VirtualBox

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

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

Main/Snapshot+Console: implement reparenting children as part of a live merge, and remove the corresponding blockers in the code which prevented deleting the first snapshot

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 262.3 KB
Line 
1/* $Id: ConsoleImpl.cpp 28873 2010-04-28 14:55:35Z 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 /* We will need to release the lock before doing the actual merge */
4295 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4296
4297 /* paranoia - we don't want merges to happen while teleporting etc. */
4298 switch (mMachineState)
4299 {
4300 case MachineState_DeletingSnapshotOnline:
4301 case MachineState_DeletingSnapshotPaused:
4302 break;
4303
4304 default:
4305 return setError(VBOX_E_INVALID_VM_STATE,
4306 tr("Invalid machine state: %s"),
4307 Global::stringifyMachineState(mMachineState));
4308 }
4309
4310 SafeIfaceArray<IStorageController> ctrls;
4311 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
4312 AssertComRC(rc);
4313 LONG lDev;
4314 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
4315 AssertComRC(rc);
4316 LONG lPort;
4317 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
4318 AssertComRC(rc);
4319 IMedium *pMedium;
4320 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
4321 AssertComRC(rc);
4322 Bstr mediumLocation;
4323 if (pMedium)
4324 {
4325 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
4326 AssertComRC(rc);
4327 }
4328
4329 Bstr attCtrlName;
4330 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
4331 AssertComRC(rc);
4332 ComPtr<IStorageController> ctrl;
4333 for (size_t i = 0; i < ctrls.size(); ++i)
4334 {
4335 Bstr ctrlName;
4336 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
4337 AssertComRC(rc);
4338 if (attCtrlName == ctrlName)
4339 {
4340 ctrl = ctrls[i];
4341 break;
4342 }
4343 }
4344 if (ctrl.isNull())
4345 {
4346 return setError(E_FAIL,
4347 tr("Could not find storage controller '%ls'"), attCtrlName.raw());
4348 }
4349 StorageControllerType_T enmCtrlType;
4350 rc = ctrl->COMGETTER(ControllerType)(&enmCtrlType);
4351 AssertComRC(rc);
4352 const char *pcszDevice = convertControllerTypeToDev(enmCtrlType);
4353
4354 StorageBus_T enmBus;
4355 rc = ctrl->COMGETTER(Bus)(&enmBus);
4356 AssertComRC(rc);
4357 ULONG uInstance;
4358 rc = ctrl->COMGETTER(Instance)(&uInstance);
4359 AssertComRC(rc);
4360 IoBackendType_T enmIoBackend;
4361 rc = ctrl->COMGETTER(IoBackend)(&enmIoBackend);
4362 AssertComRC(rc);
4363
4364 unsigned uLUN;
4365 rc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4366 AssertComRCReturnRC(rc);
4367
4368 alock.release();
4369
4370 /* Pause the VM, as it might have pending IO on this drive */
4371 VMSTATE enmVMState = VMR3GetState(pVM);
4372 if (mMachineState == MachineState_DeletingSnapshotOnline)
4373 {
4374 LogFlowFunc(("Suspending the VM...\n"));
4375 /* disable the callback to prevent Console-level state change */
4376 mVMStateChangeCallbackDisabled = true;
4377 int vrc2 = VMR3Suspend(pVM);
4378 mVMStateChangeCallbackDisabled = false;
4379 AssertRCReturn(vrc2, E_FAIL);
4380 }
4381
4382 vrc = VMR3ReqCallWait(pVM,
4383 VMCPUID_ANY,
4384 (PFNRT)reconfigureMediumAttachment,
4385 11,
4386 pVM,
4387 pcszDevice,
4388 uInstance,
4389 enmBus,
4390 enmIoBackend,
4391 true /* fSetupMerge */,
4392 aSourceIdx,
4393 aTargetIdx,
4394 aMediumAttachment,
4395 mMachineState,
4396 &rc);
4397 /* error handling is after resuming the VM */
4398
4399 if (mMachineState == MachineState_DeletingSnapshotOnline)
4400 {
4401 LogFlowFunc(("Resuming the VM...\n"));
4402 /* disable the callback to prevent Console-level state change */
4403 mVMStateChangeCallbackDisabled = true;
4404 int vrc2 = VMR3Resume(pVM);
4405 mVMStateChangeCallbackDisabled = false;
4406 AssertRC(vrc2);
4407 if (RT_FAILURE(vrc2))
4408 {
4409 /* too bad, we failed. try to sync the console state with the VMM state */
4410 vmstateChangeCallback(pVM, VMSTATE_SUSPENDED, enmVMState, this);
4411 }
4412 }
4413
4414 if (RT_FAILURE(vrc))
4415 return setError(E_FAIL, tr("%Rrc"), vrc);
4416 if (FAILED(rc))
4417 return rc;
4418
4419 PPDMIBASE pIBase = NULL;
4420 PPDMIMEDIA pIMedium = NULL;
4421 vrc = PDMR3QueryDriverOnLun(pVM, pcszDevice, uInstance, uLUN, "VD", &pIBase);
4422 if (RT_SUCCESS(vrc))
4423 {
4424 if (pIBase)
4425 {
4426 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
4427 if (!pIMedium)
4428 return setError(E_FAIL, tr("could not query medium interface of controller"));
4429 }
4430 else
4431 return setError(E_FAIL, tr("could not query base interface of controller"));
4432 }
4433
4434 /* Finally trigger the merge. */
4435 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
4436 if (RT_FAILURE(vrc))
4437 return setError(E_FAIL, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
4438
4439 /* Pause the VM, as it might have pending IO on this drive */
4440 enmVMState = VMR3GetState(pVM);
4441 if (mMachineState == MachineState_DeletingSnapshotOnline)
4442 {
4443 LogFlowFunc(("Suspending the VM...\n"));
4444 /* disable the callback to prevent Console-level state change */
4445 mVMStateChangeCallbackDisabled = true;
4446 int vrc2 = VMR3Suspend(pVM);
4447 mVMStateChangeCallbackDisabled = false;
4448 AssertRCReturn(vrc2, E_FAIL);
4449 }
4450
4451 /* Update medium chain and state now, so that the VM can continue. */
4452 rc = mControl->FinishOnlineMergeMedium(aMediumAttachment, aSource, aTarget,
4453 aMergeForward, aParentForTarget,
4454 ComSafeArrayInArg(aChildrenToReparent));
4455
4456 vrc = VMR3ReqCallWait(pVM,
4457 VMCPUID_ANY,
4458 (PFNRT)reconfigureMediumAttachment,
4459 11,
4460 pVM,
4461 pcszDevice,
4462 uInstance,
4463 enmBus,
4464 enmIoBackend,
4465 false /* fSetupMerge */,
4466 0 /* uMergeSource */,
4467 0 /* uMergeTarget */,
4468 aMediumAttachment,
4469 mMachineState,
4470 &rc);
4471 /* error handling is after resuming the VM */
4472
4473 if (mMachineState == MachineState_DeletingSnapshotOnline)
4474 {
4475 LogFlowFunc(("Resuming the VM...\n"));
4476 /* disable the callback to prevent Console-level state change */
4477 mVMStateChangeCallbackDisabled = true;
4478 int vrc2 = VMR3Resume(pVM);
4479 mVMStateChangeCallbackDisabled = false;
4480 AssertRC(vrc2);
4481 if (RT_FAILURE(vrc2))
4482 {
4483 /* too bad, we failed. try to sync the console state with the VMM state */
4484 vmstateChangeCallback(pVM, VMSTATE_SUSPENDED, enmVMState, this);
4485 }
4486 }
4487
4488 if (RT_FAILURE(vrc))
4489 return setError(E_FAIL, tr("%Rrc"), vrc);
4490 if (FAILED(rc))
4491 return rc;
4492
4493 return rc;
4494}
4495
4496
4497/**
4498 * Gets called by Session::UpdateMachineState()
4499 * (IInternalSessionControl::updateMachineState()).
4500 *
4501 * Must be called only in certain cases (see the implementation).
4502 *
4503 * @note Locks this object for writing.
4504 */
4505HRESULT Console::updateMachineState(MachineState_T aMachineState)
4506{
4507 AutoCaller autoCaller(this);
4508 AssertComRCReturnRC(autoCaller.rc());
4509
4510 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4511
4512 AssertReturn( mMachineState == MachineState_Saving
4513 || mMachineState == MachineState_LiveSnapshotting
4514 || mMachineState == MachineState_RestoringSnapshot
4515 || mMachineState == MachineState_DeletingSnapshot
4516 || mMachineState == MachineState_DeletingSnapshotOnline
4517 || mMachineState == MachineState_DeletingSnapshotPaused
4518 , E_FAIL);
4519
4520 return setMachineStateLocally(aMachineState);
4521}
4522
4523/**
4524 * @note Locks this object for writing.
4525 */
4526void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
4527 uint32_t xHot, uint32_t yHot,
4528 uint32_t width, uint32_t height,
4529 void *pShape)
4530{
4531#if 0
4532 LogFlowThisFuncEnter();
4533 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
4534 fVisible, fAlpha, xHot, yHot, width, height, pShape));
4535#endif
4536
4537 AutoCaller autoCaller(this);
4538 AssertComRCReturnVoid(autoCaller.rc());
4539
4540 /* We need a write lock because we alter the cached callback data */
4541 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4542
4543 /* Save the callback arguments */
4544 mCallbackData.mpsc.visible = fVisible;
4545 mCallbackData.mpsc.alpha = fAlpha;
4546 mCallbackData.mpsc.xHot = xHot;
4547 mCallbackData.mpsc.yHot = yHot;
4548 mCallbackData.mpsc.width = width;
4549 mCallbackData.mpsc.height = height;
4550
4551 /* start with not valid */
4552 bool wasValid = mCallbackData.mpsc.valid;
4553 mCallbackData.mpsc.valid = false;
4554
4555 if (pShape != NULL)
4556 {
4557 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
4558 cb = ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
4559 /* try to reuse the old shape buffer if the size is the same */
4560 if (!wasValid)
4561 mCallbackData.mpsc.shape = NULL;
4562 else
4563 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
4564 {
4565 RTMemFree(mCallbackData.mpsc.shape);
4566 mCallbackData.mpsc.shape = NULL;
4567 }
4568 if (mCallbackData.mpsc.shape == NULL)
4569 {
4570 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ(cb);
4571 AssertReturnVoid(mCallbackData.mpsc.shape);
4572 }
4573 mCallbackData.mpsc.shapeSize = cb;
4574 memcpy(mCallbackData.mpsc.shape, pShape, cb);
4575 }
4576 else
4577 {
4578 if (wasValid && mCallbackData.mpsc.shape != NULL)
4579 RTMemFree(mCallbackData.mpsc.shape);
4580 mCallbackData.mpsc.shape = NULL;
4581 mCallbackData.mpsc.shapeSize = 0;
4582 }
4583
4584 mCallbackData.mpsc.valid = true;
4585
4586 CallbackList::iterator it = mCallbacks.begin();
4587 while (it != mCallbacks.end())
4588 (*it++)->OnMousePointerShapeChange(fVisible, fAlpha, xHot, yHot,
4589 width, height, (BYTE *) pShape);
4590
4591#if 0
4592 LogFlowThisFuncLeave();
4593#endif
4594}
4595
4596/**
4597 * @note Locks this object for writing.
4598 */
4599void Console::onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative, BOOL needsHostCursor)
4600{
4601 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
4602 supportsAbsolute, supportsRelative, needsHostCursor));
4603
4604 AutoCaller autoCaller(this);
4605 AssertComRCReturnVoid(autoCaller.rc());
4606
4607 /* We need a write lock because we alter the cached callback data */
4608 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4609
4610 /* save the callback arguments */
4611 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
4612 mCallbackData.mcc.supportsRelative = supportsRelative;
4613 mCallbackData.mcc.needsHostCursor = needsHostCursor;
4614 mCallbackData.mcc.valid = true;
4615
4616 CallbackList::iterator it = mCallbacks.begin();
4617 while (it != mCallbacks.end())
4618 {
4619 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
4620 (*it++)->OnMouseCapabilityChange(supportsAbsolute, supportsRelative, needsHostCursor);
4621 }
4622}
4623
4624/**
4625 * @note Locks this object for reading.
4626 */
4627void Console::onStateChange(MachineState_T machineState)
4628{
4629 AutoCaller autoCaller(this);
4630 AssertComRCReturnVoid(autoCaller.rc());
4631
4632 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4633
4634 CallbackList::iterator it = mCallbacks.begin();
4635 while (it != mCallbacks.end())
4636 (*it++)->OnStateChange(machineState);
4637}
4638
4639/**
4640 * @note Locks this object for reading.
4641 */
4642void Console::onAdditionsStateChange()
4643{
4644 AutoCaller autoCaller(this);
4645 AssertComRCReturnVoid(autoCaller.rc());
4646
4647 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4648
4649 CallbackList::iterator it = mCallbacks.begin();
4650 while (it != mCallbacks.end())
4651 (*it++)->OnAdditionsStateChange();
4652}
4653
4654/**
4655 * @note Locks this object for reading.
4656 */
4657void Console::onAdditionsOutdated()
4658{
4659 AutoCaller autoCaller(this);
4660 AssertComRCReturnVoid(autoCaller.rc());
4661
4662 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4663
4664 /** @todo Use the On-Screen Display feature to report the fact.
4665 * The user should be told to install additions that are
4666 * provided with the current VBox build:
4667 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
4668 */
4669}
4670
4671/**
4672 * @note Locks this object for writing.
4673 */
4674void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
4675{
4676 AutoCaller autoCaller(this);
4677 AssertComRCReturnVoid(autoCaller.rc());
4678
4679 /* We need a write lock because we alter the cached callback data */
4680 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4681
4682 /* save the callback arguments */
4683 mCallbackData.klc.numLock = fNumLock;
4684 mCallbackData.klc.capsLock = fCapsLock;
4685 mCallbackData.klc.scrollLock = fScrollLock;
4686 mCallbackData.klc.valid = true;
4687
4688 CallbackList::iterator it = mCallbacks.begin();
4689 while (it != mCallbacks.end())
4690 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
4691}
4692
4693/**
4694 * @note Locks this object for reading.
4695 */
4696void Console::onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
4697 IVirtualBoxErrorInfo *aError)
4698{
4699 AutoCaller autoCaller(this);
4700 AssertComRCReturnVoid(autoCaller.rc());
4701
4702 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4703
4704 CallbackList::iterator it = mCallbacks.begin();
4705 while (it != mCallbacks.end())
4706 (*it++)->OnUSBDeviceStateChange(aDevice, aAttached, aError);
4707}
4708
4709/**
4710 * @note Locks this object for reading.
4711 */
4712void Console::onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
4713{
4714 AutoCaller autoCaller(this);
4715 AssertComRCReturnVoid(autoCaller.rc());
4716
4717 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4718
4719 CallbackList::iterator it = mCallbacks.begin();
4720 while (it != mCallbacks.end())
4721 (*it++)->OnRuntimeError(aFatal, aErrorID, aMessage);
4722}
4723
4724/**
4725 * @note Locks this object for reading.
4726 */
4727HRESULT Console::onShowWindow(BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
4728{
4729 AssertReturn(aCanShow, E_POINTER);
4730 AssertReturn(aWinId, E_POINTER);
4731
4732 *aCanShow = FALSE;
4733 *aWinId = 0;
4734
4735 AutoCaller autoCaller(this);
4736 AssertComRCReturnRC(autoCaller.rc());
4737
4738 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4739
4740 HRESULT rc = S_OK;
4741 CallbackList::iterator it = mCallbacks.begin();
4742
4743 if (aCheck)
4744 {
4745 while (it != mCallbacks.end())
4746 {
4747 BOOL canShow = FALSE;
4748 rc = (*it++)->OnCanShowWindow(&canShow);
4749 AssertComRC(rc);
4750 if (FAILED(rc) || !canShow)
4751 return rc;
4752 }
4753 *aCanShow = TRUE;
4754 }
4755 else
4756 {
4757 while (it != mCallbacks.end())
4758 {
4759 ULONG64 winId = 0;
4760 rc = (*it++)->OnShowWindow(&winId);
4761 AssertComRC(rc);
4762 if (FAILED(rc))
4763 return rc;
4764 /* only one callback may return non-null winId */
4765 Assert(*aWinId == 0 || winId == 0);
4766 if (*aWinId == 0)
4767 *aWinId = winId;
4768 }
4769 }
4770
4771 return S_OK;
4772}
4773
4774// private methods
4775////////////////////////////////////////////////////////////////////////////////
4776
4777/**
4778 * Increases the usage counter of the mpVM pointer. Guarantees that
4779 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
4780 * is called.
4781 *
4782 * If this method returns a failure, the caller is not allowed to use mpVM
4783 * and may return the failed result code to the upper level. This method sets
4784 * the extended error info on failure if \a aQuiet is false.
4785 *
4786 * Setting \a aQuiet to true is useful for methods that don't want to return
4787 * the failed result code to the caller when this method fails (e.g. need to
4788 * silently check for the mpVM availability).
4789 *
4790 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
4791 * returned instead of asserting. Having it false is intended as a sanity check
4792 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
4793 *
4794 * @param aQuiet true to suppress setting error info
4795 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
4796 * (otherwise this method will assert if mpVM is NULL)
4797 *
4798 * @note Locks this object for writing.
4799 */
4800HRESULT Console::addVMCaller(bool aQuiet /* = false */,
4801 bool aAllowNullVM /* = false */)
4802{
4803 AutoCaller autoCaller(this);
4804 AssertComRCReturnRC(autoCaller.rc());
4805
4806 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4807
4808 if (mVMDestroying)
4809 {
4810 /* powerDown() is waiting for all callers to finish */
4811 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
4812 tr("Virtual machine is being powered down"));
4813 }
4814
4815 if (mpVM == NULL)
4816 {
4817 Assert(aAllowNullVM == true);
4818
4819 /* The machine is not powered up */
4820 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
4821 tr("Virtual machine is not powered up"));
4822 }
4823
4824 ++ mVMCallers;
4825
4826 return S_OK;
4827}
4828
4829/**
4830 * Decreases the usage counter of the mpVM pointer. Must always complete
4831 * the addVMCaller() call after the mpVM pointer is no more necessary.
4832 *
4833 * @note Locks this object for writing.
4834 */
4835void Console::releaseVMCaller()
4836{
4837 AutoCaller autoCaller(this);
4838 AssertComRCReturnVoid(autoCaller.rc());
4839
4840 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4841
4842 AssertReturnVoid(mpVM != NULL);
4843
4844 Assert(mVMCallers > 0);
4845 --mVMCallers;
4846
4847 if (mVMCallers == 0 && mVMDestroying)
4848 {
4849 /* inform powerDown() there are no more callers */
4850 RTSemEventSignal(mVMZeroCallersSem);
4851 }
4852}
4853
4854/**
4855 * Initialize the release logging facility. In case something
4856 * goes wrong, there will be no release logging. Maybe in the future
4857 * we can add some logic to use different file names in this case.
4858 * Note that the logic must be in sync with Machine::DeleteSettings().
4859 */
4860HRESULT Console::consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
4861{
4862 HRESULT hrc = S_OK;
4863
4864 Bstr logFolder;
4865 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
4866 if (FAILED(hrc)) return hrc;
4867
4868 Utf8Str logDir = logFolder;
4869
4870 /* make sure the Logs folder exists */
4871 Assert(logDir.length());
4872 if (!RTDirExists(logDir.c_str()))
4873 RTDirCreateFullPath(logDir.c_str(), 0777);
4874
4875 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
4876 logDir.raw(), RTPATH_DELIMITER);
4877 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
4878 logDir.raw(), RTPATH_DELIMITER);
4879
4880 /*
4881 * Age the old log files
4882 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
4883 * Overwrite target files in case they exist.
4884 */
4885 ComPtr<IVirtualBox> virtualBox;
4886 aMachine->COMGETTER(Parent)(virtualBox.asOutParam());
4887 ComPtr<ISystemProperties> systemProperties;
4888 virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4889 ULONG cHistoryFiles = 3;
4890 systemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
4891 if (cHistoryFiles)
4892 {
4893 for (int i = cHistoryFiles-1; i >= 0; i--)
4894 {
4895 Utf8Str *files[] = { &logFile, &pngFile };
4896 Utf8Str oldName, newName;
4897
4898 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++ j)
4899 {
4900 if (i > 0)
4901 oldName = Utf8StrFmt("%s.%d", files[j]->raw(), i);
4902 else
4903 oldName = *files[j];
4904 newName = Utf8StrFmt("%s.%d", files[j]->raw(), i + 1);
4905 /* If the old file doesn't exist, delete the new file (if it
4906 * exists) to provide correct rotation even if the sequence is
4907 * broken */
4908 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
4909 == VERR_FILE_NOT_FOUND)
4910 RTFileDelete(newName.c_str());
4911 }
4912 }
4913 }
4914
4915 PRTLOGGER loggerRelease;
4916 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
4917 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
4918#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
4919 fFlags |= RTLOGFLAGS_USECRLF;
4920#endif
4921 char szError[RTPATH_MAX + 128] = "";
4922 int vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
4923 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
4924 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
4925 if (RT_SUCCESS(vrc))
4926 {
4927 /* some introductory information */
4928 RTTIMESPEC timeSpec;
4929 char szTmp[256];
4930 RTTimeSpecToString(RTTimeNow(&timeSpec), szTmp, sizeof(szTmp));
4931 RTLogRelLogger(loggerRelease, 0, ~0U,
4932 "VirtualBox %s r%u %s (%s %s) release log\n"
4933#ifdef VBOX_BLEEDING_EDGE
4934 "EXPERIMENTAL build " VBOX_BLEEDING_EDGE "\n"
4935#endif
4936 "Log opened %s\n",
4937 VBOX_VERSION_STRING, RTBldCfgRevision(), VBOX_BUILD_TARGET,
4938 __DATE__, __TIME__, szTmp);
4939
4940 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
4941 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4942 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Product: %s\n", szTmp);
4943 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
4944 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4945 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Release: %s\n", szTmp);
4946 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
4947 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4948 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Version: %s\n", szTmp);
4949 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
4950 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4951 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Service Pack: %s\n", szTmp);
4952
4953 ComPtr<IHost> host;
4954 virtualBox->COMGETTER(Host)(host.asOutParam());
4955 ULONG cMbHostRam = 0;
4956 ULONG cMbHostRamAvail = 0;
4957 host->COMGETTER(MemorySize)(&cMbHostRam);
4958 host->COMGETTER(MemoryAvailable)(&cMbHostRamAvail);
4959 RTLogRelLogger(loggerRelease, 0, ~0U, "Host RAM: %uMB RAM, available: %uMB\n",
4960 cMbHostRam, cMbHostRamAvail);
4961
4962 /* the package type is interesting for Linux distributions */
4963 char szExecName[RTPATH_MAX];
4964 char *pszExecName = RTProcGetExecutableName(szExecName, sizeof(szExecName));
4965 RTLogRelLogger(loggerRelease, 0, ~0U,
4966 "Executable: %s\n"
4967 "Process ID: %u\n"
4968 "Package type: %s"
4969#ifdef VBOX_OSE
4970 " (OSE)"
4971#endif
4972 "\n",
4973 pszExecName ? pszExecName : "unknown",
4974 RTProcSelf(),
4975 VBOX_PACKAGE_STRING);
4976
4977 /* register this logger as the release logger */
4978 RTLogRelSetDefaultInstance(loggerRelease);
4979 hrc = S_OK;
4980
4981 /* Explicitly flush the log in case of VBOX_RELEASE_LOG=buffered. */
4982 RTLogFlush(loggerRelease);
4983 }
4984 else
4985 hrc = setError(E_FAIL,
4986 tr("Failed to open release log (%s, %Rrc)"),
4987 szError, vrc);
4988
4989 /* If we've made any directory changes, flush the directory to increase
4990 the likelyhood that the log file will be usable after a system panic.
4991
4992 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
4993 is missing. Just don't have too high hopes for this to help. */
4994 if (SUCCEEDED(hrc) || cHistoryFiles)
4995 RTDirFlush(logDir.c_str());
4996
4997 return hrc;
4998}
4999
5000/**
5001 * Common worker for PowerUp and PowerUpPaused.
5002 *
5003 * @returns COM status code.
5004 *
5005 * @param aProgress Where to return the progress object.
5006 * @param aPaused true if PowerUpPaused called.
5007 *
5008 * @todo move down to powerDown();
5009 */
5010HRESULT Console::powerUp(IProgress **aProgress, bool aPaused)
5011{
5012 if (aProgress == NULL)
5013 return E_POINTER;
5014
5015 LogFlowThisFuncEnter();
5016 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
5017
5018 AutoCaller autoCaller(this);
5019 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5020
5021 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5022
5023 if (Global::IsOnlineOrTransient(mMachineState))
5024 return setError(VBOX_E_INVALID_VM_STATE,
5025 tr("Virtual machine is already running or busy (machine state: %s)"),
5026 Global::stringifyMachineState(mMachineState));
5027
5028 HRESULT rc = S_OK;
5029
5030 /* the network cards will undergo a quick consistency check */
5031 for (ULONG slot = 0;
5032 slot < SchemaDefs::NetworkAdapterCount;
5033 ++slot)
5034 {
5035 ComPtr<INetworkAdapter> adapter;
5036 mMachine->GetNetworkAdapter(slot, adapter.asOutParam());
5037 BOOL enabled = FALSE;
5038 adapter->COMGETTER(Enabled)(&enabled);
5039 if (!enabled)
5040 continue;
5041
5042 NetworkAttachmentType_T netattach;
5043 adapter->COMGETTER(AttachmentType)(&netattach);
5044 switch (netattach)
5045 {
5046 case NetworkAttachmentType_Bridged:
5047 {
5048#ifdef RT_OS_WINDOWS
5049 /* a valid host interface must have been set */
5050 Bstr hostif;
5051 adapter->COMGETTER(HostInterface)(hostif.asOutParam());
5052 if (!hostif)
5053 {
5054 return setError(VBOX_E_HOST_ERROR,
5055 tr("VM cannot start because host interface networking requires a host interface name to be set"));
5056 }
5057 ComPtr<IVirtualBox> virtualBox;
5058 mMachine->COMGETTER(Parent)(virtualBox.asOutParam());
5059 ComPtr<IHost> host;
5060 virtualBox->COMGETTER(Host)(host.asOutParam());
5061 ComPtr<IHostNetworkInterface> hostInterface;
5062 if (!SUCCEEDED(host->FindHostNetworkInterfaceByName(hostif, hostInterface.asOutParam())))
5063 {
5064 return setError(VBOX_E_HOST_ERROR,
5065 tr("VM cannot start because the host interface '%ls' does not exist"),
5066 hostif.raw());
5067 }
5068#endif /* RT_OS_WINDOWS */
5069 break;
5070 }
5071 default:
5072 break;
5073 }
5074 }
5075
5076 /* Read console data stored in the saved state file (if not yet done) */
5077 rc = loadDataFromSavedState();
5078 if (FAILED(rc)) return rc;
5079
5080 /* Check all types of shared folders and compose a single list */
5081 SharedFolderDataMap sharedFolders;
5082 {
5083 /* first, insert global folders */
5084 for (SharedFolderDataMap::const_iterator it = mGlobalSharedFolders.begin();
5085 it != mGlobalSharedFolders.end(); ++ it)
5086 sharedFolders[it->first] = it->second;
5087
5088 /* second, insert machine folders */
5089 for (SharedFolderDataMap::const_iterator it = mMachineSharedFolders.begin();
5090 it != mMachineSharedFolders.end(); ++ it)
5091 sharedFolders[it->first] = it->second;
5092
5093 /* third, insert console folders */
5094 for (SharedFolderMap::const_iterator it = mSharedFolders.begin();
5095 it != mSharedFolders.end(); ++ it)
5096 sharedFolders[it->first] = SharedFolderData(it->second->getHostPath(), it->second->isWritable());
5097 }
5098
5099 Bstr savedStateFile;
5100
5101 /*
5102 * Saved VMs will have to prove that their saved states seem kosher.
5103 */
5104 if (mMachineState == MachineState_Saved)
5105 {
5106 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
5107 if (FAILED(rc)) return rc;
5108 ComAssertRet(!!savedStateFile, E_FAIL);
5109 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
5110 if (RT_FAILURE(vrc))
5111 return setError(VBOX_E_FILE_ERROR,
5112 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
5113 savedStateFile.raw(), vrc);
5114 }
5115
5116 /* test and clear the TeleporterEnabled property */
5117 BOOL fTeleporterEnabled;
5118 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
5119 if (FAILED(rc)) return rc;
5120#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
5121 if (fTeleporterEnabled)
5122 {
5123 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
5124 if (FAILED(rc)) return rc;
5125 }
5126#endif
5127
5128 /* create a progress object to track progress of this operation */
5129 ComObjPtr<Progress> powerupProgress;
5130 powerupProgress.createObject();
5131 Bstr progressDesc;
5132 if (mMachineState == MachineState_Saved)
5133 progressDesc = tr("Restoring virtual machine");
5134 else if (fTeleporterEnabled)
5135 progressDesc = tr("Teleporting virtual machine");
5136 else
5137 progressDesc = tr("Starting virtual machine");
5138 rc = powerupProgress->init(static_cast<IConsole *>(this),
5139 progressDesc,
5140 fTeleporterEnabled /* aCancelable */);
5141 if (FAILED(rc)) return rc;
5142
5143 /* setup task object and thread to carry out the operation
5144 * asynchronously */
5145
5146 std::auto_ptr<VMPowerUpTask> task(new VMPowerUpTask(this, powerupProgress));
5147 ComAssertComRCRetRC(task->rc());
5148
5149 task->mSetVMErrorCallback = setVMErrorCallback;
5150 task->mConfigConstructor = configConstructor;
5151 task->mSharedFolders = sharedFolders;
5152 task->mStartPaused = aPaused;
5153 if (mMachineState == MachineState_Saved)
5154 task->mSavedStateFile = savedStateFile;
5155 task->mTeleporterEnabled = fTeleporterEnabled;
5156
5157 /* Reset differencing hard disks for which autoReset is true,
5158 * but only if the machine has no snapshots OR the current snapshot
5159 * is an OFFLINE snapshot; otherwise we would reset the current differencing
5160 * image of an ONLINE snapshot which contains the disk state of the machine
5161 * while it was previously running, but without the corresponding machine
5162 * state, which is equivalent to powering off a running machine and not
5163 * good idea
5164 */
5165 ComPtr<ISnapshot> pCurrentSnapshot;
5166 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
5167 if (FAILED(rc)) return rc;
5168
5169 BOOL fCurrentSnapshotIsOnline = false;
5170 if (pCurrentSnapshot)
5171 {
5172 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
5173 if (FAILED(rc)) return rc;
5174 }
5175
5176 if (!fCurrentSnapshotIsOnline)
5177 {
5178 LogFlowThisFunc(("Looking for immutable images to reset\n"));
5179
5180 com::SafeIfaceArray<IMediumAttachment> atts;
5181 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
5182 if (FAILED(rc)) return rc;
5183
5184 for (size_t i = 0;
5185 i < atts.size();
5186 ++i)
5187 {
5188 DeviceType_T devType;
5189 rc = atts[i]->COMGETTER(Type)(&devType);
5190 /** @todo later applies to floppies as well */
5191 if (devType == DeviceType_HardDisk)
5192 {
5193 ComPtr<IMedium> medium;
5194 rc = atts[i]->COMGETTER(Medium)(medium.asOutParam());
5195 if (FAILED(rc)) return rc;
5196
5197 /* needs autoreset? */
5198 BOOL autoReset = FALSE;
5199 rc = medium->COMGETTER(AutoReset)(&autoReset);
5200 if (FAILED(rc)) return rc;
5201
5202 if (autoReset)
5203 {
5204 ComPtr<IProgress> resetProgress;
5205 rc = medium->Reset(resetProgress.asOutParam());
5206 if (FAILED(rc)) return rc;
5207
5208 /* save for later use on the powerup thread */
5209 task->hardDiskProgresses.push_back(resetProgress);
5210 }
5211 }
5212 }
5213 }
5214 else
5215 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
5216
5217 rc = consoleInitReleaseLog(mMachine);
5218 if (FAILED(rc)) return rc;
5219
5220 /* pass the progress object to the caller if requested */
5221 if (aProgress)
5222 {
5223 if (task->hardDiskProgresses.size() == 0)
5224 {
5225 /* there are no other operations to track, return the powerup
5226 * progress only */
5227 powerupProgress.queryInterfaceTo(aProgress);
5228 }
5229 else
5230 {
5231 /* create a combined progress object */
5232 ComObjPtr<CombinedProgress> progress;
5233 progress.createObject();
5234 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
5235 progresses.push_back(ComPtr<IProgress> (powerupProgress));
5236 rc = progress->init(static_cast<IConsole *>(this),
5237 progressDesc, progresses.begin(),
5238 progresses.end());
5239 AssertComRCReturnRC(rc);
5240 progress.queryInterfaceTo(aProgress);
5241 }
5242 }
5243
5244 int vrc = RTThreadCreate(NULL, Console::powerUpThread, (void *) task.get(),
5245 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMPowerUp");
5246
5247 ComAssertMsgRCRet(vrc, ("Could not create VMPowerUp thread (%Rrc)", vrc),
5248 E_FAIL);
5249
5250 /* task is now owned by powerUpThread(), so release it */
5251 task.release();
5252
5253 /* finally, set the state: no right to fail in this method afterwards
5254 * since we've already started the thread and it is now responsible for
5255 * any error reporting and appropriate state change! */
5256
5257 if (mMachineState == MachineState_Saved)
5258 setMachineState(MachineState_Restoring);
5259 else if (fTeleporterEnabled)
5260 setMachineState(MachineState_TeleportingIn);
5261 else
5262 setMachineState(MachineState_Starting);
5263
5264 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
5265 LogFlowThisFuncLeave();
5266 return S_OK;
5267}
5268
5269/**
5270 * Internal power off worker routine.
5271 *
5272 * This method may be called only at certain places with the following meaning
5273 * as shown below:
5274 *
5275 * - if the machine state is either Running or Paused, a normal
5276 * Console-initiated powerdown takes place (e.g. PowerDown());
5277 * - if the machine state is Saving, saveStateThread() has successfully done its
5278 * job;
5279 * - if the machine state is Starting or Restoring, powerUpThread() has failed
5280 * to start/load the VM;
5281 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
5282 * as a result of the powerDown() call).
5283 *
5284 * Calling it in situations other than the above will cause unexpected behavior.
5285 *
5286 * Note that this method should be the only one that destroys mpVM and sets it
5287 * to NULL.
5288 *
5289 * @param aProgress Progress object to run (may be NULL).
5290 *
5291 * @note Locks this object for writing.
5292 *
5293 * @note Never call this method from a thread that called addVMCaller() or
5294 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
5295 * release(). Otherwise it will deadlock.
5296 */
5297HRESULT Console::powerDown(Progress *aProgress /*= NULL*/)
5298{
5299 LogFlowThisFuncEnter();
5300
5301 AutoCaller autoCaller(this);
5302 AssertComRCReturnRC(autoCaller.rc());
5303
5304 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5305
5306 /* Total # of steps for the progress object. Must correspond to the
5307 * number of "advance percent count" comments in this method! */
5308 enum { StepCount = 7 };
5309 /* current step */
5310 ULONG step = 0;
5311
5312 HRESULT rc = S_OK;
5313 int vrc = VINF_SUCCESS;
5314
5315 /* sanity */
5316 Assert(mVMDestroying == false);
5317
5318 Assert(mpVM != NULL);
5319
5320 AssertMsg( mMachineState == MachineState_Running
5321 || mMachineState == MachineState_Paused
5322 || mMachineState == MachineState_Stuck
5323 || mMachineState == MachineState_Starting
5324 || mMachineState == MachineState_Stopping
5325 || mMachineState == MachineState_Saving
5326 || mMachineState == MachineState_Restoring
5327 || mMachineState == MachineState_TeleportingPausedVM
5328 || mMachineState == MachineState_TeleportingIn
5329 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
5330
5331 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
5332 Global::stringifyMachineState(mMachineState), autoCaller.state() == InUninit));
5333
5334 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
5335 * VM has already powered itself off in vmstateChangeCallback() and is just
5336 * notifying Console about that. In case of Starting or Restoring,
5337 * powerUpThread() is calling us on failure, so the VM is already off at
5338 * that point. */
5339 if ( !mVMPoweredOff
5340 && ( mMachineState == MachineState_Starting
5341 || mMachineState == MachineState_Restoring
5342 || mMachineState == MachineState_TeleportingIn)
5343 )
5344 mVMPoweredOff = true;
5345
5346 /*
5347 * Go to Stopping state if not already there.
5348 *
5349 * Note that we don't go from Saving/Restoring to Stopping because
5350 * vmstateChangeCallback() needs it to set the state to Saved on
5351 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
5352 * while leaving the lock below, Saving or Restoring should be fine too.
5353 * Ditto for TeleportingPausedVM -> Teleported.
5354 */
5355 if ( mMachineState != MachineState_Saving
5356 && mMachineState != MachineState_Restoring
5357 && mMachineState != MachineState_Stopping
5358 && mMachineState != MachineState_TeleportingIn
5359 && mMachineState != MachineState_TeleportingPausedVM
5360 )
5361 setMachineState(MachineState_Stopping);
5362
5363 /* ----------------------------------------------------------------------
5364 * DONE with necessary state changes, perform the power down actions (it's
5365 * safe to leave the object lock now if needed)
5366 * ---------------------------------------------------------------------- */
5367
5368 /* Stop the VRDP server to prevent new clients connection while VM is being
5369 * powered off. */
5370 if (mConsoleVRDPServer)
5371 {
5372 LogFlowThisFunc(("Stopping VRDP server...\n"));
5373
5374 /* Leave the lock since EMT will call us back as addVMCaller()
5375 * in updateDisplayData(). */
5376 alock.leave();
5377
5378 mConsoleVRDPServer->Stop();
5379
5380 alock.enter();
5381 }
5382
5383 /* advance percent count */
5384 if (aProgress)
5385 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5386
5387
5388 /* ----------------------------------------------------------------------
5389 * Now, wait for all mpVM callers to finish their work if there are still
5390 * some on other threads. NO methods that need mpVM (or initiate other calls
5391 * that need it) may be called after this point
5392 * ---------------------------------------------------------------------- */
5393
5394 /* go to the destroying state to prevent from adding new callers */
5395 mVMDestroying = true;
5396
5397 if (mVMCallers > 0)
5398 {
5399 /* lazy creation */
5400 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
5401 RTSemEventCreate(&mVMZeroCallersSem);
5402
5403 LogFlowThisFunc(("Waiting for mpVM callers (%d) to drop to zero...\n",
5404 mVMCallers));
5405
5406 alock.leave();
5407
5408 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
5409
5410 alock.enter();
5411 }
5412
5413 /* advance percent count */
5414 if (aProgress)
5415 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5416
5417 vrc = VINF_SUCCESS;
5418
5419 /*
5420 * Power off the VM if not already done that.
5421 * Leave the lock since EMT will call vmstateChangeCallback.
5422 *
5423 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
5424 * VM-(guest-)initiated power off happened in parallel a ms before this
5425 * call. So far, we let this error pop up on the user's side.
5426 */
5427 if (!mVMPoweredOff)
5428 {
5429 LogFlowThisFunc(("Powering off the VM...\n"));
5430 alock.leave();
5431 vrc = VMR3PowerOff(mpVM);
5432 alock.enter();
5433 }
5434 else
5435 {
5436 /** @todo r=bird: Doesn't make sense. Please remove after 3.1 has been branched
5437 * off. */
5438 /* reset the flag for future re-use */
5439 mVMPoweredOff = false;
5440 }
5441
5442 /* advance percent count */
5443 if (aProgress)
5444 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5445
5446#ifdef VBOX_WITH_HGCM
5447 /* Shutdown HGCM services before destroying the VM. */
5448 if (mVMMDev)
5449 {
5450 LogFlowThisFunc(("Shutdown HGCM...\n"));
5451
5452 /* Leave the lock since EMT will call us back as addVMCaller() */
5453 alock.leave();
5454
5455 mVMMDev->hgcmShutdown();
5456
5457 alock.enter();
5458 }
5459
5460 /* advance percent count */
5461 if (aProgress)
5462 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5463
5464#endif /* VBOX_WITH_HGCM */
5465
5466 LogFlowThisFunc(("Ready for VM destruction.\n"));
5467
5468 /* If we are called from Console::uninit(), then try to destroy the VM even
5469 * on failure (this will most likely fail too, but what to do?..) */
5470 if (RT_SUCCESS(vrc) || autoCaller.state() == InUninit)
5471 {
5472 /* If the machine has an USB controller, release all USB devices
5473 * (symmetric to the code in captureUSBDevices()) */
5474 bool fHasUSBController = false;
5475 {
5476 PPDMIBASE pBase;
5477 vrc = PDMR3QueryLun(mpVM, "usb-ohci", 0, 0, &pBase);
5478 if (RT_SUCCESS(vrc))
5479 {
5480 fHasUSBController = true;
5481 detachAllUSBDevices(false /* aDone */);
5482 }
5483 }
5484
5485 /* Now we've got to destroy the VM as well. (mpVM is not valid beyond
5486 * this point). We leave the lock before calling VMR3Destroy() because
5487 * it will result into calling destructors of drivers associated with
5488 * Console children which may in turn try to lock Console (e.g. by
5489 * instantiating SafeVMPtr to access mpVM). It's safe here because
5490 * mVMDestroying is set which should prevent any activity. */
5491
5492 /* Set mpVM to NULL early just in case if some old code is not using
5493 * addVMCaller()/releaseVMCaller(). */
5494 PVM pVM = mpVM;
5495 mpVM = NULL;
5496
5497 LogFlowThisFunc(("Destroying the VM...\n"));
5498
5499 alock.leave();
5500
5501 vrc = VMR3Destroy(pVM);
5502
5503 /* take the lock again */
5504 alock.enter();
5505
5506 /* advance percent count */
5507 if (aProgress)
5508 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5509
5510 if (RT_SUCCESS(vrc))
5511 {
5512 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
5513 mMachineState));
5514 /* Note: the Console-level machine state change happens on the
5515 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
5516 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
5517 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
5518 * occurred yet. This is okay, because mMachineState is already
5519 * Stopping in this case, so any other attempt to call PowerDown()
5520 * will be rejected. */
5521 }
5522 else
5523 {
5524 /* bad bad bad, but what to do? */
5525 mpVM = pVM;
5526 rc = setError(VBOX_E_VM_ERROR,
5527 tr("Could not destroy the machine. (Error: %Rrc)"),
5528 vrc);
5529 }
5530
5531 /* Complete the detaching of the USB devices. */
5532 if (fHasUSBController)
5533 detachAllUSBDevices(true /* aDone */);
5534
5535 /* advance percent count */
5536 if (aProgress)
5537 aProgress->SetCurrentOperationProgress(99 * (++ step) / StepCount );
5538 }
5539 else
5540 {
5541 rc = setError(VBOX_E_VM_ERROR,
5542 tr("Could not power off the machine. (Error: %Rrc)"),
5543 vrc);
5544 }
5545
5546 /* Finished with destruction. Note that if something impossible happened and
5547 * we've failed to destroy the VM, mVMDestroying will remain true and
5548 * mMachineState will be something like Stopping, so most Console methods
5549 * will return an error to the caller. */
5550 if (mpVM == NULL)
5551 mVMDestroying = false;
5552
5553 if (SUCCEEDED(rc))
5554 {
5555 /* uninit dynamically allocated members of mCallbackData */
5556 if (mCallbackData.mpsc.valid)
5557 {
5558 if (mCallbackData.mpsc.shape != NULL)
5559 RTMemFree(mCallbackData.mpsc.shape);
5560 }
5561 memset(&mCallbackData, 0, sizeof(mCallbackData));
5562 }
5563
5564 /* complete the progress */
5565 if (aProgress)
5566 aProgress->notifyComplete(rc);
5567
5568 LogFlowThisFuncLeave();
5569 return rc;
5570}
5571
5572/**
5573 * @note Locks this object for writing.
5574 */
5575HRESULT Console::setMachineState(MachineState_T aMachineState,
5576 bool aUpdateServer /* = true */)
5577{
5578 AutoCaller autoCaller(this);
5579 AssertComRCReturnRC(autoCaller.rc());
5580
5581 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5582
5583 HRESULT rc = S_OK;
5584
5585 if (mMachineState != aMachineState)
5586 {
5587 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
5588 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
5589 mMachineState = aMachineState;
5590
5591 /// @todo (dmik)
5592 // possibly, we need to redo onStateChange() using the dedicated
5593 // Event thread, like it is done in VirtualBox. This will make it
5594 // much safer (no deadlocks possible if someone tries to use the
5595 // console from the callback), however, listeners will lose the
5596 // ability to synchronously react to state changes (is it really
5597 // necessary??)
5598 LogFlowThisFunc(("Doing onStateChange()...\n"));
5599 onStateChange(aMachineState);
5600 LogFlowThisFunc(("Done onStateChange()\n"));
5601
5602 if (aUpdateServer)
5603 {
5604 /* Server notification MUST be done from under the lock; otherwise
5605 * the machine state here and on the server might go out of sync
5606 * which can lead to various unexpected results (like the machine
5607 * state being >= MachineState_Running on the server, while the
5608 * session state is already SessionState_Closed at the same time
5609 * there).
5610 *
5611 * Cross-lock conditions should be carefully watched out: calling
5612 * UpdateState we will require Machine and SessionMachine locks
5613 * (remember that here we're holding the Console lock here, and also
5614 * all locks that have been entered by the thread before calling
5615 * this method).
5616 */
5617 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
5618 rc = mControl->UpdateState(aMachineState);
5619 LogFlowThisFunc(("mControl->UpdateState()=%08X\n", rc));
5620 }
5621 }
5622
5623 return rc;
5624}
5625
5626/**
5627 * Searches for a shared folder with the given logical name
5628 * in the collection of shared folders.
5629 *
5630 * @param aName logical name of the shared folder
5631 * @param aSharedFolder where to return the found object
5632 * @param aSetError whether to set the error info if the folder is
5633 * not found
5634 * @return
5635 * S_OK when found or E_INVALIDARG when not found
5636 *
5637 * @note The caller must lock this object for writing.
5638 */
5639HRESULT Console::findSharedFolder(CBSTR aName,
5640 ComObjPtr<SharedFolder> &aSharedFolder,
5641 bool aSetError /* = false */)
5642{
5643 /* sanity check */
5644 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
5645
5646 SharedFolderMap::const_iterator it = mSharedFolders.find(aName);
5647 if (it != mSharedFolders.end())
5648 {
5649 aSharedFolder = it->second;
5650 return S_OK;
5651 }
5652
5653 if (aSetError)
5654 setError(VBOX_E_FILE_ERROR,
5655 tr("Could not find a shared folder named '%ls'."),
5656 aName);
5657
5658 return VBOX_E_FILE_ERROR;
5659}
5660
5661/**
5662 * Fetches the list of global or machine shared folders from the server.
5663 *
5664 * @param aGlobal true to fetch global folders.
5665 *
5666 * @note The caller must lock this object for writing.
5667 */
5668HRESULT Console::fetchSharedFolders(BOOL aGlobal)
5669{
5670 /* sanity check */
5671 AssertReturn(AutoCaller(this).state() == InInit ||
5672 isWriteLockOnCurrentThread(), E_FAIL);
5673
5674 /* protect mpVM (if not NULL) */
5675 AutoVMCallerQuietWeak autoVMCaller(this);
5676
5677 HRESULT rc = S_OK;
5678
5679 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
5680
5681 if (aGlobal)
5682 {
5683 /// @todo grab & process global folders when they are done
5684 }
5685 else
5686 {
5687 SharedFolderDataMap oldFolders;
5688 if (online)
5689 oldFolders = mMachineSharedFolders;
5690
5691 mMachineSharedFolders.clear();
5692
5693 SafeIfaceArray<ISharedFolder> folders;
5694 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
5695 AssertComRCReturnRC(rc);
5696
5697 for (size_t i = 0; i < folders.size(); ++i)
5698 {
5699 ComPtr<ISharedFolder> folder = folders[i];
5700
5701 Bstr name;
5702 Bstr hostPath;
5703 BOOL writable;
5704
5705 rc = folder->COMGETTER(Name)(name.asOutParam());
5706 if (FAILED(rc)) break;
5707 rc = folder->COMGETTER(HostPath)(hostPath.asOutParam());
5708 if (FAILED(rc)) break;
5709 rc = folder->COMGETTER(Writable)(&writable);
5710
5711 mMachineSharedFolders.insert(std::make_pair(name, SharedFolderData(hostPath, writable)));
5712
5713 /* send changes to HGCM if the VM is running */
5714 /// @todo report errors as runtime warnings through VMSetError
5715 if (online)
5716 {
5717 SharedFolderDataMap::iterator it = oldFolders.find(name);
5718 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
5719 {
5720 /* a new machine folder is added or
5721 * the existing machine folder is changed */
5722 if (mSharedFolders.find(name) != mSharedFolders.end())
5723 ; /* the console folder exists, nothing to do */
5724 else
5725 {
5726 /* remove the old machine folder (when changed)
5727 * or the global folder if any (when new) */
5728 if (it != oldFolders.end() ||
5729 mGlobalSharedFolders.find(name) !=
5730 mGlobalSharedFolders.end())
5731 rc = removeSharedFolder(name);
5732 /* create the new machine folder */
5733 rc = createSharedFolder(name, SharedFolderData(hostPath, writable));
5734 }
5735 }
5736 /* forget the processed (or identical) folder */
5737 if (it != oldFolders.end())
5738 oldFolders.erase(it);
5739
5740 rc = S_OK;
5741 }
5742 }
5743
5744 AssertComRCReturnRC(rc);
5745
5746 /* process outdated (removed) folders */
5747 /// @todo report errors as runtime warnings through VMSetError
5748 if (online)
5749 {
5750 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
5751 it != oldFolders.end(); ++ it)
5752 {
5753 if (mSharedFolders.find(it->first) != mSharedFolders.end())
5754 ; /* the console folder exists, nothing to do */
5755 else
5756 {
5757 /* remove the outdated machine folder */
5758 rc = removeSharedFolder(it->first);
5759 /* create the global folder if there is any */
5760 SharedFolderDataMap::const_iterator git =
5761 mGlobalSharedFolders.find(it->first);
5762 if (git != mGlobalSharedFolders.end())
5763 rc = createSharedFolder(git->first, git->second);
5764 }
5765 }
5766
5767 rc = S_OK;
5768 }
5769 }
5770
5771 return rc;
5772}
5773
5774/**
5775 * Searches for a shared folder with the given name in the list of machine
5776 * shared folders and then in the list of the global shared folders.
5777 *
5778 * @param aName Name of the folder to search for.
5779 * @param aIt Where to store the pointer to the found folder.
5780 * @return @c true if the folder was found and @c false otherwise.
5781 *
5782 * @note The caller must lock this object for reading.
5783 */
5784bool Console::findOtherSharedFolder(IN_BSTR aName,
5785 SharedFolderDataMap::const_iterator &aIt)
5786{
5787 /* sanity check */
5788 AssertReturn(isWriteLockOnCurrentThread(), false);
5789
5790 /* first, search machine folders */
5791 aIt = mMachineSharedFolders.find(aName);
5792 if (aIt != mMachineSharedFolders.end())
5793 return true;
5794
5795 /* second, search machine folders */
5796 aIt = mGlobalSharedFolders.find(aName);
5797 if (aIt != mGlobalSharedFolders.end())
5798 return true;
5799
5800 return false;
5801}
5802
5803/**
5804 * Calls the HGCM service to add a shared folder definition.
5805 *
5806 * @param aName Shared folder name.
5807 * @param aHostPath Shared folder path.
5808 *
5809 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5810 * @note Doesn't lock anything.
5811 */
5812HRESULT Console::createSharedFolder(CBSTR aName, SharedFolderData aData)
5813{
5814 ComAssertRet(aName && *aName, E_FAIL);
5815 ComAssertRet(aData.mHostPath, E_FAIL);
5816
5817 /* sanity checks */
5818 AssertReturn(mpVM, E_FAIL);
5819 AssertReturn(mVMMDev->isShFlActive(), E_FAIL);
5820
5821 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
5822 SHFLSTRING *pFolderName, *pMapName;
5823 size_t cbString;
5824
5825 Log(("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
5826
5827 cbString = (RTUtf16Len(aData.mHostPath) + 1) * sizeof(RTUTF16);
5828 if (cbString >= UINT16_MAX)
5829 return setError(E_INVALIDARG, tr("The name is too long"));
5830 pFolderName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
5831 Assert(pFolderName);
5832 memcpy(pFolderName->String.ucs2, aData.mHostPath, cbString);
5833
5834 pFolderName->u16Size = (uint16_t)cbString;
5835 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5836
5837 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5838 parms[0].u.pointer.addr = pFolderName;
5839 parms[0].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
5840
5841 cbString = (RTUtf16Len(aName) + 1) * sizeof(RTUTF16);
5842 if (cbString >= UINT16_MAX)
5843 {
5844 RTMemFree(pFolderName);
5845 return setError(E_INVALIDARG, tr("The host path is too long"));
5846 }
5847 pMapName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
5848 Assert(pMapName);
5849 memcpy(pMapName->String.ucs2, aName, cbString);
5850
5851 pMapName->u16Size = (uint16_t)cbString;
5852 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5853
5854 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5855 parms[1].u.pointer.addr = pMapName;
5856 parms[1].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
5857
5858 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
5859 parms[2].u.uint32 = aData.mWritable;
5860
5861 int vrc = mVMMDev->hgcmHostCall("VBoxSharedFolders",
5862 SHFL_FN_ADD_MAPPING,
5863 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
5864 RTMemFree(pFolderName);
5865 RTMemFree(pMapName);
5866
5867 if (RT_FAILURE(vrc))
5868 return setError(E_FAIL,
5869 tr("Could not create a shared folder '%ls' mapped to '%ls' (%Rrc)"),
5870 aName, aData.mHostPath.raw(), vrc);
5871
5872 return S_OK;
5873}
5874
5875/**
5876 * Calls the HGCM service to remove the shared folder definition.
5877 *
5878 * @param aName Shared folder name.
5879 *
5880 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5881 * @note Doesn't lock anything.
5882 */
5883HRESULT Console::removeSharedFolder(CBSTR aName)
5884{
5885 ComAssertRet(aName && *aName, E_FAIL);
5886
5887 /* sanity checks */
5888 AssertReturn(mpVM, E_FAIL);
5889 AssertReturn(mVMMDev->isShFlActive(), E_FAIL);
5890
5891 VBOXHGCMSVCPARM parms;
5892 SHFLSTRING *pMapName;
5893 size_t cbString;
5894
5895 Log(("Removing shared folder '%ls'\n", aName));
5896
5897 cbString = (RTUtf16Len(aName) + 1) * sizeof(RTUTF16);
5898 if (cbString >= UINT16_MAX)
5899 return setError(E_INVALIDARG, tr("The name is too long"));
5900 pMapName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
5901 Assert(pMapName);
5902 memcpy(pMapName->String.ucs2, aName, cbString);
5903
5904 pMapName->u16Size = (uint16_t)cbString;
5905 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5906
5907 parms.type = VBOX_HGCM_SVC_PARM_PTR;
5908 parms.u.pointer.addr = pMapName;
5909 parms.u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
5910
5911 int vrc = mVMMDev->hgcmHostCall("VBoxSharedFolders",
5912 SHFL_FN_REMOVE_MAPPING,
5913 1, &parms);
5914 RTMemFree(pMapName);
5915 if (RT_FAILURE(vrc))
5916 return setError(E_FAIL,
5917 tr("Could not remove the shared folder '%ls' (%Rrc)"),
5918 aName, vrc);
5919
5920 return S_OK;
5921}
5922
5923/**
5924 * VM state callback function. Called by the VMM
5925 * using its state machine states.
5926 *
5927 * Primarily used to handle VM initiated power off, suspend and state saving,
5928 * but also for doing termination completed work (VMSTATE_TERMINATE).
5929 *
5930 * In general this function is called in the context of the EMT.
5931 *
5932 * @param aVM The VM handle.
5933 * @param aState The new state.
5934 * @param aOldState The old state.
5935 * @param aUser The user argument (pointer to the Console object).
5936 *
5937 * @note Locks the Console object for writing.
5938 */
5939DECLCALLBACK(void) Console::vmstateChangeCallback(PVM aVM,
5940 VMSTATE aState,
5941 VMSTATE aOldState,
5942 void *aUser)
5943{
5944 LogFlowFunc(("Changing state from %s to %s (aVM=%p)\n",
5945 VMR3GetStateName(aOldState), VMR3GetStateName(aState), aVM));
5946
5947 Console *that = static_cast<Console *>(aUser);
5948 AssertReturnVoid(that);
5949
5950 AutoCaller autoCaller(that);
5951
5952 /* Note that we must let this method proceed even if Console::uninit() has
5953 * been already called. In such case this VMSTATE change is a result of:
5954 * 1) powerDown() called from uninit() itself, or
5955 * 2) VM-(guest-)initiated power off. */
5956 AssertReturnVoid( autoCaller.isOk()
5957 || autoCaller.state() == InUninit);
5958
5959 switch (aState)
5960 {
5961 /*
5962 * The VM has terminated
5963 */
5964 case VMSTATE_OFF:
5965 {
5966 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
5967
5968 if (that->mVMStateChangeCallbackDisabled)
5969 break;
5970
5971 /* Do we still think that it is running? It may happen if this is a
5972 * VM-(guest-)initiated shutdown/poweroff.
5973 */
5974 if ( that->mMachineState != MachineState_Stopping
5975 && that->mMachineState != MachineState_Saving
5976 && that->mMachineState != MachineState_Restoring
5977 && that->mMachineState != MachineState_TeleportingIn
5978 && that->mMachineState != MachineState_TeleportingPausedVM
5979 && !that->mVMIsAlreadyPoweringOff
5980 )
5981 {
5982 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
5983
5984 /* prevent powerDown() from calling VMR3PowerOff() again */
5985 Assert(that->mVMPoweredOff == false);
5986 that->mVMPoweredOff = true;
5987
5988 /* we are stopping now */
5989 that->setMachineState(MachineState_Stopping);
5990
5991 /* Setup task object and thread to carry out the operation
5992 * asynchronously (if we call powerDown() right here but there
5993 * is one or more mpVM callers (added with addVMCaller()) we'll
5994 * deadlock).
5995 */
5996 std::auto_ptr<VMProgressTask> task(new VMProgressTask(that, NULL /* aProgress */,
5997 true /* aUsesVMPtr */));
5998
5999 /* If creating a task is falied, this can currently mean one of
6000 * two: either Console::uninit() has been called just a ms
6001 * before (so a powerDown() call is already on the way), or
6002 * powerDown() itself is being already executed. Just do
6003 * nothing.
6004 */
6005 if (!task->isOk())
6006 {
6007 LogFlowFunc(("Console is already being uninitialized.\n"));
6008 break;
6009 }
6010
6011 int vrc = RTThreadCreate(NULL, Console::powerDownThread,
6012 (void *) task.get(), 0,
6013 RTTHREADTYPE_MAIN_WORKER, 0,
6014 "VMPowerDown");
6015 AssertMsgRCBreak(vrc, ("Could not create VMPowerDown thread (%Rrc)\n", vrc));
6016
6017 /* task is now owned by powerDownThread(), so release it */
6018 task.release();
6019 }
6020 break;
6021 }
6022
6023 /* The VM has been completely destroyed.
6024 *
6025 * Note: This state change can happen at two points:
6026 * 1) At the end of VMR3Destroy() if it was not called from EMT.
6027 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
6028 * called by EMT.
6029 */
6030 case VMSTATE_TERMINATED:
6031 {
6032 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6033
6034 if (that->mVMStateChangeCallbackDisabled)
6035 break;
6036
6037 /* Terminate host interface networking. If aVM is NULL, we've been
6038 * manually called from powerUpThread() either before calling
6039 * VMR3Create() or after VMR3Create() failed, so no need to touch
6040 * networking.
6041 */
6042 if (aVM)
6043 that->powerDownHostInterfaces();
6044
6045 /* From now on the machine is officially powered down or remains in
6046 * the Saved state.
6047 */
6048 switch (that->mMachineState)
6049 {
6050 default:
6051 AssertFailed();
6052 /* fall through */
6053 case MachineState_Stopping:
6054 /* successfully powered down */
6055 that->setMachineState(MachineState_PoweredOff);
6056 break;
6057 case MachineState_Saving:
6058 /* successfully saved (note that the machine is already in
6059 * the Saved state on the server due to EndSavingState()
6060 * called from saveStateThread(), so only change the local
6061 * state) */
6062 that->setMachineStateLocally(MachineState_Saved);
6063 break;
6064 case MachineState_Starting:
6065 /* failed to start, but be patient: set back to PoweredOff
6066 * (for similarity with the below) */
6067 that->setMachineState(MachineState_PoweredOff);
6068 break;
6069 case MachineState_Restoring:
6070 /* failed to load the saved state file, but be patient: set
6071 * back to Saved (to preserve the saved state file) */
6072 that->setMachineState(MachineState_Saved);
6073 break;
6074 case MachineState_TeleportingIn:
6075 /* Teleportation failed or was cancelled. Back to powered off. */
6076 that->setMachineState(MachineState_PoweredOff);
6077 break;
6078 case MachineState_TeleportingPausedVM:
6079 /* Successfully teleported the VM. */
6080 that->setMachineState(MachineState_Teleported);
6081 break;
6082 }
6083 break;
6084 }
6085
6086 case VMSTATE_SUSPENDED:
6087 {
6088 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6089
6090 if (that->mVMStateChangeCallbackDisabled)
6091 break;
6092
6093 switch (that->mMachineState)
6094 {
6095 case MachineState_Teleporting:
6096 that->setMachineState(MachineState_TeleportingPausedVM);
6097 break;
6098
6099 case MachineState_LiveSnapshotting:
6100 that->setMachineState(MachineState_Saving);
6101 break;
6102
6103 case MachineState_TeleportingPausedVM:
6104 case MachineState_Saving:
6105 case MachineState_Restoring:
6106 case MachineState_Stopping:
6107 case MachineState_TeleportingIn:
6108 /* The worker threads handles the transition. */
6109 break;
6110
6111 default:
6112 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
6113 case MachineState_Running:
6114 that->setMachineState(MachineState_Paused);
6115 break;
6116 }
6117 break;
6118 }
6119
6120 case VMSTATE_SUSPENDED_LS:
6121 case VMSTATE_SUSPENDED_EXT_LS:
6122 {
6123 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6124 if (that->mVMStateChangeCallbackDisabled)
6125 break;
6126 switch (that->mMachineState)
6127 {
6128 case MachineState_Teleporting:
6129 that->setMachineState(MachineState_TeleportingPausedVM);
6130 break;
6131
6132 case MachineState_LiveSnapshotting:
6133 that->setMachineState(MachineState_Saving);
6134 break;
6135
6136 case MachineState_TeleportingPausedVM:
6137 case MachineState_Saving:
6138 /* ignore */
6139 break;
6140
6141 default:
6142 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(aOldState), VMR3GetStateName(aState) ));
6143 that->setMachineState(MachineState_Paused);
6144 break;
6145 }
6146 break;
6147 }
6148
6149 case VMSTATE_RUNNING:
6150 {
6151 if ( aOldState == VMSTATE_POWERING_ON
6152 || aOldState == VMSTATE_RESUMING)
6153 {
6154 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6155
6156 if (that->mVMStateChangeCallbackDisabled)
6157 break;
6158
6159 Assert( ( ( that->mMachineState == MachineState_Starting
6160 || that->mMachineState == MachineState_Paused)
6161 && aOldState == VMSTATE_POWERING_ON)
6162 || ( ( that->mMachineState == MachineState_Restoring
6163 || that->mMachineState == MachineState_TeleportingIn
6164 || that->mMachineState == MachineState_Paused
6165 || that->mMachineState == MachineState_Saving
6166 )
6167 && aOldState == VMSTATE_RESUMING));
6168
6169 that->setMachineState(MachineState_Running);
6170 }
6171
6172 break;
6173 }
6174
6175 case VMSTATE_RUNNING_LS:
6176 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
6177 || that->mMachineState == MachineState_Teleporting,
6178 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(aOldState), VMR3GetStateName(aState) ));
6179 break;
6180
6181 case VMSTATE_FATAL_ERROR:
6182 {
6183 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6184
6185 if (that->mVMStateChangeCallbackDisabled)
6186 break;
6187
6188 /* Fatal errors are only for running VMs. */
6189 Assert(Global::IsOnline(that->mMachineState));
6190
6191 /* Note! 'Pause' is used here in want of something better. There
6192 * are currently only two places where fatal errors might be
6193 * raised, so it is not worth adding a new externally
6194 * visible state for this yet. */
6195 that->setMachineState(MachineState_Paused);
6196 break;
6197 }
6198
6199 case VMSTATE_GURU_MEDITATION:
6200 {
6201 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6202
6203 if (that->mVMStateChangeCallbackDisabled)
6204 break;
6205
6206 /* Guru are only for running VMs */
6207 Assert(Global::IsOnline(that->mMachineState));
6208
6209 that->setMachineState(MachineState_Stuck);
6210 break;
6211 }
6212
6213 default: /* shut up gcc */
6214 break;
6215 }
6216}
6217
6218#ifdef VBOX_WITH_USB
6219
6220/**
6221 * Sends a request to VMM to attach the given host device.
6222 * After this method succeeds, the attached device will appear in the
6223 * mUSBDevices collection.
6224 *
6225 * @param aHostDevice device to attach
6226 *
6227 * @note Synchronously calls EMT.
6228 * @note Must be called from under this object's lock.
6229 */
6230HRESULT Console::attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs)
6231{
6232 AssertReturn(aHostDevice, E_FAIL);
6233 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6234
6235 /* still want a lock object because we need to leave it */
6236 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6237
6238 HRESULT hrc;
6239
6240 /*
6241 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
6242 * method in EMT (using usbAttachCallback()).
6243 */
6244 Bstr BstrAddress;
6245 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
6246 ComAssertComRCRetRC(hrc);
6247
6248 Utf8Str Address(BstrAddress);
6249
6250 Bstr id;
6251 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
6252 ComAssertComRCRetRC(hrc);
6253 Guid uuid(id);
6254
6255 BOOL fRemote = FALSE;
6256 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
6257 ComAssertComRCRetRC(hrc);
6258
6259 /* protect mpVM */
6260 AutoVMCaller autoVMCaller(this);
6261 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
6262
6263 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
6264 Address.raw(), uuid.ptr()));
6265
6266 /* leave the lock before a VMR3* call (EMT will call us back)! */
6267 alock.leave();
6268
6269/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
6270 int vrc = VMR3ReqCallWait(mpVM, VMCPUID_ANY,
6271 (PFNRT) usbAttachCallback, 6, this, aHostDevice, uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
6272
6273 /* restore the lock */
6274 alock.enter();
6275
6276 /* hrc is S_OK here */
6277
6278 if (RT_FAILURE(vrc))
6279 {
6280 LogWarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
6281 Address.raw(), uuid.ptr(), vrc));
6282
6283 switch (vrc)
6284 {
6285 case VERR_VUSB_NO_PORTS:
6286 hrc = setError(E_FAIL,
6287 tr("Failed to attach the USB device. (No available ports on the USB controller)."));
6288 break;
6289 case VERR_VUSB_USBFS_PERMISSION:
6290 hrc = setError(E_FAIL,
6291 tr("Not permitted to open the USB device, check usbfs options"));
6292 break;
6293 default:
6294 hrc = setError(E_FAIL,
6295 tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"),
6296 vrc);
6297 break;
6298 }
6299 }
6300
6301 return hrc;
6302}
6303
6304/**
6305 * USB device attach callback used by AttachUSBDevice().
6306 * Note that AttachUSBDevice() doesn't return until this callback is executed,
6307 * so we don't use AutoCaller and don't care about reference counters of
6308 * interface pointers passed in.
6309 *
6310 * @thread EMT
6311 * @note Locks the console object for writing.
6312 */
6313//static
6314DECLCALLBACK(int)
6315Console::usbAttachCallback(Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
6316{
6317 LogFlowFuncEnter();
6318 LogFlowFunc(("that={%p}\n", that));
6319
6320 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
6321
6322 void *pvRemoteBackend = NULL;
6323 if (aRemote)
6324 {
6325 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
6326 Guid guid(*aUuid);
6327
6328 pvRemoteBackend = that->consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &guid);
6329 if (!pvRemoteBackend)
6330 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
6331 }
6332
6333 USHORT portVersion = 1;
6334 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
6335 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
6336 Assert(portVersion == 1 || portVersion == 2);
6337
6338 int vrc = PDMR3USBCreateProxyDevice(that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
6339 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
6340 if (RT_SUCCESS(vrc))
6341 {
6342 /* Create a OUSBDevice and add it to the device list */
6343 ComObjPtr<OUSBDevice> device;
6344 device.createObject();
6345 hrc = device->init(aHostDevice);
6346 AssertComRC(hrc);
6347
6348 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6349 that->mUSBDevices.push_back(device);
6350 LogFlowFunc(("Attached device {%RTuuid}\n", device->id().raw()));
6351
6352 /* notify callbacks */
6353 that->onUSBDeviceStateChange(device, true /* aAttached */, NULL);
6354 }
6355
6356 LogFlowFunc(("vrc=%Rrc\n", vrc));
6357 LogFlowFuncLeave();
6358 return vrc;
6359}
6360
6361/**
6362 * Sends a request to VMM to detach the given host device. After this method
6363 * succeeds, the detached device will disappear from the mUSBDevices
6364 * collection.
6365 *
6366 * @param aIt Iterator pointing to the device to detach.
6367 *
6368 * @note Synchronously calls EMT.
6369 * @note Must be called from under this object's lock.
6370 */
6371HRESULT Console::detachUSBDevice(USBDeviceList::iterator &aIt)
6372{
6373 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6374
6375 /* still want a lock object because we need to leave it */
6376 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6377
6378 /* protect mpVM */
6379 AutoVMCaller autoVMCaller(this);
6380 if (FAILED(autoVMCaller.rc())) return autoVMCaller.rc();
6381
6382 /* if the device is attached, then there must at least one USB hub. */
6383 AssertReturn(PDMR3USBHasHub(mpVM), E_FAIL);
6384
6385 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
6386 (*aIt)->id().raw()));
6387
6388 /* leave the lock before a VMR3* call (EMT will call us back)! */
6389 alock.leave();
6390
6391/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
6392 int vrc = VMR3ReqCallWait(mpVM, VMCPUID_ANY,
6393 (PFNRT) usbDetachCallback, 4, this, &aIt, (*aIt)->id().raw());
6394 ComAssertRCRet(vrc, E_FAIL);
6395
6396 return S_OK;
6397}
6398
6399/**
6400 * USB device detach callback used by DetachUSBDevice().
6401 * Note that DetachUSBDevice() doesn't return until this callback is executed,
6402 * so we don't use AutoCaller and don't care about reference counters of
6403 * interface pointers passed in.
6404 *
6405 * @thread EMT
6406 * @note Locks the console object for writing.
6407 */
6408//static
6409DECLCALLBACK(int)
6410Console::usbDetachCallback(Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
6411{
6412 LogFlowFuncEnter();
6413 LogFlowFunc(("that={%p}\n", that));
6414
6415 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
6416 ComObjPtr<OUSBDevice> device = **aIt;
6417
6418 /*
6419 * If that was a remote device, release the backend pointer.
6420 * The pointer was requested in usbAttachCallback.
6421 */
6422 BOOL fRemote = FALSE;
6423
6424 HRESULT hrc2 = (**aIt)->COMGETTER(Remote)(&fRemote);
6425 ComAssertComRC(hrc2);
6426
6427 if (fRemote)
6428 {
6429 Guid guid(*aUuid);
6430 that->consoleVRDPServer()->USBBackendReleasePointer(&guid);
6431 }
6432
6433 int vrc = PDMR3USBDetachDevice(that->mpVM, aUuid);
6434
6435 if (RT_SUCCESS(vrc))
6436 {
6437 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
6438
6439 /* Remove the device from the collection */
6440 that->mUSBDevices.erase(*aIt);
6441 LogFlowFunc(("Detached device {%RTuuid}\n", device->id().raw()));
6442
6443 /* notify callbacks */
6444 that->onUSBDeviceStateChange(device, false /* aAttached */, NULL);
6445 }
6446
6447 LogFlowFunc(("vrc=%Rrc\n", vrc));
6448 LogFlowFuncLeave();
6449 return vrc;
6450}
6451
6452#endif /* VBOX_WITH_USB */
6453#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
6454
6455/**
6456 * Helper function to handle host interface device creation and attachment.
6457 *
6458 * @param networkAdapter the network adapter which attachment should be reset
6459 * @return COM status code
6460 *
6461 * @note The caller must lock this object for writing.
6462 *
6463 * @todo Move this back into the driver!
6464 */
6465HRESULT Console::attachToTapInterface(INetworkAdapter *networkAdapter)
6466{
6467 LogFlowThisFunc(("\n"));
6468 /* sanity check */
6469 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6470
6471# ifdef VBOX_STRICT
6472 /* paranoia */
6473 NetworkAttachmentType_T attachment;
6474 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6475 Assert(attachment == NetworkAttachmentType_Bridged);
6476# endif /* VBOX_STRICT */
6477
6478 HRESULT rc = S_OK;
6479
6480 ULONG slot = 0;
6481 rc = networkAdapter->COMGETTER(Slot)(&slot);
6482 AssertComRC(rc);
6483
6484# ifdef RT_OS_LINUX
6485 /*
6486 * Allocate a host interface device
6487 */
6488 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
6489 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
6490 if (RT_SUCCESS(rcVBox))
6491 {
6492 /*
6493 * Set/obtain the tap interface.
6494 */
6495 struct ifreq IfReq;
6496 memset(&IfReq, 0, sizeof(IfReq));
6497 /* The name of the TAP interface we are using */
6498 Bstr tapDeviceName;
6499 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6500 if (FAILED(rc))
6501 tapDeviceName.setNull(); /* Is this necessary? */
6502 if (tapDeviceName.isEmpty())
6503 {
6504 LogRel(("No TAP device name was supplied.\n"));
6505 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
6506 }
6507
6508 if (SUCCEEDED(rc))
6509 {
6510 /* If we are using a static TAP device then try to open it. */
6511 Utf8Str str(tapDeviceName);
6512 if (str.length() <= sizeof(IfReq.ifr_name))
6513 strcpy(IfReq.ifr_name, str.raw());
6514 else
6515 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
6516 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
6517 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
6518 if (rcVBox != 0)
6519 {
6520 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
6521 rc = setError(E_FAIL,
6522 tr("Failed to open the host network interface %ls"),
6523 tapDeviceName.raw());
6524 }
6525 }
6526 if (SUCCEEDED(rc))
6527 {
6528 /*
6529 * Make it pollable.
6530 */
6531 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
6532 {
6533 Log(("attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
6534 /*
6535 * Here is the right place to communicate the TAP file descriptor and
6536 * the host interface name to the server if/when it becomes really
6537 * necessary.
6538 */
6539 maTAPDeviceName[slot] = tapDeviceName;
6540 rcVBox = VINF_SUCCESS;
6541 }
6542 else
6543 {
6544 int iErr = errno;
6545
6546 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
6547 rcVBox = VERR_HOSTIF_BLOCKING;
6548 rc = setError(E_FAIL,
6549 tr("could not set up the host networking device for non blocking access: %s"),
6550 strerror(errno));
6551 }
6552 }
6553 }
6554 else
6555 {
6556 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
6557 switch (rcVBox)
6558 {
6559 case VERR_ACCESS_DENIED:
6560 /* will be handled by our caller */
6561 rc = rcVBox;
6562 break;
6563 default:
6564 rc = setError(E_FAIL,
6565 tr("Could not set up the host networking device: %Rrc"),
6566 rcVBox);
6567 break;
6568 }
6569 }
6570
6571# elif defined(RT_OS_FREEBSD)
6572 /*
6573 * Set/obtain the tap interface.
6574 */
6575 /* The name of the TAP interface we are using */
6576 Bstr tapDeviceName;
6577 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6578 if (FAILED(rc))
6579 tapDeviceName.setNull(); /* Is this necessary? */
6580 if (tapDeviceName.isEmpty())
6581 {
6582 LogRel(("No TAP device name was supplied.\n"));
6583 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
6584 }
6585 char szTapdev[1024] = "/dev/";
6586 /* If we are using a static TAP device then try to open it. */
6587 Utf8Str str(tapDeviceName);
6588 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
6589 strcat(szTapdev, str.raw());
6590 else
6591 memcpy(szTapdev + strlen(szTapdev), str.raw(), sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
6592 int rcVBox = RTFileOpen(&maTapFD[slot], szTapdev,
6593 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
6594
6595 if (RT_SUCCESS(rcVBox))
6596 maTAPDeviceName[slot] = tapDeviceName;
6597 else
6598 {
6599 switch (rcVBox)
6600 {
6601 case VERR_ACCESS_DENIED:
6602 /* will be handled by our caller */
6603 rc = rcVBox;
6604 break;
6605 default:
6606 rc = setError(E_FAIL,
6607 tr("Failed to open the host network interface %ls"),
6608 tapDeviceName.raw());
6609 break;
6610 }
6611 }
6612# else
6613# error "huh?"
6614# endif
6615 /* in case of failure, cleanup. */
6616 if (RT_FAILURE(rcVBox) && SUCCEEDED(rc))
6617 {
6618 LogRel(("General failure attaching to host interface\n"));
6619 rc = setError(E_FAIL,
6620 tr("General failure attaching to host interface"));
6621 }
6622 LogFlowThisFunc(("rc=%d\n", rc));
6623 return rc;
6624}
6625
6626
6627/**
6628 * Helper function to handle detachment from a host interface
6629 *
6630 * @param networkAdapter the network adapter which attachment should be reset
6631 * @return COM status code
6632 *
6633 * @note The caller must lock this object for writing.
6634 *
6635 * @todo Move this back into the driver!
6636 */
6637HRESULT Console::detachFromTapInterface(INetworkAdapter *networkAdapter)
6638{
6639 /* sanity check */
6640 LogFlowThisFunc(("\n"));
6641 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6642
6643 HRESULT rc = S_OK;
6644# ifdef VBOX_STRICT
6645 /* paranoia */
6646 NetworkAttachmentType_T attachment;
6647 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6648 Assert(attachment == NetworkAttachmentType_Bridged);
6649# endif /* VBOX_STRICT */
6650
6651 ULONG slot = 0;
6652 rc = networkAdapter->COMGETTER(Slot)(&slot);
6653 AssertComRC(rc);
6654
6655 /* is there an open TAP device? */
6656 if (maTapFD[slot] != NIL_RTFILE)
6657 {
6658 /*
6659 * Close the file handle.
6660 */
6661 Bstr tapDeviceName, tapTerminateApplication;
6662 bool isStatic = true;
6663 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6664 if (FAILED(rc) || tapDeviceName.isEmpty())
6665 {
6666 /* If the name is empty, this is a dynamic TAP device, so close it now,
6667 so that the termination script can remove the interface. Otherwise we still
6668 need the FD to pass to the termination script. */
6669 isStatic = false;
6670 int rcVBox = RTFileClose(maTapFD[slot]);
6671 AssertRC(rcVBox);
6672 maTapFD[slot] = NIL_RTFILE;
6673 }
6674 if (isStatic)
6675 {
6676 /* If we are using a static TAP device, we close it now, after having called the
6677 termination script. */
6678 int rcVBox = RTFileClose(maTapFD[slot]);
6679 AssertRC(rcVBox);
6680 }
6681 /* the TAP device name and handle are no longer valid */
6682 maTapFD[slot] = NIL_RTFILE;
6683 maTAPDeviceName[slot] = "";
6684 }
6685 LogFlowThisFunc(("returning %d\n", rc));
6686 return rc;
6687}
6688
6689#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
6690
6691/**
6692 * Called at power down to terminate host interface networking.
6693 *
6694 * @note The caller must lock this object for writing.
6695 */
6696HRESULT Console::powerDownHostInterfaces()
6697{
6698 LogFlowThisFunc(("\n"));
6699
6700 /* sanity check */
6701 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6702
6703 /*
6704 * host interface termination handling
6705 */
6706 HRESULT rc;
6707 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
6708 {
6709 ComPtr<INetworkAdapter> networkAdapter;
6710 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
6711 if (FAILED(rc)) break;
6712
6713 BOOL enabled = FALSE;
6714 networkAdapter->COMGETTER(Enabled)(&enabled);
6715 if (!enabled)
6716 continue;
6717
6718 NetworkAttachmentType_T attachment;
6719 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6720 if (attachment == NetworkAttachmentType_Bridged)
6721 {
6722#if defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)
6723 HRESULT rc2 = detachFromTapInterface(networkAdapter);
6724 if (FAILED(rc2) && SUCCEEDED(rc))
6725 rc = rc2;
6726#endif
6727 }
6728 }
6729
6730 return rc;
6731}
6732
6733
6734/**
6735 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
6736 * and VMR3Teleport.
6737 *
6738 * @param pVM The VM handle.
6739 * @param uPercent Completetion precentage (0-100).
6740 * @param pvUser Pointer to the VMProgressTask structure.
6741 * @return VINF_SUCCESS.
6742 */
6743/*static*/
6744DECLCALLBACK(int) Console::stateProgressCallback(PVM pVM, unsigned uPercent, void *pvUser)
6745{
6746 VMProgressTask *task = static_cast<VMProgressTask *>(pvUser);
6747 AssertReturn(task, VERR_INVALID_PARAMETER);
6748
6749 /* update the progress object */
6750 if (task->mProgress)
6751 task->mProgress->SetCurrentOperationProgress(uPercent);
6752
6753 return VINF_SUCCESS;
6754}
6755
6756/**
6757 * VM error callback function. Called by the various VM components.
6758 *
6759 * @param pVM VM handle. Can be NULL if an error occurred before
6760 * successfully creating a VM.
6761 * @param pvUser Pointer to the VMProgressTask structure.
6762 * @param rc VBox status code.
6763 * @param pszFormat Printf-like error message.
6764 * @param args Various number of arguments for the error message.
6765 *
6766 * @thread EMT, VMPowerUp...
6767 *
6768 * @note The VMProgressTask structure modified by this callback is not thread
6769 * safe.
6770 */
6771/* static */ DECLCALLBACK(void)
6772Console::setVMErrorCallback(PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
6773 const char *pszFormat, va_list args)
6774{
6775 VMProgressTask *task = static_cast<VMProgressTask *>(pvUser);
6776 AssertReturnVoid(task);
6777
6778 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
6779 va_list va2;
6780 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
6781
6782 /* append to the existing error message if any */
6783 if (task->mErrorMsg.length())
6784 task->mErrorMsg = Utf8StrFmt("%s.\n%N (%Rrc)", task->mErrorMsg.raw(),
6785 pszFormat, &va2, rc, rc);
6786 else
6787 task->mErrorMsg = Utf8StrFmt("%N (%Rrc)",
6788 pszFormat, &va2, rc, rc);
6789
6790 va_end (va2);
6791}
6792
6793/**
6794 * VM runtime error callback function.
6795 * See VMSetRuntimeError for the detailed description of parameters.
6796 *
6797 * @param pVM The VM handle.
6798 * @param pvUser The user argument.
6799 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
6800 * @param pszErrorId Error ID string.
6801 * @param pszFormat Error message format string.
6802 * @param va Error message arguments.
6803 * @thread EMT.
6804 */
6805/* static */ DECLCALLBACK(void)
6806Console::setVMRuntimeErrorCallback(PVM pVM, void *pvUser, uint32_t fFlags,
6807 const char *pszErrorId,
6808 const char *pszFormat, va_list va)
6809{
6810 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
6811 LogFlowFuncEnter();
6812
6813 Console *that = static_cast<Console *>(pvUser);
6814 AssertReturnVoid(that);
6815
6816 Utf8Str message = Utf8StrFmtVA(pszFormat, va);
6817
6818 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
6819 fFatal, pszErrorId, message.raw()));
6820
6821 that->onRuntimeError(BOOL(fFatal), Bstr(pszErrorId), Bstr(message));
6822
6823 LogFlowFuncLeave();
6824}
6825
6826/**
6827 * Captures USB devices that match filters of the VM.
6828 * Called at VM startup.
6829 *
6830 * @param pVM The VM handle.
6831 *
6832 * @note The caller must lock this object for writing.
6833 */
6834HRESULT Console::captureUSBDevices(PVM pVM)
6835{
6836 LogFlowThisFunc(("\n"));
6837
6838 /* sanity check */
6839 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
6840
6841 /* If the machine has an USB controller, ask the USB proxy service to
6842 * capture devices */
6843 PPDMIBASE pBase;
6844 int vrc = PDMR3QueryLun(pVM, "usb-ohci", 0, 0, &pBase);
6845 if (RT_SUCCESS(vrc))
6846 {
6847 /* leave the lock before calling Host in VBoxSVC since Host may call
6848 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6849 * produce an inter-process dead-lock otherwise. */
6850 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6851 alock.leave();
6852
6853 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6854 ComAssertComRCRetRC(hrc);
6855 }
6856 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6857 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6858 vrc = VINF_SUCCESS;
6859 else
6860 AssertRC(vrc);
6861
6862 return RT_SUCCESS(vrc) ? S_OK : E_FAIL;
6863}
6864
6865
6866/**
6867 * Detach all USB device which are attached to the VM for the
6868 * purpose of clean up and such like.
6869 *
6870 * @note The caller must lock this object for writing.
6871 */
6872void Console::detachAllUSBDevices(bool aDone)
6873{
6874 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
6875
6876 /* sanity check */
6877 AssertReturnVoid(isWriteLockOnCurrentThread());
6878
6879 mUSBDevices.clear();
6880
6881 /* leave the lock before calling Host in VBoxSVC since Host may call
6882 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6883 * produce an inter-process dead-lock otherwise. */
6884 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6885 alock.leave();
6886
6887 mControl->DetachAllUSBDevices(aDone);
6888}
6889
6890/**
6891 * @note Locks this object for writing.
6892 */
6893void Console::processRemoteUSBDevices(uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6894{
6895 LogFlowThisFuncEnter();
6896 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6897
6898 AutoCaller autoCaller(this);
6899 if (!autoCaller.isOk())
6900 {
6901 /* Console has been already uninitialized, deny request */
6902 AssertMsgFailed(("Console is already uninitialized\n"));
6903 LogFlowThisFunc(("Console is already uninitialized\n"));
6904 LogFlowThisFuncLeave();
6905 return;
6906 }
6907
6908 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6909
6910 /*
6911 * Mark all existing remote USB devices as dirty.
6912 */
6913 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6914 it != mRemoteUSBDevices.end();
6915 ++it)
6916 {
6917 (*it)->dirty(true);
6918 }
6919
6920 /*
6921 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6922 */
6923 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6924 VRDPUSBDEVICEDESC *e = pDevList;
6925
6926 /* The cbDevList condition must be checked first, because the function can
6927 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6928 */
6929 while (cbDevList >= 2 && e->oNext)
6930 {
6931 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
6932 e->idVendor, e->idProduct,
6933 e->oProduct? (char *)e + e->oProduct: ""));
6934
6935 bool fNewDevice = true;
6936
6937 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6938 it != mRemoteUSBDevices.end();
6939 ++it)
6940 {
6941 if ((*it)->devId() == e->id
6942 && (*it)->clientId() == u32ClientId)
6943 {
6944 /* The device is already in the list. */
6945 (*it)->dirty(false);
6946 fNewDevice = false;
6947 break;
6948 }
6949 }
6950
6951 if (fNewDevice)
6952 {
6953 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6954 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
6955
6956 /* Create the device object and add the new device to list. */
6957 ComObjPtr<RemoteUSBDevice> device;
6958 device.createObject();
6959 device->init(u32ClientId, e);
6960
6961 mRemoteUSBDevices.push_back(device);
6962
6963 /* Check if the device is ok for current USB filters. */
6964 BOOL fMatched = FALSE;
6965 ULONG fMaskedIfs = 0;
6966
6967 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
6968
6969 AssertComRC(hrc);
6970
6971 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
6972
6973 if (fMatched)
6974 {
6975 hrc = onUSBDeviceAttach(device, NULL, fMaskedIfs);
6976
6977 /// @todo (r=dmik) warning reporting subsystem
6978
6979 if (hrc == S_OK)
6980 {
6981 LogFlowThisFunc(("Device attached\n"));
6982 device->captured(true);
6983 }
6984 }
6985 }
6986
6987 if (cbDevList < e->oNext)
6988 {
6989 LogWarningThisFunc(("cbDevList %d > oNext %d\n",
6990 cbDevList, e->oNext));
6991 break;
6992 }
6993
6994 cbDevList -= e->oNext;
6995
6996 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6997 }
6998
6999 /*
7000 * Remove dirty devices, that is those which are not reported by the server anymore.
7001 */
7002 for (;;)
7003 {
7004 ComObjPtr<RemoteUSBDevice> device;
7005
7006 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
7007 while (it != mRemoteUSBDevices.end())
7008 {
7009 if ((*it)->dirty())
7010 {
7011 device = *it;
7012 break;
7013 }
7014
7015 ++ it;
7016 }
7017
7018 if (!device)
7019 {
7020 break;
7021 }
7022
7023 USHORT vendorId = 0;
7024 device->COMGETTER(VendorId)(&vendorId);
7025
7026 USHORT productId = 0;
7027 device->COMGETTER(ProductId)(&productId);
7028
7029 Bstr product;
7030 device->COMGETTER(Product)(product.asOutParam());
7031
7032 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
7033 vendorId, productId, product.raw()));
7034
7035 /* Detach the device from VM. */
7036 if (device->captured())
7037 {
7038 Bstr uuid;
7039 device->COMGETTER(Id)(uuid.asOutParam());
7040 onUSBDeviceDetach(uuid, NULL);
7041 }
7042
7043 /* And remove it from the list. */
7044 mRemoteUSBDevices.erase(it);
7045 }
7046
7047 LogFlowThisFuncLeave();
7048}
7049
7050/**
7051 * Thread function which starts the VM (also from saved state) and
7052 * track progress.
7053 *
7054 * @param Thread The thread id.
7055 * @param pvUser Pointer to a VMPowerUpTask structure.
7056 * @return VINF_SUCCESS (ignored).
7057 *
7058 * @note Locks the Console object for writing.
7059 */
7060/*static*/
7061DECLCALLBACK(int) Console::powerUpThread(RTTHREAD Thread, void *pvUser)
7062{
7063 LogFlowFuncEnter();
7064
7065 std::auto_ptr<VMPowerUpTask> task(static_cast<VMPowerUpTask *>(pvUser));
7066 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
7067
7068 AssertReturn(!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
7069 AssertReturn(!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
7070
7071#if defined(RT_OS_WINDOWS)
7072 {
7073 /* initialize COM */
7074 HRESULT hrc = CoInitializeEx(NULL,
7075 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
7076 COINIT_SPEED_OVER_MEMORY);
7077 LogFlowFunc(("CoInitializeEx()=%08X\n", hrc));
7078 }
7079#endif
7080
7081 HRESULT rc = S_OK;
7082 int vrc = VINF_SUCCESS;
7083
7084 /* Set up a build identifier so that it can be seen from core dumps what
7085 * exact build was used to produce the core. */
7086 static char saBuildID[40];
7087 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
7088 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, RTBldCfgRevision(), "BU", "IL", "DI", "D");
7089
7090 ComObjPtr<Console> console = task->mConsole;
7091
7092 /* Note: no need to use addCaller() because VMPowerUpTask does that */
7093
7094 /* The lock is also used as a signal from the task initiator (which
7095 * releases it only after RTThreadCreate()) that we can start the job */
7096 AutoWriteLock alock(console COMMA_LOCKVAL_SRC_POS);
7097
7098 /* sanity */
7099 Assert(console->mpVM == NULL);
7100
7101 try
7102 {
7103 /* wait for auto reset ops to complete so that we can successfully lock
7104 * the attached hard disks by calling LockMedia() below */
7105 for (VMPowerUpTask::ProgressList::const_iterator
7106 it = task->hardDiskProgresses.begin();
7107 it != task->hardDiskProgresses.end(); ++ it)
7108 {
7109 HRESULT rc2 = (*it)->WaitForCompletion(-1);
7110 AssertComRC(rc2);
7111 }
7112
7113 /*
7114 * Lock attached media. This method will also check their accessibility.
7115 * If we're a teleporter, we'll have to postpone this action so we can
7116 * migrate between local processes.
7117 *
7118 * Note! The media will be unlocked automatically by
7119 * SessionMachine::setMachineState() when the VM is powered down.
7120 */
7121 if (!task->mTeleporterEnabled)
7122 {
7123 rc = console->mControl->LockMedia();
7124 if (FAILED(rc)) throw rc;
7125 }
7126
7127#ifdef VBOX_WITH_VRDP
7128
7129 /* Create the VRDP server. In case of headless operation, this will
7130 * also create the framebuffer, required at VM creation.
7131 */
7132 ConsoleVRDPServer *server = console->consoleVRDPServer();
7133 Assert(server);
7134
7135 /* Does VRDP server call Console from the other thread?
7136 * Not sure (and can change), so leave the lock just in case.
7137 */
7138 alock.leave();
7139 vrc = server->Launch();
7140 alock.enter();
7141
7142 if (vrc == VERR_NET_ADDRESS_IN_USE)
7143 {
7144 Utf8Str errMsg;
7145 Bstr bstr;
7146 console->mVRDPServer->COMGETTER(Ports)(bstr.asOutParam());
7147 Utf8Str ports = bstr;
7148 errMsg = Utf8StrFmt(tr("VRDP server can't bind to a port: %s"),
7149 ports.raw());
7150 LogRel(("Warning: failed to launch VRDP server (%Rrc): '%s'\n",
7151 vrc, errMsg.raw()));
7152 }
7153 else if (RT_FAILURE(vrc))
7154 {
7155 Utf8Str errMsg;
7156 switch (vrc)
7157 {
7158 case VERR_FILE_NOT_FOUND:
7159 {
7160 errMsg = Utf8StrFmt(tr("Could not load the VRDP library"));
7161 break;
7162 }
7163 default:
7164 errMsg = Utf8StrFmt(tr("Failed to launch VRDP server (%Rrc)"),
7165 vrc);
7166 }
7167 LogRel(("Failed to launch VRDP server (%Rrc), error message: '%s'\n",
7168 vrc, errMsg.raw()));
7169 throw setError(E_FAIL, errMsg.c_str());
7170 }
7171
7172#endif /* VBOX_WITH_VRDP */
7173
7174 ComPtr<IMachine> pMachine = console->machine();
7175 ULONG cCpus = 1;
7176 pMachine->COMGETTER(CPUCount)(&cCpus);
7177
7178 /*
7179 * Create the VM
7180 */
7181 PVM pVM;
7182 /*
7183 * leave the lock since EMT will call Console. It's safe because
7184 * mMachineState is either Starting or Restoring state here.
7185 */
7186 alock.leave();
7187
7188 vrc = VMR3Create(cCpus, task->mSetVMErrorCallback, task.get(),
7189 task->mConfigConstructor, static_cast<Console *>(console),
7190 &pVM);
7191
7192 alock.enter();
7193
7194#ifdef VBOX_WITH_VRDP
7195 /* Enable client connections to the server. */
7196 console->consoleVRDPServer()->EnableConnections();
7197#endif /* VBOX_WITH_VRDP */
7198
7199 if (RT_SUCCESS(vrc))
7200 {
7201 do
7202 {
7203 /*
7204 * Register our load/save state file handlers
7205 */
7206 vrc = SSMR3RegisterExternal(pVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
7207 NULL, NULL, NULL,
7208 NULL, saveStateFileExec, NULL,
7209 NULL, loadStateFileExec, NULL,
7210 static_cast<Console *>(console));
7211 AssertRCBreak(vrc);
7212
7213 vrc = static_cast<Console *>(console)->getDisplay()->registerSSM(pVM);
7214 AssertRC(vrc);
7215 if (RT_FAILURE(vrc))
7216 break;
7217
7218 /*
7219 * Synchronize debugger settings
7220 */
7221 MachineDebugger *machineDebugger = console->getMachineDebugger();
7222 if (machineDebugger)
7223 {
7224 machineDebugger->flushQueuedSettings();
7225 }
7226
7227 /*
7228 * Shared Folders
7229 */
7230 if (console->getVMMDev()->isShFlActive())
7231 {
7232 /* Does the code below call Console from the other thread?
7233 * Not sure, so leave the lock just in case. */
7234 alock.leave();
7235
7236 for (SharedFolderDataMap::const_iterator
7237 it = task->mSharedFolders.begin();
7238 it != task->mSharedFolders.end();
7239 ++ it)
7240 {
7241 rc = console->createSharedFolder((*it).first, (*it).second);
7242 if (FAILED(rc)) break;
7243 }
7244 if (FAILED(rc)) break;
7245
7246 /* enter the lock again */
7247 alock.enter();
7248 }
7249
7250 /*
7251 * Capture USB devices.
7252 */
7253 rc = console->captureUSBDevices(pVM);
7254 if (FAILED(rc)) break;
7255
7256 /* leave the lock before a lengthy operation */
7257 alock.leave();
7258
7259 /* Load saved state? */
7260 if (task->mSavedStateFile.length())
7261 {
7262 LogFlowFunc(("Restoring saved state from '%s'...\n",
7263 task->mSavedStateFile.raw()));
7264
7265 vrc = VMR3LoadFromFile(pVM,
7266 task->mSavedStateFile.c_str(),
7267 Console::stateProgressCallback,
7268 static_cast<VMProgressTask*>(task.get()));
7269
7270 if (RT_SUCCESS(vrc))
7271 {
7272 if (task->mStartPaused)
7273 /* done */
7274 console->setMachineState(MachineState_Paused);
7275 else
7276 {
7277 /* Start/Resume the VM execution */
7278 vrc = VMR3Resume(pVM);
7279 AssertRC(vrc);
7280 }
7281 }
7282
7283 /* Power off in case we failed loading or resuming the VM */
7284 if (RT_FAILURE(vrc))
7285 {
7286 int vrc2 = VMR3PowerOff(pVM);
7287 AssertRC(vrc2);
7288 }
7289 }
7290 else if (task->mTeleporterEnabled)
7291 {
7292 /* -> ConsoleImplTeleporter.cpp */
7293 vrc = console->teleporterTrg(pVM, pMachine, task->mStartPaused, task->mProgress);
7294 if (RT_FAILURE(vrc) && !task->mErrorMsg.length())
7295 rc = E_FAIL; /* Avoid the "Missing error message..." assertion. */
7296 }
7297 else if (task->mStartPaused)
7298 /* done */
7299 console->setMachineState(MachineState_Paused);
7300 else
7301 {
7302 /* Power on the VM (i.e. start executing) */
7303 vrc = VMR3PowerOn(pVM);
7304 AssertRC(vrc);
7305 }
7306
7307 /* enter the lock again */
7308 alock.enter();
7309 }
7310 while (0);
7311
7312 /* On failure, destroy the VM */
7313 if (FAILED(rc) || RT_FAILURE(vrc))
7314 {
7315 /* preserve existing error info */
7316 ErrorInfoKeeper eik;
7317
7318 /* powerDown() will call VMR3Destroy() and do all necessary
7319 * cleanup (VRDP, USB devices) */
7320 HRESULT rc2 = console->powerDown();
7321 AssertComRC(rc2);
7322 }
7323 else
7324 {
7325 /*
7326 * Deregister the VMSetError callback. This is necessary as the
7327 * pfnVMAtError() function passed to VMR3Create() is supposed to
7328 * be sticky but our error callback isn't.
7329 */
7330 alock.leave();
7331 VMR3AtErrorDeregister(pVM, task->mSetVMErrorCallback, task.get());
7332 /** @todo register another VMSetError callback? */
7333 alock.enter();
7334 }
7335 }
7336 else
7337 {
7338 /*
7339 * If VMR3Create() failed it has released the VM memory.
7340 */
7341 console->mpVM = NULL;
7342 }
7343
7344 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
7345 {
7346 /* If VMR3Create() or one of the other calls in this function fail,
7347 * an appropriate error message has been set in task->mErrorMsg.
7348 * However since that happens via a callback, the rc status code in
7349 * this function is not updated.
7350 */
7351 if (!task->mErrorMsg.length())
7352 {
7353 /* If the error message is not set but we've got a failure,
7354 * convert the VBox status code into a meaningful error message.
7355 * This becomes unused once all the sources of errors set the
7356 * appropriate error message themselves.
7357 */
7358 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
7359 task->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"),
7360 vrc);
7361 }
7362
7363 /* Set the error message as the COM error.
7364 * Progress::notifyComplete() will pick it up later. */
7365 throw setError(E_FAIL, task->mErrorMsg.c_str());
7366 }
7367 }
7368 catch (HRESULT aRC) { rc = aRC; }
7369
7370 if ( console->mMachineState == MachineState_Starting
7371 || console->mMachineState == MachineState_Restoring
7372 || console->mMachineState == MachineState_TeleportingIn
7373 )
7374 {
7375 /* We are still in the Starting/Restoring state. This means one of:
7376 *
7377 * 1) we failed before VMR3Create() was called;
7378 * 2) VMR3Create() failed.
7379 *
7380 * In both cases, there is no need to call powerDown(), but we still
7381 * need to go back to the PoweredOff/Saved state. Reuse
7382 * vmstateChangeCallback() for that purpose.
7383 */
7384
7385 /* preserve existing error info */
7386 ErrorInfoKeeper eik;
7387
7388 Assert(console->mpVM == NULL);
7389 vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
7390 console);
7391 }
7392
7393 /*
7394 * Evaluate the final result. Note that the appropriate mMachineState value
7395 * is already set by vmstateChangeCallback() in all cases.
7396 */
7397
7398 /* leave the lock, don't need it any more */
7399 alock.leave();
7400
7401 if (SUCCEEDED(rc))
7402 {
7403 /* Notify the progress object of the success */
7404 task->mProgress->notifyComplete(S_OK);
7405 console->mControl->SetPowerUpInfo(NULL);
7406 }
7407 else
7408 {
7409 /* The progress object will fetch the current error info */
7410 task->mProgress->notifyComplete(rc);
7411 ProgressErrorInfo info(task->mProgress);
7412 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
7413 rc = errorInfo.createObject();
7414 if (SUCCEEDED(rc))
7415 {
7416 errorInfo->init(info.getResultCode(),
7417 info.getInterfaceID(),
7418 info.getComponent(),
7419 info.getText());
7420 console->mControl->SetPowerUpInfo(errorInfo);
7421 }
7422 else
7423 {
7424 /* If it's not possible to create an IVirtualBoxErrorInfo object
7425 * signal success, as not signalling anything will cause a stuck
7426 * progress object in VBoxSVC. */
7427 console->mControl->SetPowerUpInfo(NULL);
7428 }
7429
7430 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
7431 }
7432
7433#if defined(RT_OS_WINDOWS)
7434 /* uninitialize COM */
7435 CoUninitialize();
7436#endif
7437
7438 LogFlowFuncLeave();
7439
7440 return VINF_SUCCESS;
7441}
7442
7443
7444/**
7445 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
7446 *
7447 * @param pVM The VM handle.
7448 * @param lInstance The instance of the controller.
7449 * @param pcszDevice The name of the controller type.
7450 * @param enmBus The storage bus type of the controller.
7451 * @param fSetupMerge Whether to set up a medium merge
7452 * @param uMergeSource Merge source image index
7453 * @param uMergeTarget Merge target image index
7454 * @param aMediumAtt The medium attachment.
7455 * @param aMachineState The current machine state.
7456 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
7457 * @return VBox status code.
7458 */
7459/* static */
7460DECLCALLBACK(int) Console::reconfigureMediumAttachment(PVM pVM,
7461 const char *pcszDevice,
7462 unsigned uInstance,
7463 StorageBus_T enmBus,
7464 IoBackendType_T enmIoBackend,
7465 bool fSetupMerge,
7466 unsigned uMergeSource,
7467 unsigned uMergeTarget,
7468 IMediumAttachment *aMediumAtt,
7469 MachineState_T aMachineState,
7470 HRESULT *phrc)
7471{
7472 LogFlowFunc(("pVM=%p aMediumAtt=%p phrc=%p\n", pVM, aMediumAtt, phrc));
7473
7474 int rc;
7475 HRESULT hrc;
7476 Bstr bstr;
7477 *phrc = S_OK;
7478#define RC_CHECK() do { if (RT_FAILURE(rc)) { AssertMsgFailed(("rc=%Rrc\n", rc)); return rc; } } while (0)
7479#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
7480
7481 /* Ignore attachments other than hard disks, since at the moment they are
7482 * not subject to snapshotting in general. */
7483 DeviceType_T lType;
7484 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
7485 if (lType != DeviceType_HardDisk)
7486 return VINF_SUCCESS;
7487
7488 /* Determine the base path for the device instance. */
7489 PCFGMNODE pCtlInst;
7490 pCtlInst = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/%s/%u/", pcszDevice, uInstance);
7491 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
7492
7493 /* Update the device instance configuration. */
7494 rc = Console::configMediumAttachment(pCtlInst, pcszDevice, uInstance,
7495 enmBus, enmIoBackend,
7496 fSetupMerge, uMergeSource,
7497 uMergeTarget, aMediumAtt,
7498 aMachineState, phrc,
7499 true /* fAttachDetach */,
7500 false /* fForceUnmount */, pVM,
7501 NULL /* paLedDevType */);
7502 /** @todo this dumps everything attached to this device instance, which
7503 * is more than necessary. Dumping the changed LUN would be enough. */
7504 CFGMR3Dump(pCtlInst);
7505 RC_CHECK();
7506
7507#undef RC_CHECK
7508#undef H
7509
7510 LogFlowFunc(("Returns success\n"));
7511 return VINF_SUCCESS;
7512}
7513
7514/**
7515 * Progress cancelation callback employed by Console::fntTakeSnapshotWorker.
7516 */
7517static void takesnapshotProgressCancelCallback(void *pvUser)
7518{
7519 PVM pVM = (PVM)pvUser;
7520 SSMR3Cancel(pVM);
7521}
7522
7523/**
7524 * Worker thread created by Console::TakeSnapshot.
7525 * @param Thread The current thread (ignored).
7526 * @param pvUser The task.
7527 * @return VINF_SUCCESS (ignored).
7528 */
7529/*static*/
7530DECLCALLBACK(int) Console::fntTakeSnapshotWorker(RTTHREAD Thread, void *pvUser)
7531{
7532 VMTakeSnapshotTask *pTask = (VMTakeSnapshotTask*)pvUser;
7533
7534 // taking a snapshot consists of the following:
7535
7536 // 1) creating a diff image for each virtual hard disk, into which write operations go after
7537 // the snapshot has been created (done in VBoxSVC, in SessionMachine::BeginTakingSnapshot)
7538 // 2) creating a Snapshot object with the state of the machine (hardware + storage,
7539 // done in VBoxSVC, also in SessionMachine::BeginTakingSnapshot)
7540 // 3) saving the state of the virtual machine (here, in the VM process, if the machine is online)
7541
7542 Console *that = pTask->mConsole;
7543 bool fBeganTakingSnapshot = false;
7544 bool fSuspenededBySave = false;
7545
7546 AutoCaller autoCaller(that);
7547 if (FAILED(autoCaller.rc()))
7548 {
7549 that->mptrCancelableProgress.setNull();
7550 return autoCaller.rc();
7551 }
7552
7553 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7554
7555 HRESULT rc = S_OK;
7556
7557 try
7558 {
7559 /* STEP 1 + 2:
7560 * request creating the diff images on the server and create the snapshot object
7561 * (this will set the machine state to Saving on the server to block
7562 * others from accessing this machine)
7563 */
7564 rc = that->mControl->BeginTakingSnapshot(that,
7565 pTask->bstrName,
7566 pTask->bstrDescription,
7567 pTask->mProgress,
7568 pTask->fTakingSnapshotOnline,
7569 pTask->bstrSavedStateFile.asOutParam());
7570 if (FAILED(rc))
7571 throw rc;
7572
7573 fBeganTakingSnapshot = true;
7574
7575 /*
7576 * state file is non-null only when the VM is paused
7577 * (i.e. creating a snapshot online)
7578 */
7579 ComAssertThrow( (!pTask->bstrSavedStateFile.isEmpty() && pTask->fTakingSnapshotOnline)
7580 || ( pTask->bstrSavedStateFile.isEmpty() && !pTask->fTakingSnapshotOnline),
7581 rc = E_FAIL);
7582
7583 /* sync the state with the server */
7584 if (pTask->lastMachineState == MachineState_Running)
7585 that->setMachineStateLocally(MachineState_LiveSnapshotting);
7586 else
7587 that->setMachineStateLocally(MachineState_Saving);
7588
7589 // STEP 3: save the VM state (if online)
7590 if (pTask->fTakingSnapshotOnline)
7591 {
7592 Utf8Str strSavedStateFile(pTask->bstrSavedStateFile);
7593
7594 pTask->mProgress->SetNextOperation(Bstr(tr("Saving the machine state")),
7595 pTask->ulMemSize); // operation weight, same as computed when setting up progress object
7596 pTask->mProgress->setCancelCallback(takesnapshotProgressCancelCallback, that->mpVM);
7597
7598 alock.leave();
7599 LogFlowFunc(("VMR3Save...\n"));
7600 int vrc = VMR3Save(that->mpVM,
7601 strSavedStateFile.c_str(),
7602 true /*fContinueAfterwards*/,
7603 Console::stateProgressCallback,
7604 (void*)pTask,
7605 &fSuspenededBySave);
7606 alock.enter();
7607 if (RT_FAILURE(vrc))
7608 throw setError(E_FAIL,
7609 tr("Failed to save the machine state to '%s' (%Rrc)"),
7610 strSavedStateFile.c_str(), vrc);
7611
7612 pTask->mProgress->setCancelCallback(NULL, NULL);
7613 if (!pTask->mProgress->notifyPointOfNoReturn())
7614 throw setError(E_FAIL, tr("Cancelled"));
7615 that->mptrCancelableProgress.setNull();
7616
7617 // STEP 4: reattach hard disks
7618 LogFlowFunc(("Reattaching new differencing hard disks...\n"));
7619
7620 pTask->mProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")),
7621 1); // operation weight, same as computed when setting up progress object
7622
7623 com::SafeIfaceArray<IMediumAttachment> atts;
7624 rc = that->mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7625 if (FAILED(rc))
7626 throw rc;
7627
7628 for (size_t i = 0;
7629 i < atts.size();
7630 ++i)
7631 {
7632 ComPtr<IStorageController> controller;
7633 BSTR controllerName;
7634 ULONG lInstance;
7635 StorageControllerType_T enmController;
7636 StorageBus_T enmBus;
7637 IoBackendType_T enmIoBackend;
7638
7639 /*
7640 * We can't pass a storage controller object directly
7641 * (g++ complains about not being able to pass non POD types through '...')
7642 * so we have to query needed values here and pass them.
7643 */
7644 rc = atts[i]->COMGETTER(Controller)(&controllerName);
7645 if (FAILED(rc))
7646 throw rc;
7647
7648 rc = that->mMachine->GetStorageControllerByName(controllerName, controller.asOutParam());
7649 if (FAILED(rc))
7650 throw rc;
7651
7652 rc = controller->COMGETTER(ControllerType)(&enmController);
7653 if (FAILED(rc))
7654 throw rc;
7655 rc = controller->COMGETTER(Instance)(&lInstance);
7656 if (FAILED(rc))
7657 throw rc;
7658 rc = controller->COMGETTER(Bus)(&enmBus);
7659 if (FAILED(rc))
7660 throw rc;
7661 rc = controller->COMGETTER(IoBackend)(&enmIoBackend);
7662 if (FAILED(rc))
7663 throw rc;
7664
7665 const char *pcszDevice = Console::convertControllerTypeToDev(enmController);
7666
7667 /*
7668 * don't leave the lock since reconfigureMediumAttachment
7669 * isn't going to need the Console lock.
7670 */
7671 vrc = VMR3ReqCallWait(that->mpVM,
7672 VMCPUID_ANY,
7673 (PFNRT)reconfigureMediumAttachment,
7674 11,
7675 that->mpVM,
7676 pcszDevice,
7677 lInstance,
7678 enmBus,
7679 enmIoBackend,
7680 false /* fSetupMerge */,
7681 0 /* uMergeSource */,
7682 0 /* uMergeTarget */,
7683 atts[i],
7684 that->mMachineState,
7685 &rc);
7686 if (RT_FAILURE(vrc))
7687 throw setError(E_FAIL, Console::tr("%Rrc"), vrc);
7688 if (FAILED(rc))
7689 throw rc;
7690 }
7691 }
7692
7693 /*
7694 * finalize the requested snapshot object.
7695 * This will reset the machine state to the state it had right
7696 * before calling mControl->BeginTakingSnapshot().
7697 */
7698 rc = that->mControl->EndTakingSnapshot(TRUE /*aSuccess*/);
7699 // do not throw rc here because we can't call EndTakingSnapshot() twice
7700 LogFlowFunc(("EndTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
7701 }
7702 catch (HRESULT rcThrown)
7703 {
7704 /* preserve existing error info */
7705 ErrorInfoKeeper eik;
7706
7707 if (fBeganTakingSnapshot)
7708 that->mControl->EndTakingSnapshot(FALSE /*aSuccess*/);
7709
7710 rc = rcThrown;
7711 LogFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
7712 }
7713 Assert(alock.isWriteLockOnCurrentThread());
7714
7715 if (FAILED(rc)) /* Must come before calling setMachineState. */
7716 pTask->mProgress->notifyComplete(rc);
7717
7718 /*
7719 * Fix up the machine state.
7720 *
7721 * For live snapshots we do all the work, for the two other variantions we
7722 * just update the local copy.
7723 */
7724 MachineState_T enmMachineState;
7725 that->mMachine->COMGETTER(State)(&enmMachineState);
7726 if ( that->mMachineState == MachineState_LiveSnapshotting
7727 || that->mMachineState == MachineState_Saving)
7728 {
7729
7730 if (!pTask->fTakingSnapshotOnline)
7731 that->setMachineStateLocally(pTask->lastMachineState);
7732 else if (SUCCEEDED(rc))
7733 {
7734 Assert( pTask->lastMachineState == MachineState_Running
7735 || pTask->lastMachineState == MachineState_Paused);
7736 Assert(that->mMachineState == MachineState_Saving);
7737 if (pTask->lastMachineState == MachineState_Running)
7738 {
7739 LogFlowFunc(("VMR3Resume...\n"));
7740 alock.leave();
7741 int vrc = VMR3Resume(that->mpVM);
7742 alock.enter();
7743 if (RT_FAILURE(vrc))
7744 {
7745 rc = setError(VBOX_E_VM_ERROR, tr("Could not resume the machine execution (%Rrc)"), vrc);
7746 pTask->mProgress->notifyComplete(rc);
7747 if (that->mMachineState == MachineState_Saving)
7748 that->setMachineStateLocally(MachineState_Paused);
7749 }
7750 }
7751 else
7752 that->setMachineStateLocally(MachineState_Paused);
7753 }
7754 else
7755 {
7756 /** @todo this could probably be made more generic and reused elsewhere. */
7757 /* paranoid cleanup on for a failed online snapshot. */
7758 VMSTATE enmVMState = VMR3GetState(that->mpVM);
7759 switch (enmVMState)
7760 {
7761 case VMSTATE_RUNNING:
7762 case VMSTATE_RUNNING_LS:
7763 case VMSTATE_DEBUGGING:
7764 case VMSTATE_DEBUGGING_LS:
7765 case VMSTATE_POWERING_OFF:
7766 case VMSTATE_POWERING_OFF_LS:
7767 case VMSTATE_RESETTING:
7768 case VMSTATE_RESETTING_LS:
7769 Assert(!fSuspenededBySave);
7770 that->setMachineState(MachineState_Running);
7771 break;
7772
7773 case VMSTATE_GURU_MEDITATION:
7774 case VMSTATE_GURU_MEDITATION_LS:
7775 that->setMachineState(MachineState_Stuck);
7776 break;
7777
7778 case VMSTATE_FATAL_ERROR:
7779 case VMSTATE_FATAL_ERROR_LS:
7780 if (pTask->lastMachineState == MachineState_Paused)
7781 that->setMachineStateLocally(pTask->lastMachineState);
7782 else
7783 that->setMachineState(MachineState_Paused);
7784 break;
7785
7786 default:
7787 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
7788 case VMSTATE_SUSPENDED:
7789 case VMSTATE_SUSPENDED_LS:
7790 case VMSTATE_SUSPENDING:
7791 case VMSTATE_SUSPENDING_LS:
7792 case VMSTATE_SUSPENDING_EXT_LS:
7793 if (fSuspenededBySave)
7794 {
7795 Assert(pTask->lastMachineState == MachineState_Running);
7796 LogFlowFunc(("VMR3Resume (on failure)...\n"));
7797 alock.leave();
7798 int vrc = VMR3Resume(that->mpVM);
7799 alock.enter();
7800 AssertLogRelRC(vrc);
7801 if (RT_FAILURE(vrc))
7802 that->setMachineState(MachineState_Paused);
7803 }
7804 else if (pTask->lastMachineState == MachineState_Paused)
7805 that->setMachineStateLocally(pTask->lastMachineState);
7806 else
7807 that->setMachineState(MachineState_Paused);
7808 break;
7809 }
7810
7811 }
7812 }
7813 /*else: somebody else has change the state... Leave it. */
7814
7815 /* check the remote state to see that we got it right. */
7816 that->mMachine->COMGETTER(State)(&enmMachineState);
7817 AssertLogRelMsg(that->mMachineState == enmMachineState,
7818 ("mMachineState=%s enmMachineState=%s\n", Global::stringifyMachineState(that->mMachineState),
7819 Global::stringifyMachineState(enmMachineState) ));
7820
7821
7822 if (SUCCEEDED(rc)) /* The failure cases are handled above. */
7823 pTask->mProgress->notifyComplete(rc);
7824
7825 delete pTask;
7826
7827 LogFlowFuncLeave();
7828 return VINF_SUCCESS;
7829}
7830
7831/**
7832 * Thread for executing the saved state operation.
7833 *
7834 * @param Thread The thread handle.
7835 * @param pvUser Pointer to a VMSaveTask structure.
7836 * @return VINF_SUCCESS (ignored).
7837 *
7838 * @note Locks the Console object for writing.
7839 */
7840/*static*/
7841DECLCALLBACK(int) Console::saveStateThread(RTTHREAD Thread, void *pvUser)
7842{
7843 LogFlowFuncEnter();
7844
7845 std::auto_ptr<VMSaveTask> task(static_cast<VMSaveTask*>(pvUser));
7846 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
7847
7848 Assert(task->mSavedStateFile.length());
7849 Assert(!task->mProgress.isNull());
7850
7851 const ComObjPtr<Console> &that = task->mConsole;
7852 Utf8Str errMsg;
7853 HRESULT rc = S_OK;
7854
7855 LogFlowFunc(("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
7856
7857 bool fSuspenededBySave;
7858 int vrc = VMR3Save(that->mpVM,
7859 task->mSavedStateFile.c_str(),
7860 false, /*fContinueAfterwards*/
7861 Console::stateProgressCallback,
7862 static_cast<VMProgressTask*>(task.get()),
7863 &fSuspenededBySave);
7864 if (RT_FAILURE(vrc))
7865 {
7866 errMsg = Utf8StrFmt(Console::tr("Failed to save the machine state to '%s' (%Rrc)"),
7867 task->mSavedStateFile.raw(), vrc);
7868 rc = E_FAIL;
7869 }
7870 Assert(!fSuspenededBySave);
7871
7872 /* lock the console once we're going to access it */
7873 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
7874
7875 /*
7876 * finalize the requested save state procedure.
7877 * In case of success, the server will set the machine state to Saved;
7878 * in case of failure it will reset the it to the state it had right
7879 * before calling mControl->BeginSavingState().
7880 */
7881 that->mControl->EndSavingState(SUCCEEDED(rc));
7882
7883 /* synchronize the state with the server */
7884 if (!FAILED(rc))
7885 {
7886 /*
7887 * The machine has been successfully saved, so power it down
7888 * (vmstateChangeCallback() will set state to Saved on success).
7889 * Note: we release the task's VM caller, otherwise it will
7890 * deadlock.
7891 */
7892 task->releaseVMCaller();
7893
7894 rc = that->powerDown();
7895 }
7896
7897 /* notify the progress object about operation completion */
7898 if (SUCCEEDED(rc))
7899 task->mProgress->notifyComplete(S_OK);
7900 else
7901 {
7902 if (errMsg.length())
7903 task->mProgress->notifyComplete(rc,
7904 COM_IIDOF(IConsole),
7905 (CBSTR)Console::getComponentName(),
7906 errMsg.c_str());
7907 else
7908 task->mProgress->notifyComplete(rc);
7909 }
7910
7911 LogFlowFuncLeave();
7912 return VINF_SUCCESS;
7913}
7914
7915/**
7916 * Thread for powering down the Console.
7917 *
7918 * @param Thread The thread handle.
7919 * @param pvUser Pointer to the VMTask structure.
7920 * @return VINF_SUCCESS (ignored).
7921 *
7922 * @note Locks the Console object for writing.
7923 */
7924/*static*/
7925DECLCALLBACK(int) Console::powerDownThread(RTTHREAD Thread, void *pvUser)
7926{
7927 LogFlowFuncEnter();
7928
7929 std::auto_ptr<VMProgressTask> task(static_cast<VMProgressTask *>(pvUser));
7930 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
7931
7932 AssertReturn(task->isOk(), VERR_GENERAL_FAILURE);
7933
7934 const ComObjPtr<Console> &that = task->mConsole;
7935
7936 /* Note: no need to use addCaller() to protect Console because VMTask does
7937 * that */
7938
7939 /* wait until the method tat started us returns */
7940 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
7941
7942 /* release VM caller to avoid the powerDown() deadlock */
7943 task->releaseVMCaller();
7944
7945 that->powerDown(task->mProgress);
7946
7947 LogFlowFuncLeave();
7948 return VINF_SUCCESS;
7949}
7950
7951/**
7952 * The Main status driver instance data.
7953 */
7954typedef struct DRVMAINSTATUS
7955{
7956 /** The LED connectors. */
7957 PDMILEDCONNECTORS ILedConnectors;
7958 /** Pointer to the LED ports interface above us. */
7959 PPDMILEDPORTS pLedPorts;
7960 /** Pointer to the array of LED pointers. */
7961 PPDMLED *papLeds;
7962 /** The unit number corresponding to the first entry in the LED array. */
7963 RTUINT iFirstLUN;
7964 /** The unit number corresponding to the last entry in the LED array.
7965 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7966 RTUINT iLastLUN;
7967} DRVMAINSTATUS, *PDRVMAINSTATUS;
7968
7969
7970/**
7971 * Notification about a unit which have been changed.
7972 *
7973 * The driver must discard any pointers to data owned by
7974 * the unit and requery it.
7975 *
7976 * @param pInterface Pointer to the interface structure containing the called function pointer.
7977 * @param iLUN The unit number.
7978 */
7979DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7980{
7981 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7982 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7983 {
7984 PPDMLED pLed;
7985 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7986 if (RT_FAILURE(rc))
7987 pLed = NULL;
7988 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7989 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7990 }
7991}
7992
7993
7994/**
7995 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
7996 */
7997DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
7998{
7999 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
8000 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
8001 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
8002 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
8003 return NULL;
8004}
8005
8006
8007/**
8008 * Destruct a status driver instance.
8009 *
8010 * @returns VBox status.
8011 * @param pDrvIns The driver instance data.
8012 */
8013DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
8014{
8015 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
8016 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
8017 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
8018
8019 if (pData->papLeds)
8020 {
8021 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
8022 while (iLed-- > 0)
8023 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
8024 }
8025}
8026
8027
8028/**
8029 * Construct a status driver instance.
8030 *
8031 * @copydoc FNPDMDRVCONSTRUCT
8032 */
8033DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
8034{
8035 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
8036 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
8037 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
8038
8039 /*
8040 * Validate configuration.
8041 */
8042 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0First\0Last\0"))
8043 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
8044 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
8045 ("Configuration error: Not possible to attach anything to this driver!\n"),
8046 VERR_PDM_DRVINS_NO_ATTACH);
8047
8048 /*
8049 * Data.
8050 */
8051 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
8052 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
8053
8054 /*
8055 * Read config.
8056 */
8057 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pData->papLeds);
8058 if (RT_FAILURE(rc))
8059 {
8060 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
8061 return rc;
8062 }
8063
8064 rc = CFGMR3QueryU32(pCfg, "First", &pData->iFirstLUN);
8065 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
8066 pData->iFirstLUN = 0;
8067 else if (RT_FAILURE(rc))
8068 {
8069 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
8070 return rc;
8071 }
8072
8073 rc = CFGMR3QueryU32(pCfg, "Last", &pData->iLastLUN);
8074 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
8075 pData->iLastLUN = 0;
8076 else if (RT_FAILURE(rc))
8077 {
8078 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
8079 return rc;
8080 }
8081 if (pData->iFirstLUN > pData->iLastLUN)
8082 {
8083 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
8084 return VERR_GENERAL_FAILURE;
8085 }
8086
8087 /*
8088 * Get the ILedPorts interface of the above driver/device and
8089 * query the LEDs we want.
8090 */
8091 pData->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
8092 AssertMsgReturn(pData->pLedPorts, ("Configuration error: No led ports interface above!\n"),
8093 VERR_PDM_MISSING_INTERFACE_ABOVE);
8094
8095 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; ++i)
8096 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
8097
8098 return VINF_SUCCESS;
8099}
8100
8101
8102/**
8103 * Keyboard driver registration record.
8104 */
8105const PDMDRVREG Console::DrvStatusReg =
8106{
8107 /* u32Version */
8108 PDM_DRVREG_VERSION,
8109 /* szName */
8110 "MainStatus",
8111 /* szRCMod */
8112 "",
8113 /* szR0Mod */
8114 "",
8115 /* pszDescription */
8116 "Main status driver (Main as in the API).",
8117 /* fFlags */
8118 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
8119 /* fClass. */
8120 PDM_DRVREG_CLASS_STATUS,
8121 /* cMaxInstances */
8122 ~0,
8123 /* cbInstance */
8124 sizeof(DRVMAINSTATUS),
8125 /* pfnConstruct */
8126 Console::drvStatus_Construct,
8127 /* pfnDestruct */
8128 Console::drvStatus_Destruct,
8129 /* pfnRelocate */
8130 NULL,
8131 /* pfnIOCtl */
8132 NULL,
8133 /* pfnPowerOn */
8134 NULL,
8135 /* pfnReset */
8136 NULL,
8137 /* pfnSuspend */
8138 NULL,
8139 /* pfnResume */
8140 NULL,
8141 /* pfnAttach */
8142 NULL,
8143 /* pfnDetach */
8144 NULL,
8145 /* pfnPowerOff */
8146 NULL,
8147 /* pfnSoftReset */
8148 NULL,
8149 /* u32EndVersion */
8150 PDM_DRVREG_VERSION
8151};
8152
8153/* 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