VirtualBox

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

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

VirtualBox::RegisterCallback,Console::RegisterCallback: Explicitly query the interface instead of trusting it to be of the right kind. (ComPtr<> doesn't throw errors if it's QueryInterface fails, so we'll crash if we're not careful here.)

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