VirtualBox

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

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

Main/Console: clean up CFGM handling for medium attachments, make one implementation out of 2.5 previous ones

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 253.1 KB
Line 
1/* $Id: ConsoleImpl.cpp 28727 2010-04-26 07:37:29Z 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
3093 /* protect mpVM */
3094 AutoVMCaller autoVMCaller(this);
3095 AssertComRCReturnRC(autoVMCaller.rc());
3096
3097 /*
3098 * Call worker in EMT, that's faster and safer than doing everything
3099 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3100 * here to make requests from under the lock in order to serialize them.
3101 */
3102 PVMREQ pReq;
3103 int vrc = VMR3ReqCall(mpVM, VMCPUID_ANY, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
3104 (PFNRT)Console::changeRemovableMedium, 6,
3105 this, pszDevice, uInstance, enmBus, aMediumAttachment, fForce);
3106
3107 /* leave the lock before waiting for a result (EMT will call us back!) */
3108 alock.leave();
3109
3110 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
3111 {
3112 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3113 AssertRC(vrc);
3114 if (RT_SUCCESS(vrc))
3115 vrc = pReq->iStatus;
3116 }
3117 VMR3ReqFree(pReq);
3118
3119 if (RT_SUCCESS(vrc))
3120 {
3121 LogFlowThisFunc(("Returns S_OK\n"));
3122 return S_OK;
3123 }
3124
3125 if (!pMedium)
3126 return setError(E_FAIL,
3127 tr("Could not mount the media/drive '%ls' (%Rrc)"),
3128 mediumLocation.raw(), vrc);
3129
3130 return setError(E_FAIL,
3131 tr("Could not unmount the currently mounted media/drive (%Rrc)"),
3132 vrc);
3133}
3134
3135/**
3136 * Performs the medium change in EMT.
3137 *
3138 * @returns VBox status code.
3139 *
3140 * @param pThis Pointer to the Console object.
3141 * @param pcszDevice The PDM device name.
3142 * @param uInstance The PDM device instance.
3143 * @param uLun The PDM LUN number of the drive.
3144 * @param fHostDrive True if this is a host drive attachment.
3145 * @param pszPath The path to the media / drive which is now being mounted / captured.
3146 * If NULL no media or drive is attached and the LUN will be configured with
3147 * the default block driver with no media. This will also be the state if
3148 * mounting / capturing the specified media / drive fails.
3149 * @param pszFormat Medium format string, usually "RAW".
3150 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
3151 *
3152 * @thread EMT
3153 */
3154DECLCALLBACK(int) Console::changeRemovableMedium(Console *pThis,
3155 const char *pcszDevice,
3156 unsigned uInstance,
3157 StorageBus_T enmBus,
3158 IMediumAttachment *aMediumAtt,
3159 bool fForce)
3160{
3161 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p, fForce=%d\n",
3162 pThis, uInstance, pcszDevice, enmBus, fForce));
3163
3164 AssertReturn(pThis, VERR_INVALID_PARAMETER);
3165
3166 AutoCaller autoCaller(pThis);
3167 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3168
3169 PVM pVM = pThis->mpVM;
3170
3171 /*
3172 * Suspend the VM first.
3173 *
3174 * The VM must not be running since it might have pending I/O to
3175 * the drive which is being changed.
3176 */
3177 bool fResume;
3178 VMSTATE enmVMState = VMR3GetState(pVM);
3179 switch (enmVMState)
3180 {
3181 case VMSTATE_RESETTING:
3182 case VMSTATE_RUNNING:
3183 {
3184 LogFlowFunc(("Suspending the VM...\n"));
3185 /* disable the callback to prevent Console-level state change */
3186 pThis->mVMStateChangeCallbackDisabled = true;
3187 int rc = VMR3Suspend(pVM);
3188 pThis->mVMStateChangeCallbackDisabled = false;
3189 AssertRCReturn(rc, rc);
3190 fResume = true;
3191 break;
3192 }
3193
3194 case VMSTATE_SUSPENDED:
3195 case VMSTATE_CREATED:
3196 case VMSTATE_OFF:
3197 fResume = false;
3198 break;
3199
3200 case VMSTATE_RUNNING_LS:
3201 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot change drive during live migration"));
3202
3203 default:
3204 AssertMsgFailedReturn(("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
3205 }
3206
3207 /* Determine the base path for the device instance. */
3208 PCFGMNODE pCtlInst;
3209 pCtlInst = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/%s/%u/", pcszDevice,
3210 uInstance);
3211 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
3212
3213 int rc = VINF_SUCCESS;
3214 int rcRet = VINF_SUCCESS;
3215
3216 rcRet = Console::configMediumAttachment(pCtlInst, pcszDevice, uInstance,
3217 enmBus, aMediumAtt,
3218 pThis->mMachineState,
3219 NULL /* phrc */,
3220 true /* fAttachDetach */,
3221 fForce /* fForceUnmount */,
3222 pVM, NULL /* paLedDevType */);
3223 /** @todo this dumps everything attached to this device instance, which
3224 * is more than necessary. Dumping the changed LUN would be enough. */
3225 CFGMR3Dump(pCtlInst);
3226
3227 /*
3228 * Resume the VM if necessary.
3229 */
3230 if (fResume)
3231 {
3232 LogFlowFunc(("Resuming the VM...\n"));
3233 /* disable the callback to prevent Console-level state change */
3234 pThis->mVMStateChangeCallbackDisabled = true;
3235 rc = VMR3Resume(pVM);
3236 pThis->mVMStateChangeCallbackDisabled = false;
3237 AssertRC(rc);
3238 if (RT_FAILURE(rc))
3239 {
3240 /* too bad, we failed. try to sync the console state with the VMM state */
3241 vmstateChangeCallback(pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
3242 }
3243 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
3244 // error (if any) will be hidden from the caller. For proper reporting
3245 // of such multiple errors to the caller we need to enhance the
3246 // IVirtualBoxError interface. For now, give the first error the higher
3247 // priority.
3248 if (RT_SUCCESS(rcRet))
3249 rcRet = rc;
3250 }
3251
3252 LogFlowFunc(("Returning %Rrc\n", rcRet));
3253 return rcRet;
3254}
3255
3256
3257/**
3258 * Called by IInternalSessionControl::OnNetworkAdapterChange().
3259 *
3260 * @note Locks this object for writing.
3261 */
3262HRESULT Console::onNetworkAdapterChange(INetworkAdapter *aNetworkAdapter, BOOL changeAdapter)
3263{
3264 LogFlowThisFunc(("\n"));
3265
3266 AutoCaller autoCaller(this);
3267 AssertComRCReturnRC(autoCaller.rc());
3268
3269 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3270
3271 /* Don't do anything if the VM isn't running */
3272 if (!mpVM)
3273 return S_OK;
3274
3275 /* protect mpVM */
3276 AutoVMCaller autoVMCaller(this);
3277 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3278
3279 /* Get the properties we need from the adapter */
3280 BOOL fCableConnected, fTraceEnabled;
3281 HRESULT rc = aNetworkAdapter->COMGETTER(CableConnected)(&fCableConnected);
3282 AssertComRC(rc);
3283 if (SUCCEEDED(rc))
3284 {
3285 rc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fTraceEnabled);
3286 AssertComRC(rc);
3287 }
3288 if (SUCCEEDED(rc))
3289 {
3290 ULONG ulInstance;
3291 rc = aNetworkAdapter->COMGETTER(Slot)(&ulInstance);
3292 AssertComRC(rc);
3293 if (SUCCEEDED(rc))
3294 {
3295 /*
3296 * Find the pcnet instance, get the config interface and update
3297 * the link state.
3298 */
3299 NetworkAdapterType_T adapterType;
3300 rc = aNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
3301 AssertComRC(rc);
3302 const char *pszAdapterName = NULL;
3303 switch (adapterType)
3304 {
3305 case NetworkAdapterType_Am79C970A:
3306 case NetworkAdapterType_Am79C973:
3307 pszAdapterName = "pcnet";
3308 break;
3309#ifdef VBOX_WITH_E1000
3310 case NetworkAdapterType_I82540EM:
3311 case NetworkAdapterType_I82543GC:
3312 case NetworkAdapterType_I82545EM:
3313 pszAdapterName = "e1000";
3314 break;
3315#endif
3316#ifdef VBOX_WITH_VIRTIO
3317 case NetworkAdapterType_Virtio:
3318 pszAdapterName = "virtio-net";
3319 break;
3320#endif
3321 default:
3322 AssertFailed();
3323 pszAdapterName = "unknown";
3324 break;
3325 }
3326
3327 PPDMIBASE pBase;
3328 int vrc = PDMR3QueryDeviceLun(mpVM, pszAdapterName, ulInstance, 0, &pBase);
3329 ComAssertRC(vrc);
3330 if (RT_SUCCESS(vrc))
3331 {
3332 Assert(pBase);
3333 PPDMINETWORKCONFIG pINetCfg;
3334 pINetCfg = PDMIBASE_QUERY_INTERFACE(pBase, PDMINETWORKCONFIG);
3335 if (pINetCfg)
3336 {
3337 Log(("Console::onNetworkAdapterChange: setting link state to %d\n",
3338 fCableConnected));
3339 vrc = pINetCfg->pfnSetLinkState(pINetCfg,
3340 fCableConnected ? PDMNETWORKLINKSTATE_UP
3341 : PDMNETWORKLINKSTATE_DOWN);
3342 ComAssertRC(vrc);
3343 }
3344#ifdef VBOX_DYNAMIC_NET_ATTACH
3345 if (RT_SUCCESS(vrc) && changeAdapter)
3346 {
3347 VMSTATE enmVMState = VMR3GetState(mpVM);
3348 if ( enmVMState == VMSTATE_RUNNING /** @todo LiveMigration: Forbit or deal correctly with the _LS variants */
3349 || enmVMState == VMSTATE_SUSPENDED)
3350 {
3351 if (fTraceEnabled && fCableConnected && pINetCfg)
3352 {
3353 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_DOWN);
3354 ComAssertRC(vrc);
3355 }
3356
3357 rc = doNetworkAdapterChange(pszAdapterName, ulInstance, 0, aNetworkAdapter);
3358
3359 if (fTraceEnabled && fCableConnected && pINetCfg)
3360 {
3361 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_UP);
3362 ComAssertRC(vrc);
3363 }
3364 }
3365 }
3366#endif /* VBOX_DYNAMIC_NET_ATTACH */
3367 }
3368
3369 if (RT_FAILURE(vrc))
3370 rc = E_FAIL;
3371 }
3372 }
3373
3374 /* notify console callbacks on success */
3375 if (SUCCEEDED(rc))
3376 {
3377 CallbackList::iterator it = mCallbacks.begin();
3378 while (it != mCallbacks.end())
3379 (*it++)->OnNetworkAdapterChange(aNetworkAdapter);
3380 }
3381
3382 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
3383 return rc;
3384}
3385
3386
3387#ifdef VBOX_DYNAMIC_NET_ATTACH
3388/**
3389 * Process a network adaptor change.
3390 *
3391 * @returns COM status code.
3392 *
3393 * @param pszDevice The PDM device name.
3394 * @param uInstance The PDM device instance.
3395 * @param uLun The PDM LUN number of the drive.
3396 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
3397 *
3398 * @note Locks this object for writing.
3399 */
3400HRESULT Console::doNetworkAdapterChange(const char *pszDevice,
3401 unsigned uInstance,
3402 unsigned uLun,
3403 INetworkAdapter *aNetworkAdapter)
3404{
3405 LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
3406 pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
3407
3408 AutoCaller autoCaller(this);
3409 AssertComRCReturnRC(autoCaller.rc());
3410
3411 /* We will need to release the write lock before calling EMT */
3412 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3413
3414 /* protect mpVM */
3415 AutoVMCaller autoVMCaller(this);
3416 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3417
3418 /*
3419 * Call worker in EMT, that's faster and safer than doing everything
3420 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3421 * here to make requests from under the lock in order to serialize them.
3422 */
3423 PVMREQ pReq;
3424 int vrc = VMR3ReqCall(mpVM, 0 /*idDstCpu*/, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
3425 (PFNRT) Console::changeNetworkAttachment, 5,
3426 this, pszDevice, uInstance, uLun, aNetworkAdapter);
3427
3428 /* leave the lock before waiting for a result (EMT will call us back!) */
3429 alock.leave();
3430
3431 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
3432 {
3433 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3434 AssertRC(vrc);
3435 if (RT_SUCCESS(vrc))
3436 vrc = pReq->iStatus;
3437 }
3438 VMR3ReqFree(pReq);
3439
3440 if (RT_SUCCESS(vrc))
3441 {
3442 LogFlowThisFunc(("Returns S_OK\n"));
3443 return S_OK;
3444 }
3445
3446 return setError(E_FAIL,
3447 tr("Could not change the network adaptor attachement type (%Rrc)"),
3448 vrc);
3449}
3450
3451
3452/**
3453 * Performs the Network Adaptor change in EMT.
3454 *
3455 * @returns VBox status code.
3456 *
3457 * @param pThis Pointer to the Console object.
3458 * @param pszDevice The PDM device name.
3459 * @param uInstance The PDM device instance.
3460 * @param uLun The PDM LUN number of the drive.
3461 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
3462 *
3463 * @thread EMT
3464 * @note Locks the Console object for writing.
3465 */
3466DECLCALLBACK(int) Console::changeNetworkAttachment(Console *pThis,
3467 const char *pszDevice,
3468 unsigned uInstance,
3469 unsigned uLun,
3470 INetworkAdapter *aNetworkAdapter)
3471{
3472 LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
3473 pThis, pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
3474
3475 AssertReturn(pThis, VERR_INVALID_PARAMETER);
3476
3477 AssertMsg( ( !strcmp(pszDevice, "pcnet")
3478 || !strcmp(pszDevice, "e1000")
3479 || !strcmp(pszDevice, "virtio-net"))
3480 && (uLun == 0)
3481 && (uInstance < SchemaDefs::NetworkAdapterCount),
3482 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
3483 Log(("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
3484
3485 AutoCaller autoCaller(pThis);
3486 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3487
3488 /* protect mpVM */
3489 AutoVMCaller autoVMCaller(pThis);
3490 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3491
3492 PVM pVM = pThis->mpVM;
3493
3494 /*
3495 * Suspend the VM first.
3496 *
3497 * The VM must not be running since it might have pending I/O to
3498 * the drive which is being changed.
3499 */
3500 bool fResume;
3501 VMSTATE enmVMState = VMR3GetState(pVM);
3502 switch (enmVMState)
3503 {
3504 case VMSTATE_RESETTING:
3505 case VMSTATE_RUNNING:
3506 {
3507 LogFlowFunc(("Suspending the VM...\n"));
3508 /* disable the callback to prevent Console-level state change */
3509 pThis->mVMStateChangeCallbackDisabled = true;
3510 int rc = VMR3Suspend(pVM);
3511 pThis->mVMStateChangeCallbackDisabled = false;
3512 AssertRCReturn(rc, rc);
3513 fResume = true;
3514 break;
3515 }
3516
3517 case VMSTATE_SUSPENDED:
3518 case VMSTATE_CREATED:
3519 case VMSTATE_OFF:
3520 fResume = false;
3521 break;
3522
3523 default:
3524 AssertLogRelMsgFailedReturn(("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
3525 }
3526
3527 int rc = VINF_SUCCESS;
3528 int rcRet = VINF_SUCCESS;
3529
3530 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
3531 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
3532 PCFGMNODE pInst = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/%s/%d/", pszDevice, uInstance);
3533 AssertRelease(pInst);
3534
3535 rcRet = pThis->configNetwork(pszDevice, uInstance, uLun, aNetworkAdapter, pCfg, pLunL0, pInst, true);
3536
3537 /*
3538 * Resume the VM if necessary.
3539 */
3540 if (fResume)
3541 {
3542 LogFlowFunc(("Resuming the VM...\n"));
3543 /* disable the callback to prevent Console-level state change */
3544 pThis->mVMStateChangeCallbackDisabled = true;
3545 rc = VMR3Resume(pVM);
3546 pThis->mVMStateChangeCallbackDisabled = false;
3547 AssertRC(rc);
3548 if (RT_FAILURE(rc))
3549 {
3550 /* too bad, we failed. try to sync the console state with the VMM state */
3551 vmstateChangeCallback(pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
3552 }
3553 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
3554 // error (if any) will be hidden from the caller. For proper reporting
3555 // of such multiple errors to the caller we need to enhance the
3556 // IVirtualBoxError interface. For now, give the first error the higher
3557 // priority.
3558 if (RT_SUCCESS(rcRet))
3559 rcRet = rc;
3560 }
3561
3562 LogFlowFunc(("Returning %Rrc\n", rcRet));
3563 return rcRet;
3564}
3565#endif /* VBOX_DYNAMIC_NET_ATTACH */
3566
3567
3568/**
3569 * Called by IInternalSessionControl::OnSerialPortChange().
3570 *
3571 * @note Locks this object for writing.
3572 */
3573HRESULT Console::onSerialPortChange(ISerialPort *aSerialPort)
3574{
3575 LogFlowThisFunc(("\n"));
3576
3577 AutoCaller autoCaller(this);
3578 AssertComRCReturnRC(autoCaller.rc());
3579
3580 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3581
3582 /* Don't do anything if the VM isn't running */
3583 if (!mpVM)
3584 return S_OK;
3585
3586 HRESULT rc = S_OK;
3587
3588 /* protect mpVM */
3589 AutoVMCaller autoVMCaller(this);
3590 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3591
3592 /* nothing to do so far */
3593
3594 /* notify console callbacks on success */
3595 if (SUCCEEDED(rc))
3596 {
3597 CallbackList::iterator it = mCallbacks.begin();
3598 while (it != mCallbacks.end())
3599 (*it++)->OnSerialPortChange(aSerialPort);
3600 }
3601
3602 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
3603 return rc;
3604}
3605
3606/**
3607 * Called by IInternalSessionControl::OnParallelPortChange().
3608 *
3609 * @note Locks this object for writing.
3610 */
3611HRESULT Console::onParallelPortChange(IParallelPort *aParallelPort)
3612{
3613 LogFlowThisFunc(("\n"));
3614
3615 AutoCaller autoCaller(this);
3616 AssertComRCReturnRC(autoCaller.rc());
3617
3618 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3619
3620 /* Don't do anything if the VM isn't running */
3621 if (!mpVM)
3622 return S_OK;
3623
3624 HRESULT rc = S_OK;
3625
3626 /* protect mpVM */
3627 AutoVMCaller autoVMCaller(this);
3628 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3629
3630 /* nothing to do so far */
3631
3632 /* notify console callbacks on success */
3633 if (SUCCEEDED(rc))
3634 {
3635 CallbackList::iterator it = mCallbacks.begin();
3636 while (it != mCallbacks.end())
3637 (*it++)->OnParallelPortChange(aParallelPort);
3638 }
3639
3640 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
3641 return rc;
3642}
3643
3644/**
3645 * Called by IInternalSessionControl::OnStorageControllerChange().
3646 *
3647 * @note Locks this object for writing.
3648 */
3649HRESULT Console::onStorageControllerChange()
3650{
3651 LogFlowThisFunc(("\n"));
3652
3653 AutoCaller autoCaller(this);
3654 AssertComRCReturnRC(autoCaller.rc());
3655
3656 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3657
3658 /* Don't do anything if the VM isn't running */
3659 if (!mpVM)
3660 return S_OK;
3661
3662 HRESULT rc = S_OK;
3663
3664 /* protect mpVM */
3665 AutoVMCaller autoVMCaller(this);
3666 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3667
3668 /* nothing to do so far */
3669
3670 /* notify console callbacks on success */
3671 if (SUCCEEDED(rc))
3672 {
3673 CallbackList::iterator it = mCallbacks.begin();
3674 while (it != mCallbacks.end())
3675 (*it++)->OnStorageControllerChange();
3676 }
3677
3678 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
3679 return rc;
3680}
3681
3682/**
3683 * Called by IInternalSessionControl::OnMediumChange().
3684 *
3685 * @note Locks this object for writing.
3686 */
3687HRESULT Console::onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce)
3688{
3689 LogFlowThisFunc(("\n"));
3690
3691 AutoCaller autoCaller(this);
3692 AssertComRCReturnRC(autoCaller.rc());
3693
3694 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3695
3696 /* Don't do anything if the VM isn't running */
3697 if (!mpVM)
3698 return S_OK;
3699
3700 HRESULT rc = S_OK;
3701
3702 /* protect mpVM */
3703 AutoVMCaller autoVMCaller(this);
3704 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3705
3706 rc = doMediumChange(aMediumAttachment, !!aForce);
3707
3708 /* notify console callbacks on success */
3709 if (SUCCEEDED(rc))
3710 {
3711 CallbackList::iterator it = mCallbacks.begin();
3712 while (it != mCallbacks.end())
3713 (*it++)->OnMediumChange(aMediumAttachment);
3714 }
3715
3716 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
3717 return rc;
3718}
3719
3720/**
3721 * Called by IInternalSessionControl::OnCPUChange().
3722 *
3723 * @note Locks this object for writing.
3724 */
3725HRESULT Console::onCPUChange(ULONG aCPU, BOOL aRemove)
3726{
3727 LogFlowThisFunc(("\n"));
3728
3729 AutoCaller autoCaller(this);
3730 AssertComRCReturnRC(autoCaller.rc());
3731
3732 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3733
3734 /* Don't do anything if the VM isn't running */
3735 if (!mpVM)
3736 return S_OK;
3737
3738 HRESULT rc = S_OK;
3739
3740 /* protect mpVM */
3741 AutoVMCaller autoVMCaller(this);
3742 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3743
3744 if (aRemove)
3745 rc = doCPURemove(aCPU);
3746 else
3747 rc = doCPUAdd(aCPU);
3748
3749 /* notify console callbacks on success */
3750 if (SUCCEEDED(rc))
3751 {
3752 CallbackList::iterator it = mCallbacks.begin();
3753 while (it != mCallbacks.end())
3754 (*it++)->OnCPUChange(aCPU, aRemove);
3755 }
3756
3757 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
3758 return rc;
3759}
3760
3761/**
3762 * Called by IInternalSessionControl::OnVRDPServerChange().
3763 *
3764 * @note Locks this object for writing.
3765 */
3766HRESULT Console::onVRDPServerChange()
3767{
3768 AutoCaller autoCaller(this);
3769 AssertComRCReturnRC(autoCaller.rc());
3770
3771 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3772
3773 HRESULT rc = S_OK;
3774
3775 if ( mVRDPServer
3776 && ( mMachineState == MachineState_Running
3777 || mMachineState == MachineState_Teleporting
3778 || mMachineState == MachineState_LiveSnapshotting
3779 )
3780 )
3781 {
3782 BOOL vrdpEnabled = FALSE;
3783
3784 rc = mVRDPServer->COMGETTER(Enabled)(&vrdpEnabled);
3785 ComAssertComRCRetRC(rc);
3786
3787 /* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
3788 alock.leave();
3789
3790 if (vrdpEnabled)
3791 {
3792 // If there was no VRDP server started the 'stop' will do nothing.
3793 // However if a server was started and this notification was called,
3794 // we have to restart the server.
3795 mConsoleVRDPServer->Stop();
3796
3797 if (RT_FAILURE(mConsoleVRDPServer->Launch()))
3798 {
3799 rc = E_FAIL;
3800 }
3801 else
3802 {
3803 mConsoleVRDPServer->EnableConnections();
3804 }
3805 }
3806 else
3807 {
3808 mConsoleVRDPServer->Stop();
3809 }
3810
3811 alock.enter();
3812 }
3813
3814 /* notify console callbacks on success */
3815 if (SUCCEEDED(rc))
3816 {
3817 CallbackList::iterator it = mCallbacks.begin();
3818 while (it != mCallbacks.end())
3819 (*it++)->OnVRDPServerChange();
3820 }
3821
3822 return rc;
3823}
3824
3825/**
3826 * @note Locks this object for reading.
3827 */
3828void Console::onRemoteDisplayInfoChange()
3829{
3830 AutoCaller autoCaller(this);
3831 AssertComRCReturnVoid(autoCaller.rc());
3832
3833 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3834
3835 CallbackList::iterator it = mCallbacks.begin();
3836 while (it != mCallbacks.end())
3837 (*it++)->OnRemoteDisplayInfoChange();
3838}
3839
3840
3841
3842/**
3843 * Called by IInternalSessionControl::OnUSBControllerChange().
3844 *
3845 * @note Locks this object for writing.
3846 */
3847HRESULT Console::onUSBControllerChange()
3848{
3849 LogFlowThisFunc(("\n"));
3850
3851 AutoCaller autoCaller(this);
3852 AssertComRCReturnRC(autoCaller.rc());
3853
3854 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3855
3856 /* Ignore if no VM is running yet. */
3857 if (!mpVM)
3858 return S_OK;
3859
3860 HRESULT rc = S_OK;
3861
3862/// @todo (dmik)
3863// check for the Enabled state and disable virtual USB controller??
3864// Anyway, if we want to query the machine's USB Controller we need to cache
3865// it to mUSBController in #init() (as it is done with mDVDDrive).
3866//
3867// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
3868//
3869// /* protect mpVM */
3870// AutoVMCaller autoVMCaller(this);
3871// if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
3872
3873 /* notify console callbacks on success */
3874 if (SUCCEEDED(rc))
3875 {
3876 CallbackList::iterator it = mCallbacks.begin();
3877 while (it != mCallbacks.end())
3878 (*it++)->OnUSBControllerChange();
3879 }
3880
3881 return rc;
3882}
3883
3884/**
3885 * Called by IInternalSessionControl::OnSharedFolderChange().
3886 *
3887 * @note Locks this object for writing.
3888 */
3889HRESULT Console::onSharedFolderChange(BOOL aGlobal)
3890{
3891 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
3892
3893 AutoCaller autoCaller(this);
3894 AssertComRCReturnRC(autoCaller.rc());
3895
3896 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3897
3898 HRESULT rc = fetchSharedFolders(aGlobal);
3899
3900 /* notify console callbacks on success */
3901 if (SUCCEEDED(rc))
3902 {
3903 CallbackList::iterator it = mCallbacks.begin();
3904 while (it != mCallbacks.end())
3905 (*it++)->OnSharedFolderChange(aGlobal ? (Scope_T)Scope_Global
3906 : (Scope_T)Scope_Machine);
3907 }
3908
3909 return rc;
3910}
3911
3912/**
3913 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
3914 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
3915 * returns TRUE for a given remote USB device.
3916 *
3917 * @return S_OK if the device was attached to the VM.
3918 * @return failure if not attached.
3919 *
3920 * @param aDevice
3921 * The device in question.
3922 * @param aMaskedIfs
3923 * The interfaces to hide from the guest.
3924 *
3925 * @note Locks this object for writing.
3926 */
3927HRESULT Console::onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
3928{
3929#ifdef VBOX_WITH_USB
3930 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
3931
3932 AutoCaller autoCaller(this);
3933 ComAssertComRCRetRC(autoCaller.rc());
3934
3935 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3936
3937 /* protect mpVM (we don't need error info, since it's a callback) */
3938 AutoVMCallerQuiet autoVMCaller(this);
3939 if (FAILED(autoVMCaller.rc()))
3940 {
3941 /* The VM may be no more operational when this message arrives
3942 * (e.g. it may be Saving or Stopping or just PoweredOff) --
3943 * autoVMCaller.rc() will return a failure in this case. */
3944 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
3945 mMachineState));
3946 return autoVMCaller.rc();
3947 }
3948
3949 if (aError != NULL)
3950 {
3951 /* notify callbacks about the error */
3952 onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
3953 return S_OK;
3954 }
3955
3956 /* Don't proceed unless there's at least one USB hub. */
3957 if (!PDMR3USBHasHub(mpVM))
3958 {
3959 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
3960 return E_FAIL;
3961 }
3962
3963 HRESULT rc = attachUSBDevice(aDevice, aMaskedIfs);
3964 if (FAILED(rc))
3965 {
3966 /* take the current error info */
3967 com::ErrorInfoKeeper eik;
3968 /* the error must be a VirtualBoxErrorInfo instance */
3969 ComPtr<IVirtualBoxErrorInfo> error = eik.takeError();
3970 Assert(!error.isNull());
3971 if (!error.isNull())
3972 {
3973 /* notify callbacks about the error */
3974 onUSBDeviceStateChange(aDevice, true /* aAttached */, error);
3975 }
3976 }
3977
3978 return rc;
3979
3980#else /* !VBOX_WITH_USB */
3981 return E_FAIL;
3982#endif /* !VBOX_WITH_USB */
3983}
3984
3985/**
3986 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
3987 * processRemoteUSBDevices().
3988 *
3989 * @note Locks this object for writing.
3990 */
3991HRESULT Console::onUSBDeviceDetach(IN_BSTR aId,
3992 IVirtualBoxErrorInfo *aError)
3993{
3994#ifdef VBOX_WITH_USB
3995 Guid Uuid(aId);
3996 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
3997
3998 AutoCaller autoCaller(this);
3999 AssertComRCReturnRC(autoCaller.rc());
4000
4001 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4002
4003 /* Find the device. */
4004 ComObjPtr<OUSBDevice> device;
4005 USBDeviceList::iterator it = mUSBDevices.begin();
4006 while (it != mUSBDevices.end())
4007 {
4008 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->id().raw()));
4009 if ((*it)->id() == Uuid)
4010 {
4011 device = *it;
4012 break;
4013 }
4014 ++ it;
4015 }
4016
4017
4018 if (device.isNull())
4019 {
4020 LogFlowThisFunc(("USB device not found.\n"));
4021
4022 /* The VM may be no more operational when this message arrives
4023 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
4024 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
4025 * failure in this case. */
4026
4027 AutoVMCallerQuiet autoVMCaller(this);
4028 if (FAILED(autoVMCaller.rc()))
4029 {
4030 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
4031 mMachineState));
4032 return autoVMCaller.rc();
4033 }
4034
4035 /* the device must be in the list otherwise */
4036 AssertFailedReturn(E_FAIL);
4037 }
4038
4039 if (aError != NULL)
4040 {
4041 /* notify callback about an error */
4042 onUSBDeviceStateChange(device, false /* aAttached */, aError);
4043 return S_OK;
4044 }
4045
4046 HRESULT rc = detachUSBDevice(it);
4047
4048 if (FAILED(rc))
4049 {
4050 /* take the current error info */
4051 com::ErrorInfoKeeper eik;
4052 /* the error must be a VirtualBoxErrorInfo instance */
4053 ComPtr<IVirtualBoxErrorInfo> error = eik.takeError();
4054 Assert(!error.isNull());
4055 if (!error.isNull())
4056 {
4057 /* notify callbacks about the error */
4058 onUSBDeviceStateChange(device, false /* aAttached */, error);
4059 }
4060 }
4061
4062 return rc;
4063
4064#else /* !VBOX_WITH_USB */
4065 return E_FAIL;
4066#endif /* !VBOX_WITH_USB */
4067}
4068
4069/**
4070 * @note Temporarily locks this object for writing.
4071 */
4072HRESULT Console::getGuestProperty(IN_BSTR aName, BSTR *aValue,
4073 ULONG64 *aTimestamp, BSTR *aFlags)
4074{
4075#ifndef VBOX_WITH_GUEST_PROPS
4076 ReturnComNotImplemented();
4077#else /* VBOX_WITH_GUEST_PROPS */
4078 if (!VALID_PTR(aName))
4079 return E_INVALIDARG;
4080 if (!VALID_PTR(aValue))
4081 return E_POINTER;
4082 if ((aTimestamp != NULL) && !VALID_PTR(aTimestamp))
4083 return E_POINTER;
4084 if ((aFlags != NULL) && !VALID_PTR(aFlags))
4085 return E_POINTER;
4086
4087 AutoCaller autoCaller(this);
4088 AssertComRCReturnRC(autoCaller.rc());
4089
4090 /* protect mpVM (if not NULL) */
4091 AutoVMCallerWeak autoVMCaller(this);
4092 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
4093
4094 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
4095 * autoVMCaller, so there is no need to hold a lock of this */
4096
4097 HRESULT rc = E_UNEXPECTED;
4098 using namespace guestProp;
4099
4100 try
4101 {
4102 VBOXHGCMSVCPARM parm[4];
4103 Utf8Str Utf8Name = aName;
4104 char pszBuffer[MAX_VALUE_LEN + MAX_FLAGS_LEN];
4105
4106 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
4107 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
4108 /* The + 1 is the null terminator */
4109 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
4110 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
4111 parm[1].u.pointer.addr = pszBuffer;
4112 parm[1].u.pointer.size = sizeof(pszBuffer);
4113 int vrc = mVMMDev->hgcmHostCall("VBoxGuestPropSvc", GET_PROP_HOST,
4114 4, &parm[0]);
4115 /* The returned string should never be able to be greater than our buffer */
4116 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
4117 AssertLogRel(RT_FAILURE(vrc) || VBOX_HGCM_SVC_PARM_64BIT == parm[2].type);
4118 if (RT_SUCCESS(vrc) || (VERR_NOT_FOUND == vrc))
4119 {
4120 rc = S_OK;
4121 if (vrc != VERR_NOT_FOUND)
4122 {
4123 Utf8Str strBuffer(pszBuffer);
4124 strBuffer.cloneTo(aValue);
4125
4126 *aTimestamp = parm[2].u.uint64;
4127
4128 size_t iFlags = strBuffer.length() + 1;
4129 Utf8Str(pszBuffer + iFlags).cloneTo(aFlags);
4130 }
4131 else
4132 aValue = NULL;
4133 }
4134 else
4135 rc = setError(E_UNEXPECTED,
4136 tr("The service call failed with the error %Rrc"),
4137 vrc);
4138 }
4139 catch(std::bad_alloc & /*e*/)
4140 {
4141 rc = E_OUTOFMEMORY;
4142 }
4143 return rc;
4144#endif /* VBOX_WITH_GUEST_PROPS */
4145}
4146
4147/**
4148 * @note Temporarily locks this object for writing.
4149 */
4150HRESULT Console::setGuestProperty(IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
4151{
4152#ifndef VBOX_WITH_GUEST_PROPS
4153 ReturnComNotImplemented();
4154#else /* VBOX_WITH_GUEST_PROPS */
4155 if (!VALID_PTR(aName))
4156 return E_INVALIDARG;
4157 if ((aValue != NULL) && !VALID_PTR(aValue))
4158 return E_INVALIDARG;
4159 if ((aFlags != NULL) && !VALID_PTR(aFlags))
4160 return E_INVALIDARG;
4161
4162 AutoCaller autoCaller(this);
4163 AssertComRCReturnRC(autoCaller.rc());
4164
4165 /* protect mpVM (if not NULL) */
4166 AutoVMCallerWeak autoVMCaller(this);
4167 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
4168
4169 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
4170 * autoVMCaller, so there is no need to hold a lock of this */
4171
4172 HRESULT rc = E_UNEXPECTED;
4173 using namespace guestProp;
4174
4175 VBOXHGCMSVCPARM parm[3];
4176 Utf8Str Utf8Name = aName;
4177 int vrc = VINF_SUCCESS;
4178
4179 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
4180 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
4181 /* The + 1 is the null terminator */
4182 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
4183 Utf8Str Utf8Value = aValue;
4184 if (aValue != NULL)
4185 {
4186 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
4187 parm[1].u.pointer.addr = (void*)Utf8Value.c_str();
4188 /* The + 1 is the null terminator */
4189 parm[1].u.pointer.size = (uint32_t)Utf8Value.length() + 1;
4190 }
4191 Utf8Str Utf8Flags = aFlags;
4192 if (aFlags != NULL)
4193 {
4194 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
4195 parm[2].u.pointer.addr = (void*)Utf8Flags.c_str();
4196 /* The + 1 is the null terminator */
4197 parm[2].u.pointer.size = (uint32_t)Utf8Flags.length() + 1;
4198 }
4199 if ((aValue != NULL) && (aFlags != NULL))
4200 vrc = mVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_HOST,
4201 3, &parm[0]);
4202 else if (aValue != NULL)
4203 vrc = mVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_VALUE_HOST,
4204 2, &parm[0]);
4205 else
4206 vrc = mVMMDev->hgcmHostCall("VBoxGuestPropSvc", DEL_PROP_HOST,
4207 1, &parm[0]);
4208 if (RT_SUCCESS(vrc))
4209 rc = S_OK;
4210 else
4211 rc = setError(E_UNEXPECTED,
4212 tr("The service call failed with the error %Rrc"),
4213 vrc);
4214 return rc;
4215#endif /* VBOX_WITH_GUEST_PROPS */
4216}
4217
4218
4219/**
4220 * @note Temporarily locks this object for writing.
4221 */
4222HRESULT Console::enumerateGuestProperties(IN_BSTR aPatterns,
4223 ComSafeArrayOut(BSTR, aNames),
4224 ComSafeArrayOut(BSTR, aValues),
4225 ComSafeArrayOut(ULONG64, aTimestamps),
4226 ComSafeArrayOut(BSTR, aFlags))
4227{
4228#ifndef VBOX_WITH_GUEST_PROPS
4229 ReturnComNotImplemented();
4230#else /* VBOX_WITH_GUEST_PROPS */
4231 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
4232 return E_POINTER;
4233 if (ComSafeArrayOutIsNull(aNames))
4234 return E_POINTER;
4235 if (ComSafeArrayOutIsNull(aValues))
4236 return E_POINTER;
4237 if (ComSafeArrayOutIsNull(aTimestamps))
4238 return E_POINTER;
4239 if (ComSafeArrayOutIsNull(aFlags))
4240 return E_POINTER;
4241
4242 AutoCaller autoCaller(this);
4243 AssertComRCReturnRC(autoCaller.rc());
4244
4245 /* protect mpVM (if not NULL) */
4246 AutoVMCallerWeak autoVMCaller(this);
4247 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
4248
4249 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
4250 * autoVMCaller, so there is no need to hold a lock of this */
4251
4252 return doEnumerateGuestProperties(aPatterns, ComSafeArrayOutArg(aNames),
4253 ComSafeArrayOutArg(aValues),
4254 ComSafeArrayOutArg(aTimestamps),
4255 ComSafeArrayOutArg(aFlags));
4256#endif /* VBOX_WITH_GUEST_PROPS */
4257}
4258
4259/**
4260 * Gets called by Session::UpdateMachineState()
4261 * (IInternalSessionControl::updateMachineState()).
4262 *
4263 * Must be called only in certain cases (see the implementation).
4264 *
4265 * @note Locks this object for writing.
4266 */
4267HRESULT Console::updateMachineState(MachineState_T aMachineState)
4268{
4269 AutoCaller autoCaller(this);
4270 AssertComRCReturnRC(autoCaller.rc());
4271
4272 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4273
4274 AssertReturn( mMachineState == MachineState_Saving
4275 || mMachineState == MachineState_LiveSnapshotting
4276 || mMachineState == MachineState_RestoringSnapshot
4277 || mMachineState == MachineState_DeletingSnapshot
4278 , E_FAIL);
4279
4280 return setMachineStateLocally(aMachineState);
4281}
4282
4283/**
4284 * @note Locks this object for writing.
4285 */
4286void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
4287 uint32_t xHot, uint32_t yHot,
4288 uint32_t width, uint32_t height,
4289 void *pShape)
4290{
4291#if 0
4292 LogFlowThisFuncEnter();
4293 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
4294 fVisible, fAlpha, xHot, yHot, width, height, pShape));
4295#endif
4296
4297 AutoCaller autoCaller(this);
4298 AssertComRCReturnVoid(autoCaller.rc());
4299
4300 /* We need a write lock because we alter the cached callback data */
4301 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4302
4303 /* Save the callback arguments */
4304 mCallbackData.mpsc.visible = fVisible;
4305 mCallbackData.mpsc.alpha = fAlpha;
4306 mCallbackData.mpsc.xHot = xHot;
4307 mCallbackData.mpsc.yHot = yHot;
4308 mCallbackData.mpsc.width = width;
4309 mCallbackData.mpsc.height = height;
4310
4311 /* start with not valid */
4312 bool wasValid = mCallbackData.mpsc.valid;
4313 mCallbackData.mpsc.valid = false;
4314
4315 if (pShape != NULL)
4316 {
4317 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
4318 cb = ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
4319 /* try to reuse the old shape buffer if the size is the same */
4320 if (!wasValid)
4321 mCallbackData.mpsc.shape = NULL;
4322 else
4323 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
4324 {
4325 RTMemFree(mCallbackData.mpsc.shape);
4326 mCallbackData.mpsc.shape = NULL;
4327 }
4328 if (mCallbackData.mpsc.shape == NULL)
4329 {
4330 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ(cb);
4331 AssertReturnVoid(mCallbackData.mpsc.shape);
4332 }
4333 mCallbackData.mpsc.shapeSize = cb;
4334 memcpy(mCallbackData.mpsc.shape, pShape, cb);
4335 }
4336 else
4337 {
4338 if (wasValid && mCallbackData.mpsc.shape != NULL)
4339 RTMemFree(mCallbackData.mpsc.shape);
4340 mCallbackData.mpsc.shape = NULL;
4341 mCallbackData.mpsc.shapeSize = 0;
4342 }
4343
4344 mCallbackData.mpsc.valid = true;
4345
4346 CallbackList::iterator it = mCallbacks.begin();
4347 while (it != mCallbacks.end())
4348 (*it++)->OnMousePointerShapeChange(fVisible, fAlpha, xHot, yHot,
4349 width, height, (BYTE *) pShape);
4350
4351#if 0
4352 LogFlowThisFuncLeave();
4353#endif
4354}
4355
4356/**
4357 * @note Locks this object for writing.
4358 */
4359void Console::onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative, BOOL needsHostCursor)
4360{
4361 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
4362 supportsAbsolute, supportsRelative, needsHostCursor));
4363
4364 AutoCaller autoCaller(this);
4365 AssertComRCReturnVoid(autoCaller.rc());
4366
4367 /* We need a write lock because we alter the cached callback data */
4368 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4369
4370 /* save the callback arguments */
4371 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
4372 mCallbackData.mcc.supportsRelative = supportsRelative;
4373 mCallbackData.mcc.needsHostCursor = needsHostCursor;
4374 mCallbackData.mcc.valid = true;
4375
4376 CallbackList::iterator it = mCallbacks.begin();
4377 while (it != mCallbacks.end())
4378 {
4379 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
4380 (*it++)->OnMouseCapabilityChange(supportsAbsolute, supportsRelative, needsHostCursor);
4381 }
4382}
4383
4384/**
4385 * @note Locks this object for reading.
4386 */
4387void Console::onStateChange(MachineState_T machineState)
4388{
4389 AutoCaller autoCaller(this);
4390 AssertComRCReturnVoid(autoCaller.rc());
4391
4392 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4393
4394 CallbackList::iterator it = mCallbacks.begin();
4395 while (it != mCallbacks.end())
4396 (*it++)->OnStateChange(machineState);
4397}
4398
4399/**
4400 * @note Locks this object for reading.
4401 */
4402void Console::onAdditionsStateChange()
4403{
4404 AutoCaller autoCaller(this);
4405 AssertComRCReturnVoid(autoCaller.rc());
4406
4407 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4408
4409 CallbackList::iterator it = mCallbacks.begin();
4410 while (it != mCallbacks.end())
4411 (*it++)->OnAdditionsStateChange();
4412}
4413
4414/**
4415 * @note Locks this object for reading.
4416 */
4417void Console::onAdditionsOutdated()
4418{
4419 AutoCaller autoCaller(this);
4420 AssertComRCReturnVoid(autoCaller.rc());
4421
4422 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4423
4424 /** @todo Use the On-Screen Display feature to report the fact.
4425 * The user should be told to install additions that are
4426 * provided with the current VBox build:
4427 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
4428 */
4429}
4430
4431/**
4432 * @note Locks this object for writing.
4433 */
4434void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
4435{
4436 AutoCaller autoCaller(this);
4437 AssertComRCReturnVoid(autoCaller.rc());
4438
4439 /* We need a write lock because we alter the cached callback data */
4440 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4441
4442 /* save the callback arguments */
4443 mCallbackData.klc.numLock = fNumLock;
4444 mCallbackData.klc.capsLock = fCapsLock;
4445 mCallbackData.klc.scrollLock = fScrollLock;
4446 mCallbackData.klc.valid = true;
4447
4448 CallbackList::iterator it = mCallbacks.begin();
4449 while (it != mCallbacks.end())
4450 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
4451}
4452
4453/**
4454 * @note Locks this object for reading.
4455 */
4456void Console::onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
4457 IVirtualBoxErrorInfo *aError)
4458{
4459 AutoCaller autoCaller(this);
4460 AssertComRCReturnVoid(autoCaller.rc());
4461
4462 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4463
4464 CallbackList::iterator it = mCallbacks.begin();
4465 while (it != mCallbacks.end())
4466 (*it++)->OnUSBDeviceStateChange(aDevice, aAttached, aError);
4467}
4468
4469/**
4470 * @note Locks this object for reading.
4471 */
4472void Console::onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
4473{
4474 AutoCaller autoCaller(this);
4475 AssertComRCReturnVoid(autoCaller.rc());
4476
4477 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4478
4479 CallbackList::iterator it = mCallbacks.begin();
4480 while (it != mCallbacks.end())
4481 (*it++)->OnRuntimeError(aFatal, aErrorID, aMessage);
4482}
4483
4484/**
4485 * @note Locks this object for reading.
4486 */
4487HRESULT Console::onShowWindow(BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
4488{
4489 AssertReturn(aCanShow, E_POINTER);
4490 AssertReturn(aWinId, E_POINTER);
4491
4492 *aCanShow = FALSE;
4493 *aWinId = 0;
4494
4495 AutoCaller autoCaller(this);
4496 AssertComRCReturnRC(autoCaller.rc());
4497
4498 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4499
4500 HRESULT rc = S_OK;
4501 CallbackList::iterator it = mCallbacks.begin();
4502
4503 if (aCheck)
4504 {
4505 while (it != mCallbacks.end())
4506 {
4507 BOOL canShow = FALSE;
4508 rc = (*it++)->OnCanShowWindow(&canShow);
4509 AssertComRC(rc);
4510 if (FAILED(rc) || !canShow)
4511 return rc;
4512 }
4513 *aCanShow = TRUE;
4514 }
4515 else
4516 {
4517 while (it != mCallbacks.end())
4518 {
4519 ULONG64 winId = 0;
4520 rc = (*it++)->OnShowWindow(&winId);
4521 AssertComRC(rc);
4522 if (FAILED(rc))
4523 return rc;
4524 /* only one callback may return non-null winId */
4525 Assert(*aWinId == 0 || winId == 0);
4526 if (*aWinId == 0)
4527 *aWinId = winId;
4528 }
4529 }
4530
4531 return S_OK;
4532}
4533
4534// private methods
4535////////////////////////////////////////////////////////////////////////////////
4536
4537/**
4538 * Increases the usage counter of the mpVM pointer. Guarantees that
4539 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
4540 * is called.
4541 *
4542 * If this method returns a failure, the caller is not allowed to use mpVM
4543 * and may return the failed result code to the upper level. This method sets
4544 * the extended error info on failure if \a aQuiet is false.
4545 *
4546 * Setting \a aQuiet to true is useful for methods that don't want to return
4547 * the failed result code to the caller when this method fails (e.g. need to
4548 * silently check for the mpVM availability).
4549 *
4550 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
4551 * returned instead of asserting. Having it false is intended as a sanity check
4552 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
4553 *
4554 * @param aQuiet true to suppress setting error info
4555 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
4556 * (otherwise this method will assert if mpVM is NULL)
4557 *
4558 * @note Locks this object for writing.
4559 */
4560HRESULT Console::addVMCaller(bool aQuiet /* = false */,
4561 bool aAllowNullVM /* = false */)
4562{
4563 AutoCaller autoCaller(this);
4564 AssertComRCReturnRC(autoCaller.rc());
4565
4566 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4567
4568 if (mVMDestroying)
4569 {
4570 /* powerDown() is waiting for all callers to finish */
4571 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
4572 tr("Virtual machine is being powered down"));
4573 }
4574
4575 if (mpVM == NULL)
4576 {
4577 Assert(aAllowNullVM == true);
4578
4579 /* The machine is not powered up */
4580 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
4581 tr("Virtual machine is not powered up"));
4582 }
4583
4584 ++ mVMCallers;
4585
4586 return S_OK;
4587}
4588
4589/**
4590 * Decreases the usage counter of the mpVM pointer. Must always complete
4591 * the addVMCaller() call after the mpVM pointer is no more necessary.
4592 *
4593 * @note Locks this object for writing.
4594 */
4595void Console::releaseVMCaller()
4596{
4597 AutoCaller autoCaller(this);
4598 AssertComRCReturnVoid(autoCaller.rc());
4599
4600 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4601
4602 AssertReturnVoid(mpVM != NULL);
4603
4604 Assert(mVMCallers > 0);
4605 --mVMCallers;
4606
4607 if (mVMCallers == 0 && mVMDestroying)
4608 {
4609 /* inform powerDown() there are no more callers */
4610 RTSemEventSignal(mVMZeroCallersSem);
4611 }
4612}
4613
4614/**
4615 * Initialize the release logging facility. In case something
4616 * goes wrong, there will be no release logging. Maybe in the future
4617 * we can add some logic to use different file names in this case.
4618 * Note that the logic must be in sync with Machine::DeleteSettings().
4619 */
4620HRESULT Console::consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
4621{
4622 HRESULT hrc = S_OK;
4623
4624 Bstr logFolder;
4625 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
4626 if (FAILED(hrc)) return hrc;
4627
4628 Utf8Str logDir = logFolder;
4629
4630 /* make sure the Logs folder exists */
4631 Assert(logDir.length());
4632 if (!RTDirExists(logDir.c_str()))
4633 RTDirCreateFullPath(logDir.c_str(), 0777);
4634
4635 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
4636 logDir.raw(), RTPATH_DELIMITER);
4637 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
4638 logDir.raw(), RTPATH_DELIMITER);
4639
4640 /*
4641 * Age the old log files
4642 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
4643 * Overwrite target files in case they exist.
4644 */
4645 ComPtr<IVirtualBox> virtualBox;
4646 aMachine->COMGETTER(Parent)(virtualBox.asOutParam());
4647 ComPtr<ISystemProperties> systemProperties;
4648 virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4649 ULONG cHistoryFiles = 3;
4650 systemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
4651 if (cHistoryFiles)
4652 {
4653 for (int i = cHistoryFiles-1; i >= 0; i--)
4654 {
4655 Utf8Str *files[] = { &logFile, &pngFile };
4656 Utf8Str oldName, newName;
4657
4658 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++ j)
4659 {
4660 if (i > 0)
4661 oldName = Utf8StrFmt("%s.%d", files[j]->raw(), i);
4662 else
4663 oldName = *files[j];
4664 newName = Utf8StrFmt("%s.%d", files[j]->raw(), i + 1);
4665 /* If the old file doesn't exist, delete the new file (if it
4666 * exists) to provide correct rotation even if the sequence is
4667 * broken */
4668 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
4669 == VERR_FILE_NOT_FOUND)
4670 RTFileDelete(newName.c_str());
4671 }
4672 }
4673 }
4674
4675 PRTLOGGER loggerRelease;
4676 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
4677 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
4678#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
4679 fFlags |= RTLOGFLAGS_USECRLF;
4680#endif
4681 char szError[RTPATH_MAX + 128] = "";
4682 int vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
4683 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
4684 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
4685 if (RT_SUCCESS(vrc))
4686 {
4687 /* some introductory information */
4688 RTTIMESPEC timeSpec;
4689 char szTmp[256];
4690 RTTimeSpecToString(RTTimeNow(&timeSpec), szTmp, sizeof(szTmp));
4691 RTLogRelLogger(loggerRelease, 0, ~0U,
4692 "VirtualBox %s r%u %s (%s %s) release log\n"
4693#ifdef VBOX_BLEEDING_EDGE
4694 "EXPERIMENTAL build " VBOX_BLEEDING_EDGE "\n"
4695#endif
4696 "Log opened %s\n",
4697 VBOX_VERSION_STRING, RTBldCfgRevision(), VBOX_BUILD_TARGET,
4698 __DATE__, __TIME__, szTmp);
4699
4700 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
4701 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4702 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Product: %s\n", szTmp);
4703 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
4704 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4705 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Release: %s\n", szTmp);
4706 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
4707 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4708 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Version: %s\n", szTmp);
4709 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
4710 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4711 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Service Pack: %s\n", szTmp);
4712
4713 ComPtr<IHost> host;
4714 virtualBox->COMGETTER(Host)(host.asOutParam());
4715 ULONG cMbHostRam = 0;
4716 ULONG cMbHostRamAvail = 0;
4717 host->COMGETTER(MemorySize)(&cMbHostRam);
4718 host->COMGETTER(MemoryAvailable)(&cMbHostRamAvail);
4719 RTLogRelLogger(loggerRelease, 0, ~0U, "Host RAM: %uMB RAM, available: %uMB\n",
4720 cMbHostRam, cMbHostRamAvail);
4721
4722 /* the package type is interesting for Linux distributions */
4723 char szExecName[RTPATH_MAX];
4724 char *pszExecName = RTProcGetExecutableName(szExecName, sizeof(szExecName));
4725 RTLogRelLogger(loggerRelease, 0, ~0U,
4726 "Executable: %s\n"
4727 "Process ID: %u\n"
4728 "Package type: %s"
4729#ifdef VBOX_OSE
4730 " (OSE)"
4731#endif
4732 "\n",
4733 pszExecName ? pszExecName : "unknown",
4734 RTProcSelf(),
4735 VBOX_PACKAGE_STRING);
4736
4737 /* register this logger as the release logger */
4738 RTLogRelSetDefaultInstance(loggerRelease);
4739 hrc = S_OK;
4740
4741 /* Explicitly flush the log in case of VBOX_RELEASE_LOG=buffered. */
4742 RTLogFlush(loggerRelease);
4743 }
4744 else
4745 hrc = setError(E_FAIL,
4746 tr("Failed to open release log (%s, %Rrc)"),
4747 szError, vrc);
4748
4749 /* If we've made any directory changes, flush the directory to increase
4750 the likelyhood that the log file will be usable after a system panic.
4751
4752 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
4753 is missing. Just don't have too high hopes for this to help. */
4754 if (SUCCEEDED(hrc) || cHistoryFiles)
4755 RTDirFlush(logDir.c_str());
4756
4757 return hrc;
4758}
4759
4760/**
4761 * Common worker for PowerUp and PowerUpPaused.
4762 *
4763 * @returns COM status code.
4764 *
4765 * @param aProgress Where to return the progress object.
4766 * @param aPaused true if PowerUpPaused called.
4767 *
4768 * @todo move down to powerDown();
4769 */
4770HRESULT Console::powerUp(IProgress **aProgress, bool aPaused)
4771{
4772 if (aProgress == NULL)
4773 return E_POINTER;
4774
4775 LogFlowThisFuncEnter();
4776 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
4777
4778 AutoCaller autoCaller(this);
4779 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4780
4781 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4782
4783 if (Global::IsOnlineOrTransient(mMachineState))
4784 return setError(VBOX_E_INVALID_VM_STATE,
4785 tr("Virtual machine is already running or busy (machine state: %s)"),
4786 Global::stringifyMachineState(mMachineState));
4787
4788 HRESULT rc = S_OK;
4789
4790 /* the network cards will undergo a quick consistency check */
4791 for (ULONG slot = 0;
4792 slot < SchemaDefs::NetworkAdapterCount;
4793 ++slot)
4794 {
4795 ComPtr<INetworkAdapter> adapter;
4796 mMachine->GetNetworkAdapter(slot, adapter.asOutParam());
4797 BOOL enabled = FALSE;
4798 adapter->COMGETTER(Enabled)(&enabled);
4799 if (!enabled)
4800 continue;
4801
4802 NetworkAttachmentType_T netattach;
4803 adapter->COMGETTER(AttachmentType)(&netattach);
4804 switch (netattach)
4805 {
4806 case NetworkAttachmentType_Bridged:
4807 {
4808#ifdef RT_OS_WINDOWS
4809 /* a valid host interface must have been set */
4810 Bstr hostif;
4811 adapter->COMGETTER(HostInterface)(hostif.asOutParam());
4812 if (!hostif)
4813 {
4814 return setError(VBOX_E_HOST_ERROR,
4815 tr("VM cannot start because host interface networking requires a host interface name to be set"));
4816 }
4817 ComPtr<IVirtualBox> virtualBox;
4818 mMachine->COMGETTER(Parent)(virtualBox.asOutParam());
4819 ComPtr<IHost> host;
4820 virtualBox->COMGETTER(Host)(host.asOutParam());
4821 ComPtr<IHostNetworkInterface> hostInterface;
4822 if (!SUCCEEDED(host->FindHostNetworkInterfaceByName(hostif, hostInterface.asOutParam())))
4823 {
4824 return setError(VBOX_E_HOST_ERROR,
4825 tr("VM cannot start because the host interface '%ls' does not exist"),
4826 hostif.raw());
4827 }
4828#endif /* RT_OS_WINDOWS */
4829 break;
4830 }
4831 default:
4832 break;
4833 }
4834 }
4835
4836 /* Read console data stored in the saved state file (if not yet done) */
4837 rc = loadDataFromSavedState();
4838 if (FAILED(rc)) return rc;
4839
4840 /* Check all types of shared folders and compose a single list */
4841 SharedFolderDataMap sharedFolders;
4842 {
4843 /* first, insert global folders */
4844 for (SharedFolderDataMap::const_iterator it = mGlobalSharedFolders.begin();
4845 it != mGlobalSharedFolders.end(); ++ it)
4846 sharedFolders[it->first] = it->second;
4847
4848 /* second, insert machine folders */
4849 for (SharedFolderDataMap::const_iterator it = mMachineSharedFolders.begin();
4850 it != mMachineSharedFolders.end(); ++ it)
4851 sharedFolders[it->first] = it->second;
4852
4853 /* third, insert console folders */
4854 for (SharedFolderMap::const_iterator it = mSharedFolders.begin();
4855 it != mSharedFolders.end(); ++ it)
4856 sharedFolders[it->first] = SharedFolderData(it->second->getHostPath(), it->second->isWritable());
4857 }
4858
4859 Bstr savedStateFile;
4860
4861 /*
4862 * Saved VMs will have to prove that their saved states seem kosher.
4863 */
4864 if (mMachineState == MachineState_Saved)
4865 {
4866 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
4867 if (FAILED(rc)) return rc;
4868 ComAssertRet(!!savedStateFile, E_FAIL);
4869 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
4870 if (RT_FAILURE(vrc))
4871 return setError(VBOX_E_FILE_ERROR,
4872 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
4873 savedStateFile.raw(), vrc);
4874 }
4875
4876 /* test and clear the TeleporterEnabled property */
4877 BOOL fTeleporterEnabled;
4878 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
4879 if (FAILED(rc)) return rc;
4880#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
4881 if (fTeleporterEnabled)
4882 {
4883 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
4884 if (FAILED(rc)) return rc;
4885 }
4886#endif
4887
4888 /* create a progress object to track progress of this operation */
4889 ComObjPtr<Progress> powerupProgress;
4890 powerupProgress.createObject();
4891 Bstr progressDesc;
4892 if (mMachineState == MachineState_Saved)
4893 progressDesc = tr("Restoring virtual machine");
4894 else if (fTeleporterEnabled)
4895 progressDesc = tr("Teleporting virtual machine");
4896 else
4897 progressDesc = tr("Starting virtual machine");
4898 rc = powerupProgress->init(static_cast<IConsole *>(this),
4899 progressDesc,
4900 fTeleporterEnabled /* aCancelable */);
4901 if (FAILED(rc)) return rc;
4902
4903 /* setup task object and thread to carry out the operation
4904 * asynchronously */
4905
4906 std::auto_ptr<VMPowerUpTask> task(new VMPowerUpTask(this, powerupProgress));
4907 ComAssertComRCRetRC(task->rc());
4908
4909 task->mSetVMErrorCallback = setVMErrorCallback;
4910 task->mConfigConstructor = configConstructor;
4911 task->mSharedFolders = sharedFolders;
4912 task->mStartPaused = aPaused;
4913 if (mMachineState == MachineState_Saved)
4914 task->mSavedStateFile = savedStateFile;
4915 task->mTeleporterEnabled = fTeleporterEnabled;
4916
4917 /* Reset differencing hard disks for which autoReset is true,
4918 * but only if the machine has no snapshots OR the current snapshot
4919 * is an OFFLINE snapshot; otherwise we would reset the current differencing
4920 * image of an ONLINE snapshot which contains the disk state of the machine
4921 * while it was previously running, but without the corresponding machine
4922 * state, which is equivalent to powering off a running machine and not
4923 * good idea
4924 */
4925 ComPtr<ISnapshot> pCurrentSnapshot;
4926 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
4927 if (FAILED(rc)) return rc;
4928
4929 BOOL fCurrentSnapshotIsOnline = false;
4930 if (pCurrentSnapshot)
4931 {
4932 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
4933 if (FAILED(rc)) return rc;
4934 }
4935
4936 if (!fCurrentSnapshotIsOnline)
4937 {
4938 LogFlowThisFunc(("Looking for immutable images to reset\n"));
4939
4940 com::SafeIfaceArray<IMediumAttachment> atts;
4941 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
4942 if (FAILED(rc)) return rc;
4943
4944 for (size_t i = 0;
4945 i < atts.size();
4946 ++i)
4947 {
4948 DeviceType_T devType;
4949 rc = atts[i]->COMGETTER(Type)(&devType);
4950 /** @todo later applies to floppies as well */
4951 if (devType == DeviceType_HardDisk)
4952 {
4953 ComPtr<IMedium> medium;
4954 rc = atts[i]->COMGETTER(Medium)(medium.asOutParam());
4955 if (FAILED(rc)) return rc;
4956
4957 /* needs autoreset? */
4958 BOOL autoReset = FALSE;
4959 rc = medium->COMGETTER(AutoReset)(&autoReset);
4960 if (FAILED(rc)) return rc;
4961
4962 if (autoReset)
4963 {
4964 ComPtr<IProgress> resetProgress;
4965 rc = medium->Reset(resetProgress.asOutParam());
4966 if (FAILED(rc)) return rc;
4967
4968 /* save for later use on the powerup thread */
4969 task->hardDiskProgresses.push_back(resetProgress);
4970 }
4971 }
4972 }
4973 }
4974 else
4975 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
4976
4977 rc = consoleInitReleaseLog(mMachine);
4978 if (FAILED(rc)) return rc;
4979
4980 /* pass the progress object to the caller if requested */
4981 if (aProgress)
4982 {
4983 if (task->hardDiskProgresses.size() == 0)
4984 {
4985 /* there are no other operations to track, return the powerup
4986 * progress only */
4987 powerupProgress.queryInterfaceTo(aProgress);
4988 }
4989 else
4990 {
4991 /* create a combined progress object */
4992 ComObjPtr<CombinedProgress> progress;
4993 progress.createObject();
4994 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
4995 progresses.push_back(ComPtr<IProgress> (powerupProgress));
4996 rc = progress->init(static_cast<IConsole *>(this),
4997 progressDesc, progresses.begin(),
4998 progresses.end());
4999 AssertComRCReturnRC(rc);
5000 progress.queryInterfaceTo(aProgress);
5001 }
5002 }
5003
5004 int vrc = RTThreadCreate(NULL, Console::powerUpThread, (void *) task.get(),
5005 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMPowerUp");
5006
5007 ComAssertMsgRCRet(vrc, ("Could not create VMPowerUp thread (%Rrc)", vrc),
5008 E_FAIL);
5009
5010 /* task is now owned by powerUpThread(), so release it */
5011 task.release();
5012
5013 /* finally, set the state: no right to fail in this method afterwards
5014 * since we've already started the thread and it is now responsible for
5015 * any error reporting and appropriate state change! */
5016
5017 if (mMachineState == MachineState_Saved)
5018 setMachineState(MachineState_Restoring);
5019 else if (fTeleporterEnabled)
5020 setMachineState(MachineState_TeleportingIn);
5021 else
5022 setMachineState(MachineState_Starting);
5023
5024 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
5025 LogFlowThisFuncLeave();
5026 return S_OK;
5027}
5028
5029/**
5030 * Internal power off worker routine.
5031 *
5032 * This method may be called only at certain places with the following meaning
5033 * as shown below:
5034 *
5035 * - if the machine state is either Running or Paused, a normal
5036 * Console-initiated powerdown takes place (e.g. PowerDown());
5037 * - if the machine state is Saving, saveStateThread() has successfully done its
5038 * job;
5039 * - if the machine state is Starting or Restoring, powerUpThread() has failed
5040 * to start/load the VM;
5041 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
5042 * as a result of the powerDown() call).
5043 *
5044 * Calling it in situations other than the above will cause unexpected behavior.
5045 *
5046 * Note that this method should be the only one that destroys mpVM and sets it
5047 * to NULL.
5048 *
5049 * @param aProgress Progress object to run (may be NULL).
5050 *
5051 * @note Locks this object for writing.
5052 *
5053 * @note Never call this method from a thread that called addVMCaller() or
5054 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
5055 * release(). Otherwise it will deadlock.
5056 */
5057HRESULT Console::powerDown(Progress *aProgress /*= NULL*/)
5058{
5059 LogFlowThisFuncEnter();
5060
5061 AutoCaller autoCaller(this);
5062 AssertComRCReturnRC(autoCaller.rc());
5063
5064 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5065
5066 /* Total # of steps for the progress object. Must correspond to the
5067 * number of "advance percent count" comments in this method! */
5068 enum { StepCount = 7 };
5069 /* current step */
5070 ULONG step = 0;
5071
5072 HRESULT rc = S_OK;
5073 int vrc = VINF_SUCCESS;
5074
5075 /* sanity */
5076 Assert(mVMDestroying == false);
5077
5078 Assert(mpVM != NULL);
5079
5080 AssertMsg( mMachineState == MachineState_Running
5081 || mMachineState == MachineState_Paused
5082 || mMachineState == MachineState_Stuck
5083 || mMachineState == MachineState_Starting
5084 || mMachineState == MachineState_Stopping
5085 || mMachineState == MachineState_Saving
5086 || mMachineState == MachineState_Restoring
5087 || mMachineState == MachineState_TeleportingPausedVM
5088 || mMachineState == MachineState_TeleportingIn
5089 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
5090
5091 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
5092 Global::stringifyMachineState(mMachineState), autoCaller.state() == InUninit));
5093
5094 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
5095 * VM has already powered itself off in vmstateChangeCallback() and is just
5096 * notifying Console about that. In case of Starting or Restoring,
5097 * powerUpThread() is calling us on failure, so the VM is already off at
5098 * that point. */
5099 if ( !mVMPoweredOff
5100 && ( mMachineState == MachineState_Starting
5101 || mMachineState == MachineState_Restoring
5102 || mMachineState == MachineState_TeleportingIn)
5103 )
5104 mVMPoweredOff = true;
5105
5106 /*
5107 * Go to Stopping state if not already there.
5108 *
5109 * Note that we don't go from Saving/Restoring to Stopping because
5110 * vmstateChangeCallback() needs it to set the state to Saved on
5111 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
5112 * while leaving the lock below, Saving or Restoring should be fine too.
5113 * Ditto for TeleportingPausedVM -> Teleported.
5114 */
5115 if ( mMachineState != MachineState_Saving
5116 && mMachineState != MachineState_Restoring
5117 && mMachineState != MachineState_Stopping
5118 && mMachineState != MachineState_TeleportingIn
5119 && mMachineState != MachineState_TeleportingPausedVM
5120 )
5121 setMachineState(MachineState_Stopping);
5122
5123 /* ----------------------------------------------------------------------
5124 * DONE with necessary state changes, perform the power down actions (it's
5125 * safe to leave the object lock now if needed)
5126 * ---------------------------------------------------------------------- */
5127
5128 /* Stop the VRDP server to prevent new clients connection while VM is being
5129 * powered off. */
5130 if (mConsoleVRDPServer)
5131 {
5132 LogFlowThisFunc(("Stopping VRDP server...\n"));
5133
5134 /* Leave the lock since EMT will call us back as addVMCaller()
5135 * in updateDisplayData(). */
5136 alock.leave();
5137
5138 mConsoleVRDPServer->Stop();
5139
5140 alock.enter();
5141 }
5142
5143 /* advance percent count */
5144 if (aProgress)
5145 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5146
5147
5148 /* ----------------------------------------------------------------------
5149 * Now, wait for all mpVM callers to finish their work if there are still
5150 * some on other threads. NO methods that need mpVM (or initiate other calls
5151 * that need it) may be called after this point
5152 * ---------------------------------------------------------------------- */
5153
5154 if (mVMCallers > 0)
5155 {
5156 /* go to the destroying state to prevent from adding new callers */
5157 mVMDestroying = true;
5158
5159 /* lazy creation */
5160 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
5161 RTSemEventCreate(&mVMZeroCallersSem);
5162
5163 LogFlowThisFunc(("Waiting for mpVM callers (%d) to drop to zero...\n",
5164 mVMCallers));
5165
5166 alock.leave();
5167
5168 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
5169
5170 alock.enter();
5171 }
5172
5173 /* advance percent count */
5174 if (aProgress)
5175 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5176
5177 vrc = VINF_SUCCESS;
5178
5179 /*
5180 * Power off the VM if not already done that.
5181 * Leave the lock since EMT will call vmstateChangeCallback.
5182 *
5183 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
5184 * VM-(guest-)initiated power off happened in parallel a ms before this
5185 * call. So far, we let this error pop up on the user's side.
5186 */
5187 if (!mVMPoweredOff)
5188 {
5189 LogFlowThisFunc(("Powering off the VM...\n"));
5190 alock.leave();
5191 vrc = VMR3PowerOff(mpVM);
5192 alock.enter();
5193 }
5194 else
5195 {
5196 /** @todo r=bird: Doesn't make sense. Please remove after 3.1 has been branched
5197 * off. */
5198 /* reset the flag for future re-use */
5199 mVMPoweredOff = false;
5200 }
5201
5202 /* advance percent count */
5203 if (aProgress)
5204 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5205
5206#ifdef VBOX_WITH_HGCM
5207 /* Shutdown HGCM services before destroying the VM. */
5208 if (mVMMDev)
5209 {
5210 LogFlowThisFunc(("Shutdown HGCM...\n"));
5211
5212 /* Leave the lock since EMT will call us back as addVMCaller() */
5213 alock.leave();
5214
5215 mVMMDev->hgcmShutdown();
5216
5217 alock.enter();
5218 }
5219
5220 /* advance percent count */
5221 if (aProgress)
5222 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5223
5224#endif /* VBOX_WITH_HGCM */
5225
5226 LogFlowThisFunc(("Ready for VM destruction.\n"));
5227
5228 /* If we are called from Console::uninit(), then try to destroy the VM even
5229 * on failure (this will most likely fail too, but what to do?..) */
5230 if (RT_SUCCESS(vrc) || autoCaller.state() == InUninit)
5231 {
5232 /* If the machine has an USB controller, release all USB devices
5233 * (symmetric to the code in captureUSBDevices()) */
5234 bool fHasUSBController = false;
5235 {
5236 PPDMIBASE pBase;
5237 vrc = PDMR3QueryLun(mpVM, "usb-ohci", 0, 0, &pBase);
5238 if (RT_SUCCESS(vrc))
5239 {
5240 fHasUSBController = true;
5241 detachAllUSBDevices(false /* aDone */);
5242 }
5243 }
5244
5245 /* Now we've got to destroy the VM as well. (mpVM is not valid beyond
5246 * this point). We leave the lock before calling VMR3Destroy() because
5247 * it will result into calling destructors of drivers associated with
5248 * Console children which may in turn try to lock Console (e.g. by
5249 * instantiating SafeVMPtr to access mpVM). It's safe here because
5250 * mVMDestroying is set which should prevent any activity. */
5251
5252 /* Set mpVM to NULL early just in case if some old code is not using
5253 * addVMCaller()/releaseVMCaller(). */
5254 PVM pVM = mpVM;
5255 mpVM = NULL;
5256
5257 LogFlowThisFunc(("Destroying the VM...\n"));
5258
5259 alock.leave();
5260
5261 vrc = VMR3Destroy(pVM);
5262
5263 /* take the lock again */
5264 alock.enter();
5265
5266 /* advance percent count */
5267 if (aProgress)
5268 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5269
5270 if (RT_SUCCESS(vrc))
5271 {
5272 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
5273 mMachineState));
5274 /* Note: the Console-level machine state change happens on the
5275 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
5276 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
5277 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
5278 * occurred yet. This is okay, because mMachineState is already
5279 * Stopping in this case, so any other attempt to call PowerDown()
5280 * will be rejected. */
5281 }
5282 else
5283 {
5284 /* bad bad bad, but what to do? */
5285 mpVM = pVM;
5286 rc = setError(VBOX_E_VM_ERROR,
5287 tr("Could not destroy the machine. (Error: %Rrc)"),
5288 vrc);
5289 }
5290
5291 /* Complete the detaching of the USB devices. */
5292 if (fHasUSBController)
5293 detachAllUSBDevices(true /* aDone */);
5294
5295 /* advance percent count */
5296 if (aProgress)
5297 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5298 }
5299 else
5300 {
5301 rc = setError(VBOX_E_VM_ERROR,
5302 tr("Could not power off the machine. (Error: %Rrc)"),
5303 vrc);
5304 }
5305
5306 /* Finished with destruction. Note that if something impossible happened and
5307 * we've failed to destroy the VM, mVMDestroying will remain true and
5308 * mMachineState will be something like Stopping, so most Console methods
5309 * will return an error to the caller. */
5310 if (mpVM == NULL)
5311 mVMDestroying = false;
5312
5313 if (SUCCEEDED(rc))
5314 {
5315 /* uninit dynamically allocated members of mCallbackData */
5316 if (mCallbackData.mpsc.valid)
5317 {
5318 if (mCallbackData.mpsc.shape != NULL)
5319 RTMemFree(mCallbackData.mpsc.shape);
5320 }
5321 memset(&mCallbackData, 0, sizeof(mCallbackData));
5322 }
5323
5324 /* complete the progress */
5325 if (aProgress)
5326 aProgress->notifyComplete(rc);
5327
5328 LogFlowThisFuncLeave();
5329 return rc;
5330}
5331
5332/**
5333 * @note Locks this object for writing.
5334 */
5335HRESULT Console::setMachineState(MachineState_T aMachineState,
5336 bool aUpdateServer /* = true */)
5337{
5338 AutoCaller autoCaller(this);
5339 AssertComRCReturnRC(autoCaller.rc());
5340
5341 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5342
5343 HRESULT rc = S_OK;
5344
5345 if (mMachineState != aMachineState)
5346 {
5347 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
5348 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
5349 mMachineState = aMachineState;
5350
5351 /// @todo (dmik)
5352 // possibly, we need to redo onStateChange() using the dedicated
5353 // Event thread, like it is done in VirtualBox. This will make it
5354 // much safer (no deadlocks possible if someone tries to use the
5355 // console from the callback), however, listeners will lose the
5356 // ability to synchronously react to state changes (is it really
5357 // necessary??)
5358 LogFlowThisFunc(("Doing onStateChange()...\n"));
5359 onStateChange(aMachineState);
5360 LogFlowThisFunc(("Done onStateChange()\n"));
5361
5362 if (aUpdateServer)
5363 {
5364 /* Server notification MUST be done from under the lock; otherwise
5365 * the machine state here and on the server might go out of sync
5366 * which can lead to various unexpected results (like the machine
5367 * state being >= MachineState_Running on the server, while the
5368 * session state is already SessionState_Closed at the same time
5369 * there).
5370 *
5371 * Cross-lock conditions should be carefully watched out: calling
5372 * UpdateState we will require Machine and SessionMachine locks
5373 * (remember that here we're holding the Console lock here, and also
5374 * all locks that have been entered by the thread before calling
5375 * this method).
5376 */
5377 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
5378 rc = mControl->UpdateState(aMachineState);
5379 LogFlowThisFunc(("mControl->UpdateState()=%08X\n", rc));
5380 }
5381 }
5382
5383 return rc;
5384}
5385
5386/**
5387 * Searches for a shared folder with the given logical name
5388 * in the collection of shared folders.
5389 *
5390 * @param aName logical name of the shared folder
5391 * @param aSharedFolder where to return the found object
5392 * @param aSetError whether to set the error info if the folder is
5393 * not found
5394 * @return
5395 * S_OK when found or E_INVALIDARG when not found
5396 *
5397 * @note The caller must lock this object for writing.
5398 */
5399HRESULT Console::findSharedFolder(CBSTR aName,
5400 ComObjPtr<SharedFolder> &aSharedFolder,
5401 bool aSetError /* = false */)
5402{
5403 /* sanity check */
5404 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
5405
5406 SharedFolderMap::const_iterator it = mSharedFolders.find(aName);
5407 if (it != mSharedFolders.end())
5408 {
5409 aSharedFolder = it->second;
5410 return S_OK;
5411 }
5412
5413 if (aSetError)
5414 setError(VBOX_E_FILE_ERROR,
5415 tr("Could not find a shared folder named '%ls'."),
5416 aName);
5417
5418 return VBOX_E_FILE_ERROR;
5419}
5420
5421/**
5422 * Fetches the list of global or machine shared folders from the server.
5423 *
5424 * @param aGlobal true to fetch global folders.
5425 *
5426 * @note The caller must lock this object for writing.
5427 */
5428HRESULT Console::fetchSharedFolders(BOOL aGlobal)
5429{
5430 /* sanity check */
5431 AssertReturn(AutoCaller(this).state() == InInit ||
5432 isWriteLockOnCurrentThread(), E_FAIL);
5433
5434 /* protect mpVM (if not NULL) */
5435 AutoVMCallerQuietWeak autoVMCaller(this);
5436
5437 HRESULT rc = S_OK;
5438
5439 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
5440
5441 if (aGlobal)
5442 {
5443 /// @todo grab & process global folders when they are done
5444 }
5445 else
5446 {
5447 SharedFolderDataMap oldFolders;
5448 if (online)
5449 oldFolders = mMachineSharedFolders;
5450
5451 mMachineSharedFolders.clear();
5452
5453 SafeIfaceArray<ISharedFolder> folders;
5454 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
5455 AssertComRCReturnRC(rc);
5456
5457 for (size_t i = 0; i < folders.size(); ++i)
5458 {
5459 ComPtr<ISharedFolder> folder = folders[i];
5460
5461 Bstr name;
5462 Bstr hostPath;
5463 BOOL writable;
5464
5465 rc = folder->COMGETTER(Name)(name.asOutParam());
5466 if (FAILED(rc)) break;
5467 rc = folder->COMGETTER(HostPath)(hostPath.asOutParam());
5468 if (FAILED(rc)) break;
5469 rc = folder->COMGETTER(Writable)(&writable);
5470
5471 mMachineSharedFolders.insert(std::make_pair(name, SharedFolderData(hostPath, writable)));
5472
5473 /* send changes to HGCM if the VM is running */
5474 /// @todo report errors as runtime warnings through VMSetError
5475 if (online)
5476 {
5477 SharedFolderDataMap::iterator it = oldFolders.find(name);
5478 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
5479 {
5480 /* a new machine folder is added or
5481 * the existing machine folder is changed */
5482 if (mSharedFolders.find(name) != mSharedFolders.end())
5483 ; /* the console folder exists, nothing to do */
5484 else
5485 {
5486 /* remove the old machine folder (when changed)
5487 * or the global folder if any (when new) */
5488 if (it != oldFolders.end() ||
5489 mGlobalSharedFolders.find(name) !=
5490 mGlobalSharedFolders.end())
5491 rc = removeSharedFolder(name);
5492 /* create the new machine folder */
5493 rc = createSharedFolder(name, SharedFolderData(hostPath, writable));
5494 }
5495 }
5496 /* forget the processed (or identical) folder */
5497 if (it != oldFolders.end())
5498 oldFolders.erase(it);
5499
5500 rc = S_OK;
5501 }
5502 }
5503
5504 AssertComRCReturnRC(rc);
5505
5506 /* process outdated (removed) folders */
5507 /// @todo report errors as runtime warnings through VMSetError
5508 if (online)
5509 {
5510 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
5511 it != oldFolders.end(); ++ it)
5512 {
5513 if (mSharedFolders.find(it->first) != mSharedFolders.end())
5514 ; /* the console folder exists, nothing to do */
5515 else
5516 {
5517 /* remove the outdated machine folder */
5518 rc = removeSharedFolder(it->first);
5519 /* create the global folder if there is any */
5520 SharedFolderDataMap::const_iterator git =
5521 mGlobalSharedFolders.find(it->first);
5522 if (git != mGlobalSharedFolders.end())
5523 rc = createSharedFolder(git->first, git->second);
5524 }
5525 }
5526
5527 rc = S_OK;
5528 }
5529 }
5530
5531 return rc;
5532}
5533
5534/**
5535 * Searches for a shared folder with the given name in the list of machine
5536 * shared folders and then in the list of the global shared folders.
5537 *
5538 * @param aName Name of the folder to search for.
5539 * @param aIt Where to store the pointer to the found folder.
5540 * @return @c true if the folder was found and @c false otherwise.
5541 *
5542 * @note The caller must lock this object for reading.
5543 */
5544bool Console::findOtherSharedFolder(IN_BSTR aName,
5545 SharedFolderDataMap::const_iterator &aIt)
5546{
5547 /* sanity check */
5548 AssertReturn(isWriteLockOnCurrentThread(), false);
5549
5550 /* first, search machine folders */
5551 aIt = mMachineSharedFolders.find(aName);
5552 if (aIt != mMachineSharedFolders.end())
5553 return true;
5554
5555 /* second, search machine folders */
5556 aIt = mGlobalSharedFolders.find(aName);
5557 if (aIt != mGlobalSharedFolders.end())
5558 return true;
5559
5560 return false;
5561}
5562
5563/**
5564 * Calls the HGCM service to add a shared folder definition.
5565 *
5566 * @param aName Shared folder name.
5567 * @param aHostPath Shared folder path.
5568 *
5569 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5570 * @note Doesn't lock anything.
5571 */
5572HRESULT Console::createSharedFolder(CBSTR aName, SharedFolderData aData)
5573{
5574 ComAssertRet(aName && *aName, E_FAIL);
5575 ComAssertRet(aData.mHostPath, E_FAIL);
5576
5577 /* sanity checks */
5578 AssertReturn(mpVM, E_FAIL);
5579 AssertReturn(mVMMDev->isShFlActive(), E_FAIL);
5580
5581 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
5582 SHFLSTRING *pFolderName, *pMapName;
5583 size_t cbString;
5584
5585 Log(("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
5586
5587 cbString = (RTUtf16Len(aData.mHostPath) + 1) * sizeof(RTUTF16);
5588 if (cbString >= UINT16_MAX)
5589 return setError(E_INVALIDARG, tr("The name is too long"));
5590 pFolderName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
5591 Assert(pFolderName);
5592 memcpy(pFolderName->String.ucs2, aData.mHostPath, cbString);
5593
5594 pFolderName->u16Size = (uint16_t)cbString;
5595 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5596
5597 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5598 parms[0].u.pointer.addr = pFolderName;
5599 parms[0].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
5600
5601 cbString = (RTUtf16Len(aName) + 1) * sizeof(RTUTF16);
5602 if (cbString >= UINT16_MAX)
5603 {
5604 RTMemFree(pFolderName);
5605 return setError(E_INVALIDARG, tr("The host path is too long"));
5606 }
5607 pMapName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
5608 Assert(pMapName);
5609 memcpy(pMapName->String.ucs2, aName, cbString);
5610
5611 pMapName->u16Size = (uint16_t)cbString;
5612 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5613
5614 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5615 parms[1].u.pointer.addr = pMapName;
5616 parms[1].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
5617
5618 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
5619 parms[2].u.uint32 = aData.mWritable;
5620
5621 int vrc = mVMMDev->hgcmHostCall("VBoxSharedFolders",
5622 SHFL_FN_ADD_MAPPING,
5623 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
5624 RTMemFree(pFolderName);
5625 RTMemFree(pMapName);
5626
5627 if (RT_FAILURE(vrc))
5628 return setError(E_FAIL,
5629 tr("Could not create a shared folder '%ls' mapped to '%ls' (%Rrc)"),
5630 aName, aData.mHostPath.raw(), vrc);
5631
5632 return S_OK;
5633}
5634
5635/**
5636 * Calls the HGCM service to remove the shared folder definition.
5637 *
5638 * @param aName Shared folder name.
5639 *
5640 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5641 * @note Doesn't lock anything.
5642 */
5643HRESULT Console::removeSharedFolder(CBSTR aName)
5644{
5645 ComAssertRet(aName && *aName, E_FAIL);
5646
5647 /* sanity checks */
5648 AssertReturn(mpVM, E_FAIL);
5649 AssertReturn(mVMMDev->isShFlActive(), E_FAIL);
5650
5651 VBOXHGCMSVCPARM parms;
5652 SHFLSTRING *pMapName;
5653 size_t cbString;
5654
5655 Log(("Removing shared folder '%ls'\n", aName));
5656
5657 cbString = (RTUtf16Len(aName) + 1) * sizeof(RTUTF16);
5658 if (cbString >= UINT16_MAX)
5659 return setError(E_INVALIDARG, tr("The name is too long"));
5660 pMapName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
5661 Assert(pMapName);
5662 memcpy(pMapName->String.ucs2, aName, cbString);
5663
5664 pMapName->u16Size = (uint16_t)cbString;
5665 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5666
5667 parms.type = VBOX_HGCM_SVC_PARM_PTR;
5668 parms.u.pointer.addr = pMapName;
5669 parms.u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
5670
5671 int vrc = mVMMDev->hgcmHostCall("VBoxSharedFolders",
5672 SHFL_FN_REMOVE_MAPPING,
5673 1, &parms);
5674 RTMemFree(pMapName);
5675 if (RT_FAILURE(vrc))
5676 return setError(E_FAIL,
5677 tr("Could not remove the shared folder '%ls' (%Rrc)"),
5678 aName, vrc);
5679
5680 return S_OK;
5681}
5682
5683/**
5684 * VM state callback function. Called by the VMM
5685 * using its state machine states.
5686 *
5687 * Primarily used to handle VM initiated power off, suspend and state saving,
5688 * but also for doing termination completed work (VMSTATE_TERMINATE).
5689 *
5690 * In general this function is called in the context of the EMT.
5691 *
5692 * @param aVM The VM handle.
5693 * @param aState The new state.
5694 * @param aOldState The old state.
5695 * @param aUser The user argument (pointer to the Console object).
5696 *
5697 * @note Locks the Console object for writing.
5698 */
5699DECLCALLBACK(void) Console::vmstateChangeCallback(PVM aVM,
5700 VMSTATE aState,
5701 VMSTATE aOldState,
5702 void *aUser)
5703{
5704 LogFlowFunc(("Changing state from %s to %s (aVM=%p)\n",
5705 VMR3GetStateName(aOldState), VMR3GetStateName(aState), aVM));
5706
5707 Console *that = static_cast<Console *>(aUser);
5708 AssertReturnVoid(that);
5709
5710 AutoCaller autoCaller(that);
5711
5712 /* Note that we must let this method proceed even if Console::uninit() has
5713 * been already called. In such case this VMSTATE change is a result of:
5714 * 1) powerDown() called from uninit() itself, or
5715 * 2) VM-(guest-)initiated power off. */
5716 AssertReturnVoid( autoCaller.isOk()
5717 || autoCaller.state() == InUninit);
5718
5719 switch (aState)
5720 {
5721 /*
5722 * The VM has terminated
5723 */
5724 case VMSTATE_OFF:
5725 {
5726 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5727
5728 if (that->mVMStateChangeCallbackDisabled)
5729 break;
5730
5731 /* Do we still think that it is running? It may happen if this is a
5732 * VM-(guest-)initiated shutdown/poweroff.
5733 */
5734 if ( that->mMachineState != MachineState_Stopping
5735 && that->mMachineState != MachineState_Saving
5736 && that->mMachineState != MachineState_Restoring
5737 && that->mMachineState != MachineState_TeleportingIn
5738 && that->mMachineState != MachineState_TeleportingPausedVM
5739 && !that->mVMIsAlreadyPoweringOff
5740 )
5741 {
5742 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
5743
5744 /* prevent powerDown() from calling VMR3PowerOff() again */
5745 Assert(that->mVMPoweredOff == false);
5746 that->mVMPoweredOff = true;
5747
5748 /* we are stopping now */
5749 that->setMachineState(MachineState_Stopping);
5750
5751 /* Setup task object and thread to carry out the operation
5752 * asynchronously (if we call powerDown() right here but there
5753 * is one or more mpVM callers (added with addVMCaller()) we'll
5754 * deadlock).
5755 */
5756 std::auto_ptr<VMProgressTask> task(new VMProgressTask(that, NULL /* aProgress */,
5757 true /* aUsesVMPtr */));
5758
5759 /* If creating a task is falied, this can currently mean one of
5760 * two: either Console::uninit() has been called just a ms
5761 * before (so a powerDown() call is already on the way), or
5762 * powerDown() itself is being already executed. Just do
5763 * nothing.
5764 */
5765 if (!task->isOk())
5766 {
5767 LogFlowFunc(("Console is already being uninitialized.\n"));
5768 break;
5769 }
5770
5771 int vrc = RTThreadCreate(NULL, Console::powerDownThread,
5772 (void *) task.get(), 0,
5773 RTTHREADTYPE_MAIN_WORKER, 0,
5774 "VMPowerDown");
5775 AssertMsgRCBreak(vrc, ("Could not create VMPowerDown thread (%Rrc)\n", vrc));
5776
5777 /* task is now owned by powerDownThread(), so release it */
5778 task.release();
5779 }
5780 break;
5781 }
5782
5783 /* The VM has been completely destroyed.
5784 *
5785 * Note: This state change can happen at two points:
5786 * 1) At the end of VMR3Destroy() if it was not called from EMT.
5787 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
5788 * called by EMT.
5789 */
5790 case VMSTATE_TERMINATED:
5791 {
5792 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5793
5794 if (that->mVMStateChangeCallbackDisabled)
5795 break;
5796
5797 /* Terminate host interface networking. If aVM is NULL, we've been
5798 * manually called from powerUpThread() either before calling
5799 * VMR3Create() or after VMR3Create() failed, so no need to touch
5800 * networking.
5801 */
5802 if (aVM)
5803 that->powerDownHostInterfaces();
5804
5805 /* From now on the machine is officially powered down or remains in
5806 * the Saved state.
5807 */
5808 switch (that->mMachineState)
5809 {
5810 default:
5811 AssertFailed();
5812 /* fall through */
5813 case MachineState_Stopping:
5814 /* successfully powered down */
5815 that->setMachineState(MachineState_PoweredOff);
5816 break;
5817 case MachineState_Saving:
5818 /* successfully saved (note that the machine is already in
5819 * the Saved state on the server due to EndSavingState()
5820 * called from saveStateThread(), so only change the local
5821 * state) */
5822 that->setMachineStateLocally(MachineState_Saved);
5823 break;
5824 case MachineState_Starting:
5825 /* failed to start, but be patient: set back to PoweredOff
5826 * (for similarity with the below) */
5827 that->setMachineState(MachineState_PoweredOff);
5828 break;
5829 case MachineState_Restoring:
5830 /* failed to load the saved state file, but be patient: set
5831 * back to Saved (to preserve the saved state file) */
5832 that->setMachineState(MachineState_Saved);
5833 break;
5834 case MachineState_TeleportingIn:
5835 /* Teleportation failed or was cancelled. Back to powered off. */
5836 that->setMachineState(MachineState_PoweredOff);
5837 break;
5838 case MachineState_TeleportingPausedVM:
5839 /* Successfully teleported the VM. */
5840 that->setMachineState(MachineState_Teleported);
5841 break;
5842 }
5843 break;
5844 }
5845
5846 case VMSTATE_SUSPENDED:
5847 {
5848 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5849
5850 if (that->mVMStateChangeCallbackDisabled)
5851 break;
5852
5853 switch (that->mMachineState)
5854 {
5855 case MachineState_Teleporting:
5856 that->setMachineState(MachineState_TeleportingPausedVM);
5857 break;
5858
5859 case MachineState_LiveSnapshotting:
5860 that->setMachineState(MachineState_Saving);
5861 break;
5862
5863 case MachineState_TeleportingPausedVM:
5864 case MachineState_Saving:
5865 case MachineState_Restoring:
5866 case MachineState_Stopping:
5867 case MachineState_TeleportingIn:
5868 /* The worker threads handles the transition. */
5869 break;
5870
5871 default:
5872 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
5873 case MachineState_Running:
5874 that->setMachineState(MachineState_Paused);
5875 break;
5876 }
5877 break;
5878 }
5879
5880 case VMSTATE_SUSPENDED_LS:
5881 case VMSTATE_SUSPENDED_EXT_LS:
5882 {
5883 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5884 if (that->mVMStateChangeCallbackDisabled)
5885 break;
5886 switch (that->mMachineState)
5887 {
5888 case MachineState_Teleporting:
5889 that->setMachineState(MachineState_TeleportingPausedVM);
5890 break;
5891
5892 case MachineState_LiveSnapshotting:
5893 that->setMachineState(MachineState_Saving);
5894 break;
5895
5896 case MachineState_TeleportingPausedVM:
5897 case MachineState_Saving:
5898 /* ignore */
5899 break;
5900
5901 default:
5902 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(aOldState), VMR3GetStateName(aState) ));
5903 that->setMachineState(MachineState_Paused);
5904 break;
5905 }
5906 break;
5907 }
5908
5909 case VMSTATE_RUNNING:
5910 {
5911 if ( aOldState == VMSTATE_POWERING_ON
5912 || aOldState == VMSTATE_RESUMING)
5913 {
5914 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5915
5916 if (that->mVMStateChangeCallbackDisabled)
5917 break;
5918
5919 Assert( ( ( that->mMachineState == MachineState_Starting
5920 || that->mMachineState == MachineState_Paused)
5921 && aOldState == VMSTATE_POWERING_ON)
5922 || ( ( that->mMachineState == MachineState_Restoring
5923 || that->mMachineState == MachineState_TeleportingIn
5924 || that->mMachineState == MachineState_Paused
5925 || that->mMachineState == MachineState_Saving
5926 )
5927 && aOldState == VMSTATE_RESUMING));
5928 that->setMachineState(MachineState_Running);
5929 }
5930
5931 break;
5932 }
5933
5934 case VMSTATE_RUNNING_LS:
5935 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
5936 || that->mMachineState == MachineState_Teleporting,
5937 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(aOldState), VMR3GetStateName(aState) ));
5938 break;
5939
5940 case VMSTATE_FATAL_ERROR:
5941 {
5942 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5943
5944 if (that->mVMStateChangeCallbackDisabled)
5945 break;
5946
5947 /* Fatal errors are only for running VMs. */
5948 Assert(Global::IsOnline(that->mMachineState));
5949
5950 /* Note! 'Pause' is used here in want of something better. There
5951 * are currently only two places where fatal errors might be
5952 * raised, so it is not worth adding a new externally
5953 * visible state for this yet. */
5954 that->setMachineState(MachineState_Paused);
5955 break;
5956 }
5957
5958 case VMSTATE_GURU_MEDITATION:
5959 {
5960 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5961
5962 if (that->mVMStateChangeCallbackDisabled)
5963 break;
5964
5965 /* Guru are only for running VMs */
5966 Assert(Global::IsOnline(that->mMachineState));
5967
5968 that->setMachineState(MachineState_Stuck);
5969 break;
5970 }
5971
5972 default: /* shut up gcc */
5973 break;
5974 }
5975}
5976
5977#ifdef VBOX_WITH_USB
5978
5979/**
5980 * Sends a request to VMM to attach the given host device.
5981 * After this method succeeds, the attached device will appear in the
5982 * mUSBDevices collection.
5983 *
5984 * @param aHostDevice device to attach
5985 *
5986 * @note Synchronously calls EMT.
5987 * @note Must be called from under this object's lock.
5988 */
5989HRESULT Console::attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs)
5990{
5991 AssertReturn(aHostDevice, E_FAIL);
5992 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
5993
5994 /* still want a lock object because we need to leave it */
5995 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5996
5997 HRESULT hrc;
5998
5999 /*
6000 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
6001 * method in EMT (using usbAttachCallback()).
6002 */
6003 Bstr BstrAddress;
6004 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
6005 ComAssertComRCRetRC(hrc);
6006
6007 Utf8Str Address(BstrAddress);
6008
6009 Bstr id;
6010 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
6011 ComAssertComRCRetRC(hrc);
6012 Guid uuid(id);
6013
6014 BOOL fRemote = FALSE;
6015 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
6016 ComAssertComRCRetRC(hrc);
6017
6018 /* protect mpVM */
6019 AutoVMCaller autoVMCaller(this);
6020 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
6021
6022 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
6023 Address.raw(), uuid.ptr()));
6024
6025 /* leave the lock before a VMR3* call (EMT will call us back)! */
6026 alock.leave();
6027
6028/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
6029 int vrc = VMR3ReqCallWait(mpVM, VMCPUID_ANY,
6030 (PFNRT) usbAttachCallback, 6, this, aHostDevice, uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
6031
6032 /* restore the lock */
6033 alock.enter();
6034
6035 /* hrc is S_OK here */
6036
6037 if (RT_FAILURE(vrc))
6038 {
6039 LogWarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
6040 Address.raw(), uuid.ptr(), vrc));
6041
6042 switch (vrc)
6043 {
6044 case VERR_VUSB_NO_PORTS:
6045 hrc = setError(E_FAIL,
6046 tr("Failed to attach the USB device. (No available ports on the USB controller)."));
6047 break;
6048 case VERR_VUSB_USBFS_PERMISSION:
6049 hrc = setError(E_FAIL,
6050 tr("Not permitted to open the USB device, check usbfs options"));
6051 break;
6052 default:
6053 hrc = setError(E_FAIL,
6054 tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"),
6055 vrc);
6056 break;
6057 }
6058 }
6059
6060 return hrc;
6061}
6062
6063/**
6064 * USB device attach callback used by AttachUSBDevice().
6065 * Note that AttachUSBDevice() doesn't return until this callback is executed,
6066 * so we don't use AutoCaller and don't care about reference counters of
6067 * interface pointers passed in.
6068 *
6069 * @thread EMT
6070 * @note Locks the console object for writing.
6071 */
6072//static
6073DECLCALLBACK(int)
6074Console::usbAttachCallback(Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
6075{
6076 LogFlowFuncEnter();
6077 LogFlowFunc(("that={%p}\n", that));
6078
6079 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
6080
6081 void *pvRemoteBackend = NULL;
6082 if (aRemote)
6083 {
6084 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
6085 Guid guid(*aUuid);
6086
6087 pvRemoteBackend = that->consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &guid);
6088 if (!pvRemoteBackend)
6089 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
6090 }
6091
6092 USHORT portVersion = 1;
6093 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
6094 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
6095 Assert(portVersion == 1 || portVersion == 2);
6096
6097 int vrc = PDMR3USBCreateProxyDevice(that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
6098 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
6099 if (RT_SUCCESS(vrc))
6100 {
6101 /* Create a OUSBDevice and add it to the device list */
6102 ComObjPtr<OUSBDevice> device;
6103 device.createObject();
6104 hrc = device->init(aHostDevice);
6105 AssertComRC(hrc);
6106
6107 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6108 that->mUSBDevices.push_back(device);
6109 LogFlowFunc(("Attached device {%RTuuid}\n", device->id().raw()));
6110
6111 /* notify callbacks */
6112 that->onUSBDeviceStateChange(device, true /* aAttached */, NULL);
6113 }
6114
6115 LogFlowFunc(("vrc=%Rrc\n", vrc));
6116 LogFlowFuncLeave();
6117 return vrc;
6118}
6119
6120/**
6121 * Sends a request to VMM to detach the given host device. After this method
6122 * succeeds, the detached device will disappear from the mUSBDevices
6123 * collection.
6124 *
6125 * @param aIt Iterator pointing to the device to detach.
6126 *
6127 * @note Synchronously calls EMT.
6128 * @note Must be called from under this object's lock.
6129 */
6130HRESULT Console::detachUSBDevice(USBDeviceList::iterator &aIt)
6131{
6132 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6133
6134 /* still want a lock object because we need to leave it */
6135 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6136
6137 /* protect mpVM */
6138 AutoVMCaller autoVMCaller(this);
6139 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
6140
6141 /* if the device is attached, then there must at least one USB hub. */
6142 AssertReturn(PDMR3USBHasHub(mpVM), E_FAIL);
6143
6144 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
6145 (*aIt)->id().raw()));
6146
6147 /* leave the lock before a VMR3* call (EMT will call us back)! */
6148 alock.leave();
6149
6150/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
6151 int vrc = VMR3ReqCallWait(mpVM, VMCPUID_ANY,
6152 (PFNRT) usbDetachCallback, 4, this, &aIt, (*aIt)->id().raw());
6153 ComAssertRCRet(vrc, E_FAIL);
6154
6155 return S_OK;
6156}
6157
6158/**
6159 * USB device detach callback used by DetachUSBDevice().
6160 * Note that DetachUSBDevice() doesn't return until this callback is executed,
6161 * so we don't use AutoCaller and don't care about reference counters of
6162 * interface pointers passed in.
6163 *
6164 * @thread EMT
6165 * @note Locks the console object for writing.
6166 */
6167//static
6168DECLCALLBACK(int)
6169Console::usbDetachCallback(Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
6170{
6171 LogFlowFuncEnter();
6172 LogFlowFunc(("that={%p}\n", that));
6173
6174 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
6175 ComObjPtr<OUSBDevice> device = **aIt;
6176
6177 /*
6178 * If that was a remote device, release the backend pointer.
6179 * The pointer was requested in usbAttachCallback.
6180 */
6181 BOOL fRemote = FALSE;
6182
6183 HRESULT hrc2 = (**aIt)->COMGETTER(Remote)(&fRemote);
6184 ComAssertComRC(hrc2);
6185
6186 if (fRemote)
6187 {
6188 Guid guid(*aUuid);
6189 that->consoleVRDPServer()->USBBackendReleasePointer(&guid);
6190 }
6191
6192 int vrc = PDMR3USBDetachDevice(that->mpVM, aUuid);
6193
6194 if (RT_SUCCESS(vrc))
6195 {
6196 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6197
6198 /* Remove the device from the collection */
6199 that->mUSBDevices.erase(*aIt);
6200 LogFlowFunc(("Detached device {%RTuuid}\n", device->id().raw()));
6201
6202 /* notify callbacks */
6203 that->onUSBDeviceStateChange(device, false /* aAttached */, NULL);
6204 }
6205
6206 LogFlowFunc(("vrc=%Rrc\n", vrc));
6207 LogFlowFuncLeave();
6208 return vrc;
6209}
6210
6211#endif /* VBOX_WITH_USB */
6212#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
6213
6214/**
6215 * Helper function to handle host interface device creation and attachment.
6216 *
6217 * @param networkAdapter the network adapter which attachment should be reset
6218 * @return COM status code
6219 *
6220 * @note The caller must lock this object for writing.
6221 *
6222 * @todo Move this back into the driver!
6223 */
6224HRESULT Console::attachToTapInterface(INetworkAdapter *networkAdapter)
6225{
6226 LogFlowThisFunc(("\n"));
6227 /* sanity check */
6228 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6229
6230# ifdef VBOX_STRICT
6231 /* paranoia */
6232 NetworkAttachmentType_T attachment;
6233 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6234 Assert(attachment == NetworkAttachmentType_Bridged);
6235# endif /* VBOX_STRICT */
6236
6237 HRESULT rc = S_OK;
6238
6239 ULONG slot = 0;
6240 rc = networkAdapter->COMGETTER(Slot)(&slot);
6241 AssertComRC(rc);
6242
6243# ifdef RT_OS_LINUX
6244 /*
6245 * Allocate a host interface device
6246 */
6247 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
6248 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
6249 if (RT_SUCCESS(rcVBox))
6250 {
6251 /*
6252 * Set/obtain the tap interface.
6253 */
6254 struct ifreq IfReq;
6255 memset(&IfReq, 0, sizeof(IfReq));
6256 /* The name of the TAP interface we are using */
6257 Bstr tapDeviceName;
6258 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6259 if (FAILED(rc))
6260 tapDeviceName.setNull(); /* Is this necessary? */
6261 if (tapDeviceName.isEmpty())
6262 {
6263 LogRel(("No TAP device name was supplied.\n"));
6264 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
6265 }
6266
6267 if (SUCCEEDED(rc))
6268 {
6269 /* If we are using a static TAP device then try to open it. */
6270 Utf8Str str(tapDeviceName);
6271 if (str.length() <= sizeof(IfReq.ifr_name))
6272 strcpy(IfReq.ifr_name, str.raw());
6273 else
6274 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
6275 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
6276 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
6277 if (rcVBox != 0)
6278 {
6279 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
6280 rc = setError(E_FAIL,
6281 tr("Failed to open the host network interface %ls"),
6282 tapDeviceName.raw());
6283 }
6284 }
6285 if (SUCCEEDED(rc))
6286 {
6287 /*
6288 * Make it pollable.
6289 */
6290 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
6291 {
6292 Log(("attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
6293 /*
6294 * Here is the right place to communicate the TAP file descriptor and
6295 * the host interface name to the server if/when it becomes really
6296 * necessary.
6297 */
6298 maTAPDeviceName[slot] = tapDeviceName;
6299 rcVBox = VINF_SUCCESS;
6300 }
6301 else
6302 {
6303 int iErr = errno;
6304
6305 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
6306 rcVBox = VERR_HOSTIF_BLOCKING;
6307 rc = setError(E_FAIL,
6308 tr("could not set up the host networking device for non blocking access: %s"),
6309 strerror(errno));
6310 }
6311 }
6312 }
6313 else
6314 {
6315 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
6316 switch (rcVBox)
6317 {
6318 case VERR_ACCESS_DENIED:
6319 /* will be handled by our caller */
6320 rc = rcVBox;
6321 break;
6322 default:
6323 rc = setError(E_FAIL,
6324 tr("Could not set up the host networking device: %Rrc"),
6325 rcVBox);
6326 break;
6327 }
6328 }
6329
6330# elif defined(RT_OS_FREEBSD)
6331 /*
6332 * Set/obtain the tap interface.
6333 */
6334 /* The name of the TAP interface we are using */
6335 Bstr tapDeviceName;
6336 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6337 if (FAILED(rc))
6338 tapDeviceName.setNull(); /* Is this necessary? */
6339 if (tapDeviceName.isEmpty())
6340 {
6341 LogRel(("No TAP device name was supplied.\n"));
6342 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
6343 }
6344 char szTapdev[1024] = "/dev/";
6345 /* If we are using a static TAP device then try to open it. */
6346 Utf8Str str(tapDeviceName);
6347 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
6348 strcat(szTapdev, str.raw());
6349 else
6350 memcpy(szTapdev + strlen(szTapdev), str.raw(), sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
6351 int rcVBox = RTFileOpen(&maTapFD[slot], szTapdev,
6352 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
6353
6354 if (RT_SUCCESS(rcVBox))
6355 maTAPDeviceName[slot] = tapDeviceName;
6356 else
6357 {
6358 switch (rcVBox)
6359 {
6360 case VERR_ACCESS_DENIED:
6361 /* will be handled by our caller */
6362 rc = rcVBox;
6363 break;
6364 default:
6365 rc = setError(E_FAIL,
6366 tr("Failed to open the host network interface %ls"),
6367 tapDeviceName.raw());
6368 break;
6369 }
6370 }
6371# else
6372# error "huh?"
6373# endif
6374 /* in case of failure, cleanup. */
6375 if (RT_FAILURE(rcVBox) && SUCCEEDED(rc))
6376 {
6377 LogRel(("General failure attaching to host interface\n"));
6378 rc = setError(E_FAIL,
6379 tr("General failure attaching to host interface"));
6380 }
6381 LogFlowThisFunc(("rc=%d\n", rc));
6382 return rc;
6383}
6384
6385
6386/**
6387 * Helper function to handle detachment from a host interface
6388 *
6389 * @param networkAdapter the network adapter which attachment should be reset
6390 * @return COM status code
6391 *
6392 * @note The caller must lock this object for writing.
6393 *
6394 * @todo Move this back into the driver!
6395 */
6396HRESULT Console::detachFromTapInterface(INetworkAdapter *networkAdapter)
6397{
6398 /* sanity check */
6399 LogFlowThisFunc(("\n"));
6400 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6401
6402 HRESULT rc = S_OK;
6403# ifdef VBOX_STRICT
6404 /* paranoia */
6405 NetworkAttachmentType_T attachment;
6406 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6407 Assert(attachment == NetworkAttachmentType_Bridged);
6408# endif /* VBOX_STRICT */
6409
6410 ULONG slot = 0;
6411 rc = networkAdapter->COMGETTER(Slot)(&slot);
6412 AssertComRC(rc);
6413
6414 /* is there an open TAP device? */
6415 if (maTapFD[slot] != NIL_RTFILE)
6416 {
6417 /*
6418 * Close the file handle.
6419 */
6420 Bstr tapDeviceName, tapTerminateApplication;
6421 bool isStatic = true;
6422 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6423 if (FAILED(rc) || tapDeviceName.isEmpty())
6424 {
6425 /* If the name is empty, this is a dynamic TAP device, so close it now,
6426 so that the termination script can remove the interface. Otherwise we still
6427 need the FD to pass to the termination script. */
6428 isStatic = false;
6429 int rcVBox = RTFileClose(maTapFD[slot]);
6430 AssertRC(rcVBox);
6431 maTapFD[slot] = NIL_RTFILE;
6432 }
6433 if (isStatic)
6434 {
6435 /* If we are using a static TAP device, we close it now, after having called the
6436 termination script. */
6437 int rcVBox = RTFileClose(maTapFD[slot]);
6438 AssertRC(rcVBox);
6439 }
6440 /* the TAP device name and handle are no longer valid */
6441 maTapFD[slot] = NIL_RTFILE;
6442 maTAPDeviceName[slot] = "";
6443 }
6444 LogFlowThisFunc(("returning %d\n", rc));
6445 return rc;
6446}
6447
6448#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
6449
6450/**
6451 * Called at power down to terminate host interface networking.
6452 *
6453 * @note The caller must lock this object for writing.
6454 */
6455HRESULT Console::powerDownHostInterfaces()
6456{
6457 LogFlowThisFunc(("\n"));
6458
6459 /* sanity check */
6460 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6461
6462 /*
6463 * host interface termination handling
6464 */
6465 HRESULT rc;
6466 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
6467 {
6468 ComPtr<INetworkAdapter> networkAdapter;
6469 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
6470 if (FAILED(rc)) break;
6471
6472 BOOL enabled = FALSE;
6473 networkAdapter->COMGETTER(Enabled)(&enabled);
6474 if (!enabled)
6475 continue;
6476
6477 NetworkAttachmentType_T attachment;
6478 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6479 if (attachment == NetworkAttachmentType_Bridged)
6480 {
6481#if defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)
6482 HRESULT rc2 = detachFromTapInterface(networkAdapter);
6483 if (FAILED(rc2) && SUCCEEDED(rc))
6484 rc = rc2;
6485#endif
6486 }
6487 }
6488
6489 return rc;
6490}
6491
6492
6493/**
6494 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
6495 * and VMR3Teleport.
6496 *
6497 * @param pVM The VM handle.
6498 * @param uPercent Completetion precentage (0-100).
6499 * @param pvUser Pointer to the VMProgressTask structure.
6500 * @return VINF_SUCCESS.
6501 */
6502/*static*/
6503DECLCALLBACK(int) Console::stateProgressCallback(PVM pVM, unsigned uPercent, void *pvUser)
6504{
6505 VMProgressTask *task = static_cast<VMProgressTask *>(pvUser);
6506 AssertReturn(task, VERR_INVALID_PARAMETER);
6507
6508 /* update the progress object */
6509 if (task->mProgress)
6510 task->mProgress->SetCurrentOperationProgress(uPercent);
6511
6512 return VINF_SUCCESS;
6513}
6514
6515/**
6516 * VM error callback function. Called by the various VM components.
6517 *
6518 * @param pVM VM handle. Can be NULL if an error occurred before
6519 * successfully creating a VM.
6520 * @param pvUser Pointer to the VMProgressTask structure.
6521 * @param rc VBox status code.
6522 * @param pszFormat Printf-like error message.
6523 * @param args Various number of arguments for the error message.
6524 *
6525 * @thread EMT, VMPowerUp...
6526 *
6527 * @note The VMProgressTask structure modified by this callback is not thread
6528 * safe.
6529 */
6530/* static */ DECLCALLBACK(void)
6531Console::setVMErrorCallback(PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
6532 const char *pszFormat, va_list args)
6533{
6534 VMProgressTask *task = static_cast<VMProgressTask *>(pvUser);
6535 AssertReturnVoid(task);
6536
6537 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
6538 va_list va2;
6539 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
6540
6541 /* append to the existing error message if any */
6542 if (task->mErrorMsg.length())
6543 task->mErrorMsg = Utf8StrFmt("%s.\n%N (%Rrc)", task->mErrorMsg.raw(),
6544 pszFormat, &va2, rc, rc);
6545 else
6546 task->mErrorMsg = Utf8StrFmt("%N (%Rrc)",
6547 pszFormat, &va2, rc, rc);
6548
6549 va_end (va2);
6550}
6551
6552/**
6553 * VM runtime error callback function.
6554 * See VMSetRuntimeError for the detailed description of parameters.
6555 *
6556 * @param pVM The VM handle.
6557 * @param pvUser The user argument.
6558 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
6559 * @param pszErrorId Error ID string.
6560 * @param pszFormat Error message format string.
6561 * @param va Error message arguments.
6562 * @thread EMT.
6563 */
6564/* static */ DECLCALLBACK(void)
6565Console::setVMRuntimeErrorCallback(PVM pVM, void *pvUser, uint32_t fFlags,
6566 const char *pszErrorId,
6567 const char *pszFormat, va_list va)
6568{
6569 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
6570 LogFlowFuncEnter();
6571
6572 Console *that = static_cast<Console *>(pvUser);
6573 AssertReturnVoid(that);
6574
6575 Utf8Str message = Utf8StrFmtVA(pszFormat, va);
6576
6577 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
6578 fFatal, pszErrorId, message.raw()));
6579
6580 that->onRuntimeError(BOOL(fFatal), Bstr(pszErrorId), Bstr(message));
6581
6582 LogFlowFuncLeave();
6583}
6584
6585/**
6586 * Captures USB devices that match filters of the VM.
6587 * Called at VM startup.
6588 *
6589 * @param pVM The VM handle.
6590 *
6591 * @note The caller must lock this object for writing.
6592 */
6593HRESULT Console::captureUSBDevices(PVM pVM)
6594{
6595 LogFlowThisFunc(("\n"));
6596
6597 /* sanity check */
6598 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
6599
6600 /* If the machine has an USB controller, ask the USB proxy service to
6601 * capture devices */
6602 PPDMIBASE pBase;
6603 int vrc = PDMR3QueryLun(pVM, "usb-ohci", 0, 0, &pBase);
6604 if (RT_SUCCESS(vrc))
6605 {
6606 /* leave the lock before calling Host in VBoxSVC since Host may call
6607 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6608 * produce an inter-process dead-lock otherwise. */
6609 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6610 alock.leave();
6611
6612 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6613 ComAssertComRCRetRC(hrc);
6614 }
6615 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6616 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6617 vrc = VINF_SUCCESS;
6618 else
6619 AssertRC(vrc);
6620
6621 return RT_SUCCESS(vrc) ? S_OK : E_FAIL;
6622}
6623
6624
6625/**
6626 * Detach all USB device which are attached to the VM for the
6627 * purpose of clean up and such like.
6628 *
6629 * @note The caller must lock this object for writing.
6630 */
6631void Console::detachAllUSBDevices(bool aDone)
6632{
6633 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
6634
6635 /* sanity check */
6636 AssertReturnVoid(isWriteLockOnCurrentThread());
6637
6638 mUSBDevices.clear();
6639
6640 /* leave the lock before calling Host in VBoxSVC since Host may call
6641 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6642 * produce an inter-process dead-lock otherwise. */
6643 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6644 alock.leave();
6645
6646 mControl->DetachAllUSBDevices(aDone);
6647}
6648
6649/**
6650 * @note Locks this object for writing.
6651 */
6652void Console::processRemoteUSBDevices(uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6653{
6654 LogFlowThisFuncEnter();
6655 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6656
6657 AutoCaller autoCaller(this);
6658 if (!autoCaller.isOk())
6659 {
6660 /* Console has been already uninitialized, deny request */
6661 AssertMsgFailed(("Console is already uninitialized\n"));
6662 LogFlowThisFunc(("Console is already uninitialized\n"));
6663 LogFlowThisFuncLeave();
6664 return;
6665 }
6666
6667 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6668
6669 /*
6670 * Mark all existing remote USB devices as dirty.
6671 */
6672 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6673 it != mRemoteUSBDevices.end();
6674 ++it)
6675 {
6676 (*it)->dirty(true);
6677 }
6678
6679 /*
6680 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6681 */
6682 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6683 VRDPUSBDEVICEDESC *e = pDevList;
6684
6685 /* The cbDevList condition must be checked first, because the function can
6686 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6687 */
6688 while (cbDevList >= 2 && e->oNext)
6689 {
6690 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
6691 e->idVendor, e->idProduct,
6692 e->oProduct? (char *)e + e->oProduct: ""));
6693
6694 bool fNewDevice = true;
6695
6696 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6697 it != mRemoteUSBDevices.end();
6698 ++it)
6699 {
6700 if ((*it)->devId() == e->id
6701 && (*it)->clientId() == u32ClientId)
6702 {
6703 /* The device is already in the list. */
6704 (*it)->dirty(false);
6705 fNewDevice = false;
6706 break;
6707 }
6708 }
6709
6710 if (fNewDevice)
6711 {
6712 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6713 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
6714
6715 /* Create the device object and add the new device to list. */
6716 ComObjPtr<RemoteUSBDevice> device;
6717 device.createObject();
6718 device->init(u32ClientId, e);
6719
6720 mRemoteUSBDevices.push_back(device);
6721
6722 /* Check if the device is ok for current USB filters. */
6723 BOOL fMatched = FALSE;
6724 ULONG fMaskedIfs = 0;
6725
6726 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
6727
6728 AssertComRC(hrc);
6729
6730 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
6731
6732 if (fMatched)
6733 {
6734 hrc = onUSBDeviceAttach(device, NULL, fMaskedIfs);
6735
6736 /// @todo (r=dmik) warning reporting subsystem
6737
6738 if (hrc == S_OK)
6739 {
6740 LogFlowThisFunc(("Device attached\n"));
6741 device->captured(true);
6742 }
6743 }
6744 }
6745
6746 if (cbDevList < e->oNext)
6747 {
6748 LogWarningThisFunc(("cbDevList %d > oNext %d\n",
6749 cbDevList, e->oNext));
6750 break;
6751 }
6752
6753 cbDevList -= e->oNext;
6754
6755 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6756 }
6757
6758 /*
6759 * Remove dirty devices, that is those which are not reported by the server anymore.
6760 */
6761 for (;;)
6762 {
6763 ComObjPtr<RemoteUSBDevice> device;
6764
6765 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6766 while (it != mRemoteUSBDevices.end())
6767 {
6768 if ((*it)->dirty())
6769 {
6770 device = *it;
6771 break;
6772 }
6773
6774 ++ it;
6775 }
6776
6777 if (!device)
6778 {
6779 break;
6780 }
6781
6782 USHORT vendorId = 0;
6783 device->COMGETTER(VendorId)(&vendorId);
6784
6785 USHORT productId = 0;
6786 device->COMGETTER(ProductId)(&productId);
6787
6788 Bstr product;
6789 device->COMGETTER(Product)(product.asOutParam());
6790
6791 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6792 vendorId, productId, product.raw()));
6793
6794 /* Detach the device from VM. */
6795 if (device->captured())
6796 {
6797 Bstr uuid;
6798 device->COMGETTER(Id)(uuid.asOutParam());
6799 onUSBDeviceDetach(uuid, NULL);
6800 }
6801
6802 /* And remove it from the list. */
6803 mRemoteUSBDevices.erase(it);
6804 }
6805
6806 LogFlowThisFuncLeave();
6807}
6808
6809/**
6810 * Thread function which starts the VM (also from saved state) and
6811 * track progress.
6812 *
6813 * @param Thread The thread id.
6814 * @param pvUser Pointer to a VMPowerUpTask structure.
6815 * @return VINF_SUCCESS (ignored).
6816 *
6817 * @note Locks the Console object for writing.
6818 */
6819/*static*/
6820DECLCALLBACK(int) Console::powerUpThread(RTTHREAD Thread, void *pvUser)
6821{
6822 LogFlowFuncEnter();
6823
6824 std::auto_ptr<VMPowerUpTask> task(static_cast<VMPowerUpTask *>(pvUser));
6825 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
6826
6827 AssertReturn(!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6828 AssertReturn(!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6829
6830#if defined(RT_OS_WINDOWS)
6831 {
6832 /* initialize COM */
6833 HRESULT hrc = CoInitializeEx(NULL,
6834 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6835 COINIT_SPEED_OVER_MEMORY);
6836 LogFlowFunc(("CoInitializeEx()=%08X\n", hrc));
6837 }
6838#endif
6839
6840 HRESULT rc = S_OK;
6841 int vrc = VINF_SUCCESS;
6842
6843 /* Set up a build identifier so that it can be seen from core dumps what
6844 * exact build was used to produce the core. */
6845 static char saBuildID[40];
6846 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
6847 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, RTBldCfgRevision(), "BU", "IL", "DI", "D");
6848
6849 ComObjPtr<Console> console = task->mConsole;
6850
6851 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6852
6853 /* The lock is also used as a signal from the task initiator (which
6854 * releases it only after RTThreadCreate()) that we can start the job */
6855 AutoWriteLock alock(console COMMA_LOCKVAL_SRC_POS);
6856
6857 /* sanity */
6858 Assert(console->mpVM == NULL);
6859
6860 try
6861 {
6862 /* wait for auto reset ops to complete so that we can successfully lock
6863 * the attached hard disks by calling LockMedia() below */
6864 for (VMPowerUpTask::ProgressList::const_iterator
6865 it = task->hardDiskProgresses.begin();
6866 it != task->hardDiskProgresses.end(); ++ it)
6867 {
6868 HRESULT rc2 = (*it)->WaitForCompletion(-1);
6869 AssertComRC(rc2);
6870 }
6871
6872 /*
6873 * Lock attached media. This method will also check their accessibility.
6874 * If we're a teleporter, we'll have to postpone this action so we can
6875 * migrate between local processes.
6876 *
6877 * Note! The media will be unlocked automatically by
6878 * SessionMachine::setMachineState() when the VM is powered down.
6879 */
6880 if (!task->mTeleporterEnabled)
6881 {
6882 rc = console->mControl->LockMedia();
6883 if (FAILED(rc)) throw rc;
6884 }
6885
6886#ifdef VBOX_WITH_VRDP
6887
6888 /* Create the VRDP server. In case of headless operation, this will
6889 * also create the framebuffer, required at VM creation.
6890 */
6891 ConsoleVRDPServer *server = console->consoleVRDPServer();
6892 Assert(server);
6893
6894 /* Does VRDP server call Console from the other thread?
6895 * Not sure (and can change), so leave the lock just in case.
6896 */
6897 alock.leave();
6898 vrc = server->Launch();
6899 alock.enter();
6900
6901 if (vrc == VERR_NET_ADDRESS_IN_USE)
6902 {
6903 Utf8Str errMsg;
6904 Bstr bstr;
6905 console->mVRDPServer->COMGETTER(Ports)(bstr.asOutParam());
6906 Utf8Str ports = bstr;
6907 errMsg = Utf8StrFmt(tr("VRDP server can't bind to a port: %s"),
6908 ports.raw());
6909 LogRel(("Warning: failed to launch VRDP server (%Rrc): '%s'\n",
6910 vrc, errMsg.raw()));
6911 }
6912 else if (RT_FAILURE(vrc))
6913 {
6914 Utf8Str errMsg;
6915 switch (vrc)
6916 {
6917 case VERR_FILE_NOT_FOUND:
6918 {
6919 errMsg = Utf8StrFmt(tr("Could not load the VRDP library"));
6920 break;
6921 }
6922 default:
6923 errMsg = Utf8StrFmt(tr("Failed to launch VRDP server (%Rrc)"),
6924 vrc);
6925 }
6926 LogRel(("Failed to launch VRDP server (%Rrc), error message: '%s'\n",
6927 vrc, errMsg.raw()));
6928 throw setError(E_FAIL, errMsg.c_str());
6929 }
6930
6931#endif /* VBOX_WITH_VRDP */
6932
6933 ComPtr<IMachine> pMachine = console->machine();
6934 ULONG cCpus = 1;
6935 pMachine->COMGETTER(CPUCount)(&cCpus);
6936
6937 /*
6938 * Create the VM
6939 */
6940 PVM pVM;
6941 /*
6942 * leave the lock since EMT will call Console. It's safe because
6943 * mMachineState is either Starting or Restoring state here.
6944 */
6945 alock.leave();
6946
6947 vrc = VMR3Create(cCpus, task->mSetVMErrorCallback, task.get(),
6948 task->mConfigConstructor, static_cast<Console *>(console),
6949 &pVM);
6950
6951 alock.enter();
6952
6953#ifdef VBOX_WITH_VRDP
6954 /* Enable client connections to the server. */
6955 console->consoleVRDPServer()->EnableConnections();
6956#endif /* VBOX_WITH_VRDP */
6957
6958 if (RT_SUCCESS(vrc))
6959 {
6960 do
6961 {
6962 /*
6963 * Register our load/save state file handlers
6964 */
6965 vrc = SSMR3RegisterExternal(pVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
6966 NULL, NULL, NULL,
6967 NULL, saveStateFileExec, NULL,
6968 NULL, loadStateFileExec, NULL,
6969 static_cast<Console *>(console));
6970 AssertRCBreak(vrc);
6971
6972 vrc = static_cast<Console *>(console)->getDisplay()->registerSSM(pVM);
6973 AssertRC(vrc);
6974 if (RT_FAILURE(vrc))
6975 break;
6976
6977 /*
6978 * Synchronize debugger settings
6979 */
6980 MachineDebugger *machineDebugger = console->getMachineDebugger();
6981 if (machineDebugger)
6982 {
6983 machineDebugger->flushQueuedSettings();
6984 }
6985
6986 /*
6987 * Shared Folders
6988 */
6989 if (console->getVMMDev()->isShFlActive())
6990 {
6991 /* Does the code below call Console from the other thread?
6992 * Not sure, so leave the lock just in case. */
6993 alock.leave();
6994
6995 for (SharedFolderDataMap::const_iterator
6996 it = task->mSharedFolders.begin();
6997 it != task->mSharedFolders.end();
6998 ++ it)
6999 {
7000 rc = console->createSharedFolder((*it).first, (*it).second);
7001 if (FAILED(rc)) break;
7002 }
7003 if (FAILED(rc)) break;
7004
7005 /* enter the lock again */
7006 alock.enter();
7007 }
7008
7009 /*
7010 * Capture USB devices.
7011 */
7012 rc = console->captureUSBDevices(pVM);
7013 if (FAILED(rc)) break;
7014
7015 /* leave the lock before a lengthy operation */
7016 alock.leave();
7017
7018 /* Load saved state? */
7019 if (task->mSavedStateFile.length())
7020 {
7021 LogFlowFunc(("Restoring saved state from '%s'...\n",
7022 task->mSavedStateFile.raw()));
7023
7024 vrc = VMR3LoadFromFile(pVM,
7025 task->mSavedStateFile.c_str(),
7026 Console::stateProgressCallback,
7027 static_cast<VMProgressTask*>(task.get()));
7028
7029 if (RT_SUCCESS(vrc))
7030 {
7031 if (task->mStartPaused)
7032 /* done */
7033 console->setMachineState(MachineState_Paused);
7034 else
7035 {
7036 /* Start/Resume the VM execution */
7037 vrc = VMR3Resume(pVM);
7038 AssertRC(vrc);
7039 }
7040 }
7041
7042 /* Power off in case we failed loading or resuming the VM */
7043 if (RT_FAILURE(vrc))
7044 {
7045 int vrc2 = VMR3PowerOff(pVM);
7046 AssertRC(vrc2);
7047 }
7048 }
7049 else if (task->mTeleporterEnabled)
7050 {
7051 /* -> ConsoleImplTeleporter.cpp */
7052 vrc = console->teleporterTrg(pVM, pMachine, task->mStartPaused, task->mProgress);
7053 if (RT_FAILURE(vrc) && !task->mErrorMsg.length())
7054 rc = E_FAIL; /* Avoid the "Missing error message..." assertion. */
7055 }
7056 else if (task->mStartPaused)
7057 /* done */
7058 console->setMachineState(MachineState_Paused);
7059 else
7060 {
7061 /* Power on the VM (i.e. start executing) */
7062 vrc = VMR3PowerOn(pVM);
7063 AssertRC(vrc);
7064 }
7065
7066 /* enter the lock again */
7067 alock.enter();
7068 }
7069 while (0);
7070
7071 /* On failure, destroy the VM */
7072 if (FAILED(rc) || RT_FAILURE(vrc))
7073 {
7074 /* preserve existing error info */
7075 ErrorInfoKeeper eik;
7076
7077 /* powerDown() will call VMR3Destroy() and do all necessary
7078 * cleanup (VRDP, USB devices) */
7079 HRESULT rc2 = console->powerDown();
7080 AssertComRC(rc2);
7081 }
7082 else
7083 {
7084 /*
7085 * Deregister the VMSetError callback. This is necessary as the
7086 * pfnVMAtError() function passed to VMR3Create() is supposed to
7087 * be sticky but our error callback isn't.
7088 */
7089 alock.leave();
7090 VMR3AtErrorDeregister(pVM, task->mSetVMErrorCallback, task.get());
7091 /** @todo register another VMSetError callback? */
7092 alock.enter();
7093 }
7094 }
7095 else
7096 {
7097 /*
7098 * If VMR3Create() failed it has released the VM memory.
7099 */
7100 console->mpVM = NULL;
7101 }
7102
7103 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
7104 {
7105 /* If VMR3Create() or one of the other calls in this function fail,
7106 * an appropriate error message has been set in task->mErrorMsg.
7107 * However since that happens via a callback, the rc status code in
7108 * this function is not updated.
7109 */
7110 if (!task->mErrorMsg.length())
7111 {
7112 /* If the error message is not set but we've got a failure,
7113 * convert the VBox status code into a meaningful error message.
7114 * This becomes unused once all the sources of errors set the
7115 * appropriate error message themselves.
7116 */
7117 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
7118 task->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"),
7119 vrc);
7120 }
7121
7122 /* Set the error message as the COM error.
7123 * Progress::notifyComplete() will pick it up later. */
7124 throw setError(E_FAIL, task->mErrorMsg.c_str());
7125 }
7126 }
7127 catch (HRESULT aRC) { rc = aRC; }
7128
7129 if ( console->mMachineState == MachineState_Starting
7130 || console->mMachineState == MachineState_Restoring
7131 || console->mMachineState == MachineState_TeleportingIn
7132 )
7133 {
7134 /* We are still in the Starting/Restoring state. This means one of:
7135 *
7136 * 1) we failed before VMR3Create() was called;
7137 * 2) VMR3Create() failed.
7138 *
7139 * In both cases, there is no need to call powerDown(), but we still
7140 * need to go back to the PoweredOff/Saved state. Reuse
7141 * vmstateChangeCallback() for that purpose.
7142 */
7143
7144 /* preserve existing error info */
7145 ErrorInfoKeeper eik;
7146
7147 Assert(console->mpVM == NULL);
7148 vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
7149 console);
7150 }
7151
7152 /*
7153 * Evaluate the final result. Note that the appropriate mMachineState value
7154 * is already set by vmstateChangeCallback() in all cases.
7155 */
7156
7157 /* leave the lock, don't need it any more */
7158 alock.leave();
7159
7160 if (SUCCEEDED(rc))
7161 {
7162 /* Notify the progress object of the success */
7163 task->mProgress->notifyComplete(S_OK);
7164 console->mControl->SetPowerUpInfo(NULL);
7165 }
7166 else
7167 {
7168 /* The progress object will fetch the current error info */
7169 task->mProgress->notifyComplete(rc);
7170 ProgressErrorInfo info(task->mProgress);
7171 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
7172 rc = errorInfo.createObject();
7173 if (SUCCEEDED(rc))
7174 {
7175 errorInfo->init(info.getResultCode(),
7176 info.getInterfaceID(),
7177 info.getComponent(),
7178 info.getText());
7179 console->mControl->SetPowerUpInfo(errorInfo);
7180 }
7181 else
7182 {
7183 /* If it's not possible to create an IVirtualBoxErrorInfo object
7184 * signal success, as not signalling anything will cause a stuck
7185 * progress object in VBoxSVC. */
7186 console->mControl->SetPowerUpInfo(NULL);
7187 }
7188
7189 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
7190 }
7191
7192#if defined(RT_OS_WINDOWS)
7193 /* uninitialize COM */
7194 CoUninitialize();
7195#endif
7196
7197 LogFlowFuncLeave();
7198
7199 return VINF_SUCCESS;
7200}
7201
7202
7203/**
7204 * Reconfigures a medium attachment (part of taking an online snapshot).
7205 *
7206 * @param pVM The VM handle.
7207 * @param lInstance The instance of the controller.
7208 * @param pcszDevice The name of the controller type.
7209 * @param enmBus The storage bus type of the controller.
7210 * @param aMediumAtt The medium attachment.
7211 * @param aMachineState The current machine state.
7212 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
7213 * @return VBox status code.
7214 */
7215/* static */
7216DECLCALLBACK(int) Console::reconfigureMediumAttachment(PVM pVM,
7217 const char *pcszDevice,
7218 unsigned uInstance,
7219 StorageBus_T enmBus,
7220 IMediumAttachment *aMediumAtt,
7221 MachineState_T aMachineState,
7222 HRESULT *phrc)
7223{
7224 LogFlowFunc(("pVM=%p aMediumAtt=%p phrc=%p\n", pVM, aMediumAtt, phrc));
7225
7226 int rc;
7227 HRESULT hrc;
7228 Bstr bstr;
7229 *phrc = S_OK;
7230#define RC_CHECK() do { if (RT_FAILURE(rc)) { AssertMsgFailed(("rc=%Rrc\n", rc)); return rc; } } while (0)
7231#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
7232
7233 /* Ignore attachments other than hard disks, since at the moment they are
7234 * not subject to snapshotting in general. */
7235 DeviceType_T lType;
7236 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
7237 if (lType != DeviceType_HardDisk)
7238 return VINF_SUCCESS;
7239
7240 /* Determine the base path for the device instance. */
7241 PCFGMNODE pCtlInst;
7242 pCtlInst = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/%s/%u/", pcszDevice, uInstance);
7243 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
7244
7245 /* Update the device instance configuration. */
7246 rc = Console::configMediumAttachment(pCtlInst, pcszDevice, uInstance,
7247 enmBus, aMediumAtt, aMachineState,
7248 phrc, true /* fAttachDetach */,
7249 false /* fForceUnmount */, pVM,
7250 NULL /* paLedDevType */);
7251 /** @todo this dumps everything attached to this device instance, which
7252 * is more than necessary. Dumping the changed LUN would be enough. */
7253 CFGMR3Dump(pCtlInst);
7254 RC_CHECK();
7255
7256#undef RC_CHECK
7257#undef H
7258
7259 LogFlowFunc(("Returns success\n"));
7260 return VINF_SUCCESS;
7261}
7262
7263/**
7264 * Progress cancelation callback employed by Console::fntTakeSnapshotWorker.
7265 */
7266static void takesnapshotProgressCancelCallback(void *pvUser)
7267{
7268 PVM pVM = (PVM)pvUser;
7269 SSMR3Cancel(pVM);
7270}
7271
7272/**
7273 * Worker thread created by Console::TakeSnapshot.
7274 * @param Thread The current thread (ignored).
7275 * @param pvUser The task.
7276 * @return VINF_SUCCESS (ignored).
7277 */
7278/*static*/
7279DECLCALLBACK(int) Console::fntTakeSnapshotWorker(RTTHREAD Thread, void *pvUser)
7280{
7281 VMTakeSnapshotTask *pTask = (VMTakeSnapshotTask*)pvUser;
7282
7283 // taking a snapshot consists of the following:
7284
7285 // 1) creating a diff image for each virtual hard disk, into which write operations go after
7286 // the snapshot has been created (done in VBoxSVC, in SessionMachine::BeginTakingSnapshot)
7287 // 2) creating a Snapshot object with the state of the machine (hardware + storage,
7288 // done in VBoxSVC, also in SessionMachine::BeginTakingSnapshot)
7289 // 3) saving the state of the virtual machine (here, in the VM process, if the machine is online)
7290
7291 Console *that = pTask->mConsole;
7292 bool fBeganTakingSnapshot = false;
7293 bool fSuspenededBySave = false;
7294
7295 AutoCaller autoCaller(that);
7296 if (FAILED(autoCaller.rc()))
7297 {
7298 that->mptrCancelableProgress.setNull();
7299 return autoCaller.rc();
7300 }
7301
7302 /* protect mpVM */
7303 AutoVMCaller autoVMCaller(that);
7304 if (FAILED(autoVMCaller.rc()))
7305 {
7306 that->mptrCancelableProgress.setNull();
7307 return autoVMCaller.rc();
7308 }
7309
7310 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7311
7312 HRESULT rc = S_OK;
7313
7314 try
7315 {
7316 /* STEP 1 + 2:
7317 * request creating the diff images on the server and create the snapshot object
7318 * (this will set the machine state to Saving on the server to block
7319 * others from accessing this machine)
7320 */
7321 rc = that->mControl->BeginTakingSnapshot(that,
7322 pTask->bstrName,
7323 pTask->bstrDescription,
7324 pTask->mProgress,
7325 pTask->fTakingSnapshotOnline,
7326 pTask->bstrSavedStateFile.asOutParam());
7327 if (FAILED(rc))
7328 throw rc;
7329
7330 fBeganTakingSnapshot = true;
7331
7332 /*
7333 * state file is non-null only when the VM is paused
7334 * (i.e. creating a snapshot online)
7335 */
7336 ComAssertThrow( (!pTask->bstrSavedStateFile.isEmpty() && pTask->fTakingSnapshotOnline)
7337 || ( pTask->bstrSavedStateFile.isEmpty() && !pTask->fTakingSnapshotOnline),
7338 rc = E_FAIL);
7339
7340 /* sync the state with the server */
7341 if (pTask->lastMachineState == MachineState_Running)
7342 that->setMachineStateLocally(MachineState_LiveSnapshotting);
7343 else
7344 that->setMachineStateLocally(MachineState_Saving);
7345
7346 // STEP 3: save the VM state (if online)
7347 if (pTask->fTakingSnapshotOnline)
7348 {
7349 Utf8Str strSavedStateFile(pTask->bstrSavedStateFile);
7350
7351 pTask->mProgress->SetNextOperation(Bstr(tr("Saving the machine state")),
7352 pTask->ulMemSize); // operation weight, same as computed when setting up progress object
7353 pTask->mProgress->setCancelCallback(takesnapshotProgressCancelCallback, that->mpVM);
7354
7355 alock.leave();
7356 LogFlowFunc(("VMR3Save...\n"));
7357 int vrc = VMR3Save(that->mpVM,
7358 strSavedStateFile.c_str(),
7359 true /*fContinueAfterwards*/,
7360 Console::stateProgressCallback,
7361 (void*)pTask,
7362 &fSuspenededBySave);
7363 alock.enter();
7364 if (RT_FAILURE(vrc))
7365 throw setError(E_FAIL,
7366 tr("Failed to save the machine state to '%s' (%Rrc)"),
7367 strSavedStateFile.c_str(), vrc);
7368
7369 pTask->mProgress->setCancelCallback(NULL, NULL);
7370 if (!pTask->mProgress->notifyPointOfNoReturn())
7371 throw setError(E_FAIL, tr("Cancelled"));
7372 that->mptrCancelableProgress.setNull();
7373
7374 // STEP 4: reattach hard disks
7375 LogFlowFunc(("Reattaching new differencing hard disks...\n"));
7376
7377 pTask->mProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")),
7378 1); // operation weight, same as computed when setting up progress object
7379
7380 com::SafeIfaceArray<IMediumAttachment> atts;
7381 rc = that->mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7382 if (FAILED(rc))
7383 throw rc;
7384
7385 for (size_t i = 0;
7386 i < atts.size();
7387 ++i)
7388 {
7389 ComPtr<IStorageController> controller;
7390 BSTR controllerName;
7391 ULONG lInstance;
7392 StorageControllerType_T enmController;
7393 StorageBus_T enmBus;
7394
7395 /*
7396 * We can't pass a storage controller object directly
7397 * (g++ complains about not being able to pass non POD types through '...')
7398 * so we have to query needed values here and pass them.
7399 */
7400 rc = atts[i]->COMGETTER(Controller)(&controllerName);
7401 if (FAILED(rc))
7402 throw rc;
7403
7404 rc = that->mMachine->GetStorageControllerByName(controllerName, controller.asOutParam());
7405 if (FAILED(rc))
7406 throw rc;
7407
7408 rc = controller->COMGETTER(ControllerType)(&enmController);
7409 if (FAILED(rc))
7410 throw rc;
7411 rc = controller->COMGETTER(Instance)(&lInstance);
7412 if (FAILED(rc))
7413 throw rc;
7414 rc = controller->COMGETTER(Bus)(&enmBus);
7415 if (FAILED(rc))
7416 throw rc;
7417 const char *pcszDevice = Console::convertControllerTypeToDev(enmController);
7418
7419 /*
7420 * don't leave the lock since reconfigureMediumAttachment
7421 * isn't going to need the Console lock.
7422 */
7423 vrc = VMR3ReqCallWait(that->mpVM,
7424 VMCPUID_ANY,
7425 (PFNRT)reconfigureMediumAttachment,
7426 7,
7427 that->mpVM,
7428 pcszDevice,
7429 lInstance,
7430 enmBus,
7431 atts[i],
7432 that->mMachineState,
7433 &rc);
7434 if (RT_FAILURE(vrc))
7435 throw setError(E_FAIL, Console::tr("%Rrc"), vrc);
7436 if (FAILED(rc))
7437 throw rc;
7438 }
7439 }
7440
7441 /*
7442 * finalize the requested snapshot object.
7443 * This will reset the machine state to the state it had right
7444 * before calling mControl->BeginTakingSnapshot().
7445 */
7446 rc = that->mControl->EndTakingSnapshot(TRUE /*aSuccess*/);
7447 // do not throw rc here because we can't call EndTakingSnapshot() twice
7448 LogFlowFunc(("EndTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
7449 }
7450 catch (HRESULT rcThrown)
7451 {
7452 /* preserve existing error info */
7453 ErrorInfoKeeper eik;
7454
7455 if (fBeganTakingSnapshot)
7456 that->mControl->EndTakingSnapshot(FALSE /*aSuccess*/);
7457
7458 rc = rcThrown;
7459 LogFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
7460 }
7461 Assert(alock.isWriteLockOnCurrentThread());
7462
7463 if (FAILED(rc)) /* Must come before calling setMachineState. */
7464 pTask->mProgress->notifyComplete(rc);
7465
7466 /*
7467 * Fix up the machine state.
7468 *
7469 * For live snapshots we do all the work, for the two other variantions we
7470 * just update the local copy.
7471 */
7472 MachineState_T enmMachineState;
7473 that->mMachine->COMGETTER(State)(&enmMachineState);
7474 if ( that->mMachineState == MachineState_LiveSnapshotting
7475 || that->mMachineState == MachineState_Saving)
7476 {
7477
7478 if (!pTask->fTakingSnapshotOnline)
7479 that->setMachineStateLocally(pTask->lastMachineState);
7480 else if (SUCCEEDED(rc))
7481 {
7482 Assert( pTask->lastMachineState == MachineState_Running
7483 || pTask->lastMachineState == MachineState_Paused);
7484 Assert(that->mMachineState == MachineState_Saving);
7485 if (pTask->lastMachineState == MachineState_Running)
7486 {
7487 LogFlowFunc(("VMR3Resume...\n"));
7488 alock.leave();
7489 int vrc = VMR3Resume(that->mpVM);
7490 alock.enter();
7491 if (RT_FAILURE(vrc))
7492 {
7493 rc = setError(VBOX_E_VM_ERROR, tr("Could not resume the machine execution (%Rrc)"), vrc);
7494 pTask->mProgress->notifyComplete(rc);
7495 if (that->mMachineState == MachineState_Saving)
7496 that->setMachineStateLocally(MachineState_Paused);
7497 }
7498 }
7499 else
7500 that->setMachineStateLocally(MachineState_Paused);
7501 }
7502 else
7503 {
7504 /** @todo this could probably be made more generic and reused elsewhere. */
7505 /* paranoid cleanup on for a failed online snapshot. */
7506 VMSTATE enmVMState = VMR3GetState(that->mpVM);
7507 switch (enmVMState)
7508 {
7509 case VMSTATE_RUNNING:
7510 case VMSTATE_RUNNING_LS:
7511 case VMSTATE_DEBUGGING:
7512 case VMSTATE_DEBUGGING_LS:
7513 case VMSTATE_POWERING_OFF:
7514 case VMSTATE_POWERING_OFF_LS:
7515 case VMSTATE_RESETTING:
7516 case VMSTATE_RESETTING_LS:
7517 Assert(!fSuspenededBySave);
7518 that->setMachineState(MachineState_Running);
7519 break;
7520
7521 case VMSTATE_GURU_MEDITATION:
7522 case VMSTATE_GURU_MEDITATION_LS:
7523 that->setMachineState(MachineState_Stuck);
7524 break;
7525
7526 case VMSTATE_FATAL_ERROR:
7527 case VMSTATE_FATAL_ERROR_LS:
7528 if (pTask->lastMachineState == MachineState_Paused)
7529 that->setMachineStateLocally(pTask->lastMachineState);
7530 else
7531 that->setMachineState(MachineState_Paused);
7532 break;
7533
7534 default:
7535 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
7536 case VMSTATE_SUSPENDED:
7537 case VMSTATE_SUSPENDED_LS:
7538 case VMSTATE_SUSPENDING:
7539 case VMSTATE_SUSPENDING_LS:
7540 case VMSTATE_SUSPENDING_EXT_LS:
7541 if (fSuspenededBySave)
7542 {
7543 Assert(pTask->lastMachineState == MachineState_Running);
7544 LogFlowFunc(("VMR3Resume (on failure)...\n"));
7545 alock.leave();
7546 int vrc = VMR3Resume(that->mpVM);
7547 alock.enter();
7548 AssertLogRelRC(vrc);
7549 if (RT_FAILURE(vrc))
7550 that->setMachineState(MachineState_Paused);
7551 }
7552 else if (pTask->lastMachineState == MachineState_Paused)
7553 that->setMachineStateLocally(pTask->lastMachineState);
7554 else
7555 that->setMachineState(MachineState_Paused);
7556 break;
7557 }
7558
7559 }
7560 }
7561 /*else: somebody else has change the state... Leave it. */
7562
7563 /* check the remote state to see that we got it right. */
7564 that->mMachine->COMGETTER(State)(&enmMachineState);
7565 AssertLogRelMsg(that->mMachineState == enmMachineState,
7566 ("mMachineState=%s enmMachineState=%s\n", Global::stringifyMachineState(that->mMachineState),
7567 Global::stringifyMachineState(enmMachineState) ));
7568
7569
7570 if (SUCCEEDED(rc)) /* The failure cases are handled above. */
7571 pTask->mProgress->notifyComplete(rc);
7572
7573 delete pTask;
7574
7575 LogFlowFuncLeave();
7576 return VINF_SUCCESS;
7577}
7578
7579/**
7580 * Thread for executing the saved state operation.
7581 *
7582 * @param Thread The thread handle.
7583 * @param pvUser Pointer to a VMSaveTask structure.
7584 * @return VINF_SUCCESS (ignored).
7585 *
7586 * @note Locks the Console object for writing.
7587 */
7588/*static*/
7589DECLCALLBACK(int) Console::saveStateThread(RTTHREAD Thread, void *pvUser)
7590{
7591 LogFlowFuncEnter();
7592
7593 std::auto_ptr<VMSaveTask> task(static_cast<VMSaveTask*>(pvUser));
7594 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
7595
7596 Assert(task->mSavedStateFile.length());
7597 Assert(!task->mProgress.isNull());
7598
7599 const ComObjPtr<Console> &that = task->mConsole;
7600 Utf8Str errMsg;
7601 HRESULT rc = S_OK;
7602
7603 LogFlowFunc(("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
7604
7605 bool fSuspenededBySave;
7606 int vrc = VMR3Save(that->mpVM,
7607 task->mSavedStateFile.c_str(),
7608 false, /*fContinueAfterwards*/
7609 Console::stateProgressCallback,
7610 static_cast<VMProgressTask*>(task.get()),
7611 &fSuspenededBySave);
7612 if (RT_FAILURE(vrc))
7613 {
7614 errMsg = Utf8StrFmt(Console::tr("Failed to save the machine state to '%s' (%Rrc)"),
7615 task->mSavedStateFile.raw(), vrc);
7616 rc = E_FAIL;
7617 }
7618 Assert(!fSuspenededBySave);
7619
7620 /* lock the console once we're going to access it */
7621 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
7622
7623 /*
7624 * finalize the requested save state procedure.
7625 * In case of success, the server will set the machine state to Saved;
7626 * in case of failure it will reset the it to the state it had right
7627 * before calling mControl->BeginSavingState().
7628 */
7629 that->mControl->EndSavingState(SUCCEEDED(rc));
7630
7631 /* synchronize the state with the server */
7632 if (!FAILED(rc))
7633 {
7634 /*
7635 * The machine has been successfully saved, so power it down
7636 * (vmstateChangeCallback() will set state to Saved on success).
7637 * Note: we release the task's VM caller, otherwise it will
7638 * deadlock.
7639 */
7640 task->releaseVMCaller();
7641
7642 rc = that->powerDown();
7643 }
7644
7645 /* notify the progress object about operation completion */
7646 if (SUCCEEDED(rc))
7647 task->mProgress->notifyComplete(S_OK);
7648 else
7649 {
7650 if (errMsg.length())
7651 task->mProgress->notifyComplete(rc,
7652 COM_IIDOF(IConsole),
7653 (CBSTR)Console::getComponentName(),
7654 errMsg.c_str());
7655 else
7656 task->mProgress->notifyComplete(rc);
7657 }
7658
7659 LogFlowFuncLeave();
7660 return VINF_SUCCESS;
7661}
7662
7663/**
7664 * Thread for powering down the Console.
7665 *
7666 * @param Thread The thread handle.
7667 * @param pvUser Pointer to the VMTask structure.
7668 * @return VINF_SUCCESS (ignored).
7669 *
7670 * @note Locks the Console object for writing.
7671 */
7672/*static*/
7673DECLCALLBACK(int) Console::powerDownThread(RTTHREAD Thread, void *pvUser)
7674{
7675 LogFlowFuncEnter();
7676
7677 std::auto_ptr<VMProgressTask> task(static_cast<VMProgressTask *>(pvUser));
7678 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
7679
7680 AssertReturn(task->isOk(), VERR_GENERAL_FAILURE);
7681
7682 const ComObjPtr<Console> &that = task->mConsole;
7683
7684 /* Note: no need to use addCaller() to protect Console because VMTask does
7685 * that */
7686
7687 /* wait until the method tat started us returns */
7688 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
7689
7690 /* release VM caller to avoid the powerDown() deadlock */
7691 task->releaseVMCaller();
7692
7693 that->powerDown(task->mProgress);
7694
7695 LogFlowFuncLeave();
7696 return VINF_SUCCESS;
7697}
7698
7699/**
7700 * The Main status driver instance data.
7701 */
7702typedef struct DRVMAINSTATUS
7703{
7704 /** The LED connectors. */
7705 PDMILEDCONNECTORS ILedConnectors;
7706 /** Pointer to the LED ports interface above us. */
7707 PPDMILEDPORTS pLedPorts;
7708 /** Pointer to the array of LED pointers. */
7709 PPDMLED *papLeds;
7710 /** The unit number corresponding to the first entry in the LED array. */
7711 RTUINT iFirstLUN;
7712 /** The unit number corresponding to the last entry in the LED array.
7713 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7714 RTUINT iLastLUN;
7715} DRVMAINSTATUS, *PDRVMAINSTATUS;
7716
7717
7718/**
7719 * Notification about a unit which have been changed.
7720 *
7721 * The driver must discard any pointers to data owned by
7722 * the unit and requery it.
7723 *
7724 * @param pInterface Pointer to the interface structure containing the called function pointer.
7725 * @param iLUN The unit number.
7726 */
7727DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7728{
7729 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7730 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7731 {
7732 PPDMLED pLed;
7733 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7734 if (RT_FAILURE(rc))
7735 pLed = NULL;
7736 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7737 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7738 }
7739}
7740
7741
7742/**
7743 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
7744 */
7745DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
7746{
7747 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7748 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7749 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
7750 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
7751 return NULL;
7752}
7753
7754
7755/**
7756 * Destruct a status driver instance.
7757 *
7758 * @returns VBox status.
7759 * @param pDrvIns The driver instance data.
7760 */
7761DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7762{
7763 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7764 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7765 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
7766
7767 if (pData->papLeds)
7768 {
7769 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7770 while (iLed-- > 0)
7771 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7772 }
7773}
7774
7775
7776/**
7777 * Construct a status driver instance.
7778 *
7779 * @copydoc FNPDMDRVCONSTRUCT
7780 */
7781DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
7782{
7783 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7784 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7785 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
7786
7787 /*
7788 * Validate configuration.
7789 */
7790 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0First\0Last\0"))
7791 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7792 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
7793 ("Configuration error: Not possible to attach anything to this driver!\n"),
7794 VERR_PDM_DRVINS_NO_ATTACH);
7795
7796 /*
7797 * Data.
7798 */
7799 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7800 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7801
7802 /*
7803 * Read config.
7804 */
7805 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pData->papLeds);
7806 if (RT_FAILURE(rc))
7807 {
7808 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
7809 return rc;
7810 }
7811
7812 rc = CFGMR3QueryU32(pCfg, "First", &pData->iFirstLUN);
7813 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7814 pData->iFirstLUN = 0;
7815 else if (RT_FAILURE(rc))
7816 {
7817 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
7818 return rc;
7819 }
7820
7821 rc = CFGMR3QueryU32(pCfg, "Last", &pData->iLastLUN);
7822 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7823 pData->iLastLUN = 0;
7824 else if (RT_FAILURE(rc))
7825 {
7826 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
7827 return rc;
7828 }
7829 if (pData->iFirstLUN > pData->iLastLUN)
7830 {
7831 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7832 return VERR_GENERAL_FAILURE;
7833 }
7834
7835 /*
7836 * Get the ILedPorts interface of the above driver/device and
7837 * query the LEDs we want.
7838 */
7839 pData->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
7840 AssertMsgReturn(pData->pLedPorts, ("Configuration error: No led ports interface above!\n"),
7841 VERR_PDM_MISSING_INTERFACE_ABOVE);
7842
7843 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; ++i)
7844 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7845
7846 return VINF_SUCCESS;
7847}
7848
7849
7850/**
7851 * Keyboard driver registration record.
7852 */
7853const PDMDRVREG Console::DrvStatusReg =
7854{
7855 /* u32Version */
7856 PDM_DRVREG_VERSION,
7857 /* szName */
7858 "MainStatus",
7859 /* szRCMod */
7860 "",
7861 /* szR0Mod */
7862 "",
7863 /* pszDescription */
7864 "Main status driver (Main as in the API).",
7865 /* fFlags */
7866 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7867 /* fClass. */
7868 PDM_DRVREG_CLASS_STATUS,
7869 /* cMaxInstances */
7870 ~0,
7871 /* cbInstance */
7872 sizeof(DRVMAINSTATUS),
7873 /* pfnConstruct */
7874 Console::drvStatus_Construct,
7875 /* pfnDestruct */
7876 Console::drvStatus_Destruct,
7877 /* pfnRelocate */
7878 NULL,
7879 /* pfnIOCtl */
7880 NULL,
7881 /* pfnPowerOn */
7882 NULL,
7883 /* pfnReset */
7884 NULL,
7885 /* pfnSuspend */
7886 NULL,
7887 /* pfnResume */
7888 NULL,
7889 /* pfnAttach */
7890 NULL,
7891 /* pfnDetach */
7892 NULL,
7893 /* pfnPowerOff */
7894 NULL,
7895 /* pfnSoftReset */
7896 NULL,
7897 /* u32EndVersion */
7898 PDM_DRVREG_VERSION
7899};
7900
7901/* 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