VirtualBox

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

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

Main: live snapshot merging. initially limited to forward merging (i.e. everything but the first snapshot can be deleted)

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