VirtualBox

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

Last change on this file since 6375 was 6375, checked in by vboxsync, 17 years ago

Main: Fixed VM error callback used during powerup so that it doesn't complete the progress object but simply saves the received error message; Fixed Progress::notifyComplete() to not accept the second and subsequent calls (all for #2238).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 208.0 KB
Line 
1/** @file
2 *
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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#include <iprt/types.h> /* for stdint.h constants */
19
20#if defined(RT_OS_WINDOWS)
21#elif defined(RT_OS_LINUX)
22# include <errno.h>
23# include <sys/ioctl.h>
24# include <sys/poll.h>
25# include <sys/fcntl.h>
26# include <sys/types.h>
27# include <sys/wait.h>
28# include <net/if.h>
29# include <linux/if_tun.h>
30# include <stdio.h>
31# include <stdlib.h>
32# include <string.h>
33#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
34# include <sys/wait.h>
35# include <sys/fcntl.h>
36#endif
37
38#include "ConsoleImpl.h"
39#include "GuestImpl.h"
40#include "KeyboardImpl.h"
41#include "MouseImpl.h"
42#include "DisplayImpl.h"
43#include "MachineDebuggerImpl.h"
44#include "USBDeviceImpl.h"
45#include "RemoteUSBDeviceImpl.h"
46#include "SharedFolderImpl.h"
47#include "AudioSnifferInterface.h"
48#include "ConsoleVRDPServer.h"
49#include "VMMDev.h"
50#include "Version.h"
51
52// generated header
53#include "SchemaDefs.h"
54
55#include "Logging.h"
56
57#include <iprt/string.h>
58#include <iprt/asm.h>
59#include <iprt/file.h>
60#include <iprt/path.h>
61#include <iprt/dir.h>
62#include <iprt/process.h>
63#include <iprt/ldr.h>
64#include <iprt/cpputils.h>
65
66#include <VBox/vmapi.h>
67#include <VBox/err.h>
68#include <VBox/param.h>
69#include <VBox/vusb.h>
70#include <VBox/mm.h>
71#include <VBox/ssm.h>
72#include <VBox/version.h>
73#ifdef VBOX_WITH_USB
74# include <VBox/pdmusb.h>
75#endif
76
77#include <VBox/VBoxDev.h>
78
79#include <VBox/HostServices/VBoxClipboardSvc.h>
80
81#include <set>
82#include <algorithm>
83#include <memory> // for auto_ptr
84
85
86// VMTask and friends
87////////////////////////////////////////////////////////////////////////////////
88
89/**
90 * Task structure for asynchronous VM operations.
91 *
92 * Once created, the task structure adds itself as a Console caller.
93 * This means:
94 *
95 * 1. The user must check for #rc() before using the created structure
96 * (e.g. passing it as a thread function argument). If #rc() returns a
97 * failure, the Console object may not be used by the task (see
98 Console::addCaller() for more details).
99 * 2. On successful initialization, the structure keeps the Console caller
100 * until destruction (to ensure Console remains in the Ready state and won't
101 * be accidentially uninitialized). Forgetting to delete the created task
102 * will lead to Console::uninit() stuck waiting for releasing all added
103 * callers.
104 *
105 * If \a aUsesVMPtr parameter is true, the task structure will also add itself
106 * as a Console::mpVM caller with the same meaning as above. See
107 * Console::addVMCaller() for more info.
108 */
109struct VMTask
110{
111 VMTask (Console *aConsole, bool aUsesVMPtr)
112 : mConsole (aConsole), mCallerAdded (false), mVMCallerAdded (false)
113 {
114 AssertReturnVoid (aConsole);
115 mRC = aConsole->addCaller();
116 if (SUCCEEDED (mRC))
117 {
118 mCallerAdded = true;
119 if (aUsesVMPtr)
120 {
121 mRC = aConsole->addVMCaller();
122 if (SUCCEEDED (mRC))
123 mVMCallerAdded = true;
124 }
125 }
126 }
127
128 ~VMTask()
129 {
130 if (mVMCallerAdded)
131 mConsole->releaseVMCaller();
132 if (mCallerAdded)
133 mConsole->releaseCaller();
134 }
135
136 HRESULT rc() const { return mRC; }
137 bool isOk() const { return SUCCEEDED (rc()); }
138
139 /** Releases the Console caller before destruction. Not normally necessary. */
140 void releaseCaller()
141 {
142 AssertReturnVoid (mCallerAdded);
143 mConsole->releaseCaller();
144 mCallerAdded = false;
145 }
146
147 /** Releases the VM caller before destruction. Not normally necessary. */
148 void releaseVMCaller()
149 {
150 AssertReturnVoid (mVMCallerAdded);
151 mConsole->releaseVMCaller();
152 mVMCallerAdded = false;
153 }
154
155 const ComObjPtr <Console> mConsole;
156
157private:
158
159 HRESULT mRC;
160 bool mCallerAdded : 1;
161 bool mVMCallerAdded : 1;
162};
163
164struct VMProgressTask : public VMTask
165{
166 VMProgressTask (Console *aConsole, Progress *aProgress, bool aUsesVMPtr)
167 : VMTask (aConsole, aUsesVMPtr), mProgress (aProgress) {}
168
169 const ComObjPtr <Progress> mProgress;
170
171 Utf8Str mErrorMsg;
172};
173
174struct VMPowerUpTask : public VMProgressTask
175{
176 VMPowerUpTask (Console *aConsole, Progress *aProgress)
177 : VMProgressTask (aConsole, aProgress, false /* aUsesVMPtr */)
178 , mSetVMErrorCallback (NULL), mConfigConstructor (NULL) {}
179
180 PFNVMATERROR mSetVMErrorCallback;
181 PFNCFGMCONSTRUCTOR mConfigConstructor;
182 Utf8Str mSavedStateFile;
183 Console::SharedFolderDataMap mSharedFolders;
184};
185
186struct VMSaveTask : public VMProgressTask
187{
188 VMSaveTask (Console *aConsole, Progress *aProgress)
189 : VMProgressTask (aConsole, aProgress, true /* aUsesVMPtr */)
190 , mIsSnapshot (false)
191 , mLastMachineState (MachineState_InvalidMachineState) {}
192
193 bool mIsSnapshot;
194 Utf8Str mSavedStateFile;
195 MachineState_T mLastMachineState;
196 ComPtr <IProgress> mServerProgress;
197};
198
199
200// constructor / desctructor
201/////////////////////////////////////////////////////////////////////////////
202
203Console::Console()
204 : mSavedStateDataLoaded (false)
205 , mConsoleVRDPServer (NULL)
206 , mpVM (NULL)
207 , mVMCallers (0)
208 , mVMZeroCallersSem (NIL_RTSEMEVENT)
209 , mVMDestroying (false)
210 , meDVDState (DriveState_NotMounted)
211 , meFloppyState (DriveState_NotMounted)
212 , mVMMDev (NULL)
213 , mAudioSniffer (NULL)
214 , mVMStateChangeCallbackDisabled (false)
215 , mMachineState (MachineState_PoweredOff)
216{}
217
218Console::~Console()
219{}
220
221HRESULT Console::FinalConstruct()
222{
223 LogFlowThisFunc (("\n"));
224
225 memset(mapFDLeds, 0, sizeof(mapFDLeds));
226 memset(mapIDELeds, 0, sizeof(mapIDELeds));
227 memset(mapNetworkLeds, 0, sizeof(mapNetworkLeds));
228 memset(&mapUSBLed, 0, sizeof(mapUSBLed));
229 memset(&mapSharedFolderLed, 0, sizeof(mapSharedFolderLed));
230
231#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
232 Assert(ELEMENTS(maTapFD) == ELEMENTS(maTAPDeviceName));
233 Assert(ELEMENTS(maTapFD) >= SchemaDefs::NetworkAdapterCount);
234 for (unsigned i = 0; i < ELEMENTS(maTapFD); i++)
235 {
236 maTapFD[i] = NIL_RTFILE;
237 maTAPDeviceName[i] = "";
238 }
239#endif
240
241 return S_OK;
242}
243
244void Console::FinalRelease()
245{
246 LogFlowThisFunc (("\n"));
247
248 uninit();
249}
250
251// public initializer/uninitializer for internal purposes only
252/////////////////////////////////////////////////////////////////////////////
253
254HRESULT Console::init (IMachine *aMachine, IInternalMachineControl *aControl)
255{
256 AssertReturn (aMachine && aControl, E_INVALIDARG);
257
258 /* Enclose the state transition NotReady->InInit->Ready */
259 AutoInitSpan autoInitSpan (this);
260 AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
261
262 LogFlowThisFuncEnter();
263 LogFlowThisFunc(("aMachine=%p, aControl=%p\n", aMachine, aControl));
264
265 HRESULT rc = E_FAIL;
266
267 unconst (mMachine) = aMachine;
268 unconst (mControl) = aControl;
269
270 memset (&mCallbackData, 0, sizeof (mCallbackData));
271
272 /* Cache essential properties and objects */
273
274 rc = mMachine->COMGETTER(State) (&mMachineState);
275 AssertComRCReturnRC (rc);
276
277#ifdef VBOX_VRDP
278 rc = mMachine->COMGETTER(VRDPServer) (unconst (mVRDPServer).asOutParam());
279 AssertComRCReturnRC (rc);
280#endif
281
282 rc = mMachine->COMGETTER(DVDDrive) (unconst (mDVDDrive).asOutParam());
283 AssertComRCReturnRC (rc);
284
285 rc = mMachine->COMGETTER(FloppyDrive) (unconst (mFloppyDrive).asOutParam());
286 AssertComRCReturnRC (rc);
287
288 /* Create associated child COM objects */
289
290 unconst (mGuest).createObject();
291 rc = mGuest->init (this);
292 AssertComRCReturnRC (rc);
293
294 unconst (mKeyboard).createObject();
295 rc = mKeyboard->init (this);
296 AssertComRCReturnRC (rc);
297
298 unconst (mMouse).createObject();
299 rc = mMouse->init (this);
300 AssertComRCReturnRC (rc);
301
302 unconst (mDisplay).createObject();
303 rc = mDisplay->init (this);
304 AssertComRCReturnRC (rc);
305
306 unconst (mRemoteDisplayInfo).createObject();
307 rc = mRemoteDisplayInfo->init (this);
308 AssertComRCReturnRC (rc);
309
310 /* Grab global and machine shared folder lists */
311
312 rc = fetchSharedFolders (true /* aGlobal */);
313 AssertComRCReturnRC (rc);
314 rc = fetchSharedFolders (false /* aGlobal */);
315 AssertComRCReturnRC (rc);
316
317 /* Create other child objects */
318
319 unconst (mConsoleVRDPServer) = new ConsoleVRDPServer (this);
320 AssertReturn (mConsoleVRDPServer, E_FAIL);
321
322 mcAudioRefs = 0;
323 mcVRDPClients = 0;
324
325 unconst (mVMMDev) = new VMMDev(this);
326 AssertReturn (mVMMDev, E_FAIL);
327
328 unconst (mAudioSniffer) = new AudioSniffer(this);
329 AssertReturn (mAudioSniffer, E_FAIL);
330
331 /* Confirm a successful initialization when it's the case */
332 autoInitSpan.setSucceeded();
333
334 LogFlowThisFuncLeave();
335
336 return S_OK;
337}
338
339/**
340 * Uninitializes the Console object.
341 */
342void Console::uninit()
343{
344 LogFlowThisFuncEnter();
345
346 /* Enclose the state transition Ready->InUninit->NotReady */
347 AutoUninitSpan autoUninitSpan (this);
348 if (autoUninitSpan.uninitDone())
349 {
350 LogFlowThisFunc (("Already uninitialized.\n"));
351 LogFlowThisFuncLeave();
352 return;
353 }
354
355 LogFlowThisFunc (("initFailed()=%d\n", autoUninitSpan.initFailed()));
356
357 /*
358 * Uninit all children that ise addDependentChild()/removeDependentChild()
359 * in their init()/uninit() methods.
360 */
361 uninitDependentChildren();
362
363 /* power down the VM if necessary */
364 if (mpVM)
365 {
366 powerDown();
367 Assert (mpVM == NULL);
368 }
369
370 if (mVMZeroCallersSem != NIL_RTSEMEVENT)
371 {
372 RTSemEventDestroy (mVMZeroCallersSem);
373 mVMZeroCallersSem = NIL_RTSEMEVENT;
374 }
375
376 if (mAudioSniffer)
377 {
378 delete mAudioSniffer;
379 unconst (mAudioSniffer) = NULL;
380 }
381
382 if (mVMMDev)
383 {
384 delete mVMMDev;
385 unconst (mVMMDev) = NULL;
386 }
387
388 mGlobalSharedFolders.clear();
389 mMachineSharedFolders.clear();
390
391 mSharedFolders.clear();
392 mRemoteUSBDevices.clear();
393 mUSBDevices.clear();
394
395 if (mRemoteDisplayInfo)
396 {
397 mRemoteDisplayInfo->uninit();
398 unconst (mRemoteDisplayInfo).setNull();;
399 }
400
401 if (mDebugger)
402 {
403 mDebugger->uninit();
404 unconst (mDebugger).setNull();
405 }
406
407 if (mDisplay)
408 {
409 mDisplay->uninit();
410 unconst (mDisplay).setNull();
411 }
412
413 if (mMouse)
414 {
415 mMouse->uninit();
416 unconst (mMouse).setNull();
417 }
418
419 if (mKeyboard)
420 {
421 mKeyboard->uninit();
422 unconst (mKeyboard).setNull();;
423 }
424
425 if (mGuest)
426 {
427 mGuest->uninit();
428 unconst (mGuest).setNull();;
429 }
430
431 if (mConsoleVRDPServer)
432 {
433 delete mConsoleVRDPServer;
434 unconst (mConsoleVRDPServer) = NULL;
435 }
436
437 unconst (mFloppyDrive).setNull();
438 unconst (mDVDDrive).setNull();
439#ifdef VBOX_VRDP
440 unconst (mVRDPServer).setNull();
441#endif
442
443 unconst (mControl).setNull();
444 unconst (mMachine).setNull();
445
446 /* Release all callbacks. Do this after uninitializing the components,
447 * as some of them are well-behaved and unregister their callbacks.
448 * These would trigger error messages complaining about trying to
449 * unregister a non-registered callback. */
450 mCallbacks.clear();
451
452 /* dynamically allocated members of mCallbackData are uninitialized
453 * at the end of powerDown() */
454 Assert (!mCallbackData.mpsc.valid && mCallbackData.mpsc.shape == NULL);
455 Assert (!mCallbackData.mcc.valid);
456 Assert (!mCallbackData.klc.valid);
457
458 LogFlowThisFuncLeave();
459}
460
461int Console::VRDPClientLogon (uint32_t u32ClientId, const char *pszUser, const char *pszPassword, const char *pszDomain)
462{
463 LogFlowFuncEnter();
464 LogFlowFunc (("%d, %s, %s, %s\n", u32ClientId, pszUser, pszPassword, pszDomain));
465
466 AutoCaller autoCaller (this);
467 if (!autoCaller.isOk())
468 {
469 /* Console has been already uninitialized, deny request */
470 LogRel(("VRDPAUTH: Access denied (Console uninitialized).\n"));
471 LogFlowFuncLeave();
472 return VERR_ACCESS_DENIED;
473 }
474
475 Guid uuid;
476 HRESULT hrc = mMachine->COMGETTER (Id) (uuid.asOutParam());
477 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
478
479 VRDPAuthType_T authType = VRDPAuthType_VRDPAuthNull;
480 hrc = mVRDPServer->COMGETTER(AuthType) (&authType);
481 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
482
483 ULONG authTimeout = 0;
484 hrc = mVRDPServer->COMGETTER(AuthTimeout) (&authTimeout);
485 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
486
487 VRDPAuthResult result = VRDPAuthAccessDenied;
488 VRDPAuthGuestJudgement guestJudgement = VRDPAuthGuestNotAsked;
489
490 LogFlowFunc(("Auth type %d\n", authType));
491
492 LogRel (("VRDPAUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
493 pszUser, pszDomain,
494 authType == VRDPAuthType_VRDPAuthNull?
495 "null":
496 (authType == VRDPAuthType_VRDPAuthExternal?
497 "external":
498 (authType == VRDPAuthType_VRDPAuthGuest?
499 "guest":
500 "INVALID"
501 )
502 )
503 ));
504
505 /* Multiconnection check. */
506 BOOL allowMultiConnection = FALSE;
507 hrc = mVRDPServer->COMGETTER(AllowMultiConnection) (&allowMultiConnection);
508 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
509
510 LogFlowFunc(("allowMultiConnection %d, mcVRDPClients = %d\n", allowMultiConnection, mcVRDPClients));
511
512 if (allowMultiConnection == FALSE)
513 {
514 /* Note: the variable is incremented in ClientConnect callback, which is called when the client
515 * is successfully connected, that is after the ClientLogon callback. Therefore the mcVRDPClients
516 * value is 0 for first client.
517 */
518 if (mcVRDPClients > 0)
519 {
520 /* Reject. */
521 LogRel(("VRDPAUTH: Multiple connections are not enabled. Access denied.\n"));
522 return VERR_ACCESS_DENIED;
523 }
524 }
525
526 switch (authType)
527 {
528 case VRDPAuthType_VRDPAuthNull:
529 {
530 result = VRDPAuthAccessGranted;
531 break;
532 }
533
534 case VRDPAuthType_VRDPAuthExternal:
535 {
536 /* Call the external library. */
537 result = mConsoleVRDPServer->Authenticate (uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
538
539 if (result != VRDPAuthDelegateToGuest)
540 {
541 break;
542 }
543
544 LogRel(("VRDPAUTH: Delegated to guest.\n"));
545
546 LogFlowFunc (("External auth asked for guest judgement\n"));
547 } /* pass through */
548
549 case VRDPAuthType_VRDPAuthGuest:
550 {
551 guestJudgement = VRDPAuthGuestNotReacted;
552
553 if (mVMMDev)
554 {
555 /* Issue the request to guest. Assume that the call does not require EMT. It should not. */
556
557 /* Ask the guest to judge these credentials. */
558 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_JUDGE;
559
560 int rc = mVMMDev->getVMMDevPort()->pfnSetCredentials (mVMMDev->getVMMDevPort(),
561 pszUser, pszPassword, pszDomain, u32GuestFlags);
562
563 if (VBOX_SUCCESS (rc))
564 {
565 /* Wait for guest. */
566 rc = mVMMDev->WaitCredentialsJudgement (authTimeout, &u32GuestFlags);
567
568 if (VBOX_SUCCESS (rc))
569 {
570 switch (u32GuestFlags & (VMMDEV_CREDENTIALS_JUDGE_OK | VMMDEV_CREDENTIALS_JUDGE_DENY | VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT))
571 {
572 case VMMDEV_CREDENTIALS_JUDGE_DENY: guestJudgement = VRDPAuthGuestAccessDenied; break;
573 case VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT: guestJudgement = VRDPAuthGuestNoJudgement; break;
574 case VMMDEV_CREDENTIALS_JUDGE_OK: guestJudgement = VRDPAuthGuestAccessGranted; break;
575 default:
576 LogFlowFunc (("Invalid guest flags %08X!!!\n", u32GuestFlags)); break;
577 }
578 }
579 else
580 {
581 LogFlowFunc (("Wait for credentials judgement rc = %Vrc!!!\n", rc));
582 }
583
584 LogFlowFunc (("Guest judgement %d\n", guestJudgement));
585 }
586 else
587 {
588 LogFlowFunc (("Could not set credentials rc = %Vrc!!!\n", rc));
589 }
590 }
591
592 if (authType == VRDPAuthType_VRDPAuthExternal)
593 {
594 LogRel(("VRDPAUTH: Guest judgement %d.\n", guestJudgement));
595 LogFlowFunc (("External auth called again with guest judgement = %d\n", guestJudgement));
596 result = mConsoleVRDPServer->Authenticate (uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
597 }
598 else
599 {
600 switch (guestJudgement)
601 {
602 case VRDPAuthGuestAccessGranted:
603 result = VRDPAuthAccessGranted;
604 break;
605 default:
606 result = VRDPAuthAccessDenied;
607 break;
608 }
609 }
610 } break;
611
612 default:
613 AssertFailed();
614 }
615
616 LogFlowFunc (("Result = %d\n", result));
617 LogFlowFuncLeave();
618
619 if (result == VRDPAuthAccessGranted)
620 {
621 LogRel(("VRDPAUTH: Access granted.\n"));
622 return VINF_SUCCESS;
623 }
624
625 /* Reject. */
626 LogRel(("VRDPAUTH: Access denied.\n"));
627 return VERR_ACCESS_DENIED;
628}
629
630void Console::VRDPClientConnect (uint32_t u32ClientId)
631{
632 LogFlowFuncEnter();
633
634 AutoCaller autoCaller (this);
635 AssertComRCReturnVoid (autoCaller.rc());
636
637#ifdef VBOX_VRDP
638 uint32_t u32Clients = ASMAtomicIncU32(&mcVRDPClients);
639
640 if (u32Clients == 1)
641 {
642 getVMMDev()->getVMMDevPort()->
643 pfnVRDPChange (getVMMDev()->getVMMDevPort(),
644 true, VRDP_EXPERIENCE_LEVEL_FULL); // @todo configurable
645 }
646
647 NOREF(u32ClientId);
648 mDisplay->VideoAccelVRDP (true);
649#endif /* VBOX_VRDP */
650
651 LogFlowFuncLeave();
652 return;
653}
654
655void Console::VRDPClientDisconnect (uint32_t u32ClientId,
656 uint32_t fu32Intercepted)
657{
658 LogFlowFuncEnter();
659
660 AutoCaller autoCaller (this);
661 AssertComRCReturnVoid (autoCaller.rc());
662
663 AssertReturnVoid (mConsoleVRDPServer);
664
665#ifdef VBOX_VRDP
666 uint32_t u32Clients = ASMAtomicDecU32(&mcVRDPClients);
667
668 if (u32Clients == 0)
669 {
670 getVMMDev()->getVMMDevPort()->
671 pfnVRDPChange (getVMMDev()->getVMMDevPort(),
672 false, 0);
673 }
674
675 mDisplay->VideoAccelVRDP (false);
676#endif /* VBOX_VRDP */
677
678 if (fu32Intercepted & VRDP_CLIENT_INTERCEPT_USB)
679 {
680 mConsoleVRDPServer->USBBackendDelete (u32ClientId);
681 }
682
683#ifdef VBOX_VRDP
684 if (fu32Intercepted & VRDP_CLIENT_INTERCEPT_CLIPBOARD)
685 {
686 mConsoleVRDPServer->ClipboardDelete (u32ClientId);
687 }
688
689 if (fu32Intercepted & VRDP_CLIENT_INTERCEPT_AUDIO)
690 {
691 mcAudioRefs--;
692
693 if (mcAudioRefs <= 0)
694 {
695 if (mAudioSniffer)
696 {
697 PPDMIAUDIOSNIFFERPORT port = mAudioSniffer->getAudioSnifferPort();
698 if (port)
699 {
700 port->pfnSetup (port, false, false);
701 }
702 }
703 }
704 }
705#endif /* VBOX_VRDP */
706
707 Guid uuid;
708 HRESULT hrc = mMachine->COMGETTER (Id) (uuid.asOutParam());
709 AssertComRC (hrc);
710
711 VRDPAuthType_T authType = VRDPAuthType_VRDPAuthNull;
712 hrc = mVRDPServer->COMGETTER(AuthType) (&authType);
713 AssertComRC (hrc);
714
715 if (authType == VRDPAuthType_VRDPAuthExternal)
716 mConsoleVRDPServer->AuthDisconnect (uuid, u32ClientId);
717
718 LogFlowFuncLeave();
719 return;
720}
721
722void Console::VRDPInterceptAudio (uint32_t u32ClientId)
723{
724 LogFlowFuncEnter();
725
726 AutoCaller autoCaller (this);
727 AssertComRCReturnVoid (autoCaller.rc());
728
729 LogFlowFunc (("mAudioSniffer %p, u32ClientId %d.\n",
730 mAudioSniffer, u32ClientId));
731 NOREF(u32ClientId);
732
733#ifdef VBOX_VRDP
734 mcAudioRefs++;
735
736 if (mcAudioRefs == 1)
737 {
738 if (mAudioSniffer)
739 {
740 PPDMIAUDIOSNIFFERPORT port = mAudioSniffer->getAudioSnifferPort();
741 if (port)
742 {
743 port->pfnSetup (port, true, true);
744 }
745 }
746 }
747#endif
748
749 LogFlowFuncLeave();
750 return;
751}
752
753void Console::VRDPInterceptUSB (uint32_t u32ClientId, void **ppvIntercept)
754{
755 LogFlowFuncEnter();
756
757 AutoCaller autoCaller (this);
758 AssertComRCReturnVoid (autoCaller.rc());
759
760 AssertReturnVoid (mConsoleVRDPServer);
761
762 mConsoleVRDPServer->USBBackendCreate (u32ClientId, ppvIntercept);
763
764 LogFlowFuncLeave();
765 return;
766}
767
768void Console::VRDPInterceptClipboard (uint32_t u32ClientId)
769{
770 LogFlowFuncEnter();
771
772 AutoCaller autoCaller (this);
773 AssertComRCReturnVoid (autoCaller.rc());
774
775 AssertReturnVoid (mConsoleVRDPServer);
776
777#ifdef VBOX_VRDP
778 mConsoleVRDPServer->ClipboardCreate (u32ClientId);
779#endif /* VBOX_VRDP */
780
781 LogFlowFuncLeave();
782 return;
783}
784
785
786//static
787const char *Console::sSSMConsoleUnit = "ConsoleData";
788//static
789uint32_t Console::sSSMConsoleVer = 0x00010000;
790
791/**
792 * Loads various console data stored in the saved state file.
793 * This method does validation of the state file and returns an error info
794 * when appropriate.
795 *
796 * The method does nothing if the machine is not in the Saved file or if
797 * console data from it has already been loaded.
798 *
799 * @note The caller must lock this object for writing.
800 */
801HRESULT Console::loadDataFromSavedState()
802{
803 if (mMachineState != MachineState_Saved || mSavedStateDataLoaded)
804 return S_OK;
805
806 Bstr savedStateFile;
807 HRESULT rc = mMachine->COMGETTER(StateFilePath) (savedStateFile.asOutParam());
808 if (FAILED (rc))
809 return rc;
810
811 PSSMHANDLE ssm;
812 int vrc = SSMR3Open (Utf8Str(savedStateFile), 0, &ssm);
813 if (VBOX_SUCCESS (vrc))
814 {
815 uint32_t version = 0;
816 vrc = SSMR3Seek (ssm, sSSMConsoleUnit, 0 /* iInstance */, &version);
817 if (version == sSSMConsoleVer)
818 {
819 if (VBOX_SUCCESS (vrc))
820 vrc = loadStateFileExec (ssm, this, 0);
821 else if (vrc == VERR_SSM_UNIT_NOT_FOUND)
822 vrc = VINF_SUCCESS;
823 }
824 else
825 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
826
827 SSMR3Close (ssm);
828 }
829
830 if (VBOX_FAILURE (vrc))
831 rc = setError (E_FAIL,
832 tr ("The saved state file '%ls' is invalid (%Vrc). "
833 "Discard the saved state and try again"),
834 savedStateFile.raw(), vrc);
835
836 mSavedStateDataLoaded = true;
837
838 return rc;
839}
840
841/**
842 * Callback handler to save various console data to the state file,
843 * called when the user saves the VM state.
844 *
845 * @param pvUser pointer to Console
846 *
847 * @note Locks the Console object for reading.
848 */
849//static
850DECLCALLBACK(void)
851Console::saveStateFileExec (PSSMHANDLE pSSM, void *pvUser)
852{
853 LogFlowFunc (("\n"));
854
855 Console *that = static_cast <Console *> (pvUser);
856 AssertReturnVoid (that);
857
858 AutoCaller autoCaller (that);
859 AssertComRCReturnVoid (autoCaller.rc());
860
861 AutoReaderLock alock (that);
862
863 int vrc = SSMR3PutU32 (pSSM, (uint32_t)that->mSharedFolders.size());
864 AssertRC (vrc);
865
866 for (SharedFolderMap::const_iterator it = that->mSharedFolders.begin();
867 it != that->mSharedFolders.end();
868 ++ it)
869 {
870 ComObjPtr <SharedFolder> folder = (*it).second;
871 // don't lock the folder because methods we access are const
872
873 Utf8Str name = folder->name();
874 vrc = SSMR3PutU32 (pSSM, (uint32_t)name.length() + 1 /* term. 0 */);
875 AssertRC (vrc);
876 vrc = SSMR3PutStrZ (pSSM, name);
877 AssertRC (vrc);
878
879 Utf8Str hostPath = folder->hostPath();
880 vrc = SSMR3PutU32 (pSSM, (uint32_t)hostPath.length() + 1 /* term. 0 */);
881 AssertRC (vrc);
882 vrc = SSMR3PutStrZ (pSSM, hostPath);
883 AssertRC (vrc);
884 }
885
886 return;
887}
888
889/**
890 * Callback handler to load various console data from the state file.
891 * When \a u32Version is 0, this method is called from #loadDataFromSavedState,
892 * otherwise it is called when the VM is being restored from the saved state.
893 *
894 * @param pvUser pointer to Console
895 * @param u32Version Console unit version.
896 * When not 0, should match sSSMConsoleVer.
897 *
898 * @note Locks the Console object for writing.
899 */
900//static
901DECLCALLBACK(int)
902Console::loadStateFileExec (PSSMHANDLE pSSM, void *pvUser, uint32_t u32Version)
903{
904 LogFlowFunc (("\n"));
905
906 if (u32Version != 0 && u32Version != sSSMConsoleVer)
907 return VERR_VERSION_MISMATCH;
908
909 if (u32Version != 0)
910 {
911 /* currently, nothing to do when we've been called from VMR3Load */
912 return VINF_SUCCESS;
913 }
914
915 Console *that = static_cast <Console *> (pvUser);
916 AssertReturn (that, VERR_INVALID_PARAMETER);
917
918 AutoCaller autoCaller (that);
919 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
920
921 AutoLock alock (that);
922
923 AssertReturn (that->mSharedFolders.size() == 0, VERR_INTERNAL_ERROR);
924
925 uint32_t size = 0;
926 int vrc = SSMR3GetU32 (pSSM, &size);
927 AssertRCReturn (vrc, vrc);
928
929 for (uint32_t i = 0; i < size; ++ i)
930 {
931 Bstr name;
932 Bstr hostPath;
933
934 uint32_t szBuf = 0;
935 char *buf = NULL;
936
937 vrc = SSMR3GetU32 (pSSM, &szBuf);
938 AssertRCReturn (vrc, vrc);
939 buf = new char [szBuf];
940 vrc = SSMR3GetStrZ (pSSM, buf, szBuf);
941 AssertRC (vrc);
942 name = buf;
943 delete[] buf;
944
945 vrc = SSMR3GetU32 (pSSM, &szBuf);
946 AssertRCReturn (vrc, vrc);
947 buf = new char [szBuf];
948 vrc = SSMR3GetStrZ (pSSM, buf, szBuf);
949 AssertRC (vrc);
950 hostPath = buf;
951 delete[] buf;
952
953 ComObjPtr <SharedFolder> sharedFolder;
954 sharedFolder.createObject();
955 HRESULT rc = sharedFolder->init (that, name, hostPath);
956 AssertComRCReturn (rc, VERR_INTERNAL_ERROR);
957
958 that->mSharedFolders.insert (std::make_pair (name, sharedFolder));
959 }
960
961 return VINF_SUCCESS;
962}
963
964// IConsole properties
965/////////////////////////////////////////////////////////////////////////////
966
967STDMETHODIMP Console::COMGETTER(Machine) (IMachine **aMachine)
968{
969 if (!aMachine)
970 return E_POINTER;
971
972 AutoCaller autoCaller (this);
973 CheckComRCReturnRC (autoCaller.rc());
974
975 /* mMachine is constant during life time, no need to lock */
976 mMachine.queryInterfaceTo (aMachine);
977
978 return S_OK;
979}
980
981STDMETHODIMP Console::COMGETTER(State) (MachineState_T *aMachineState)
982{
983 if (!aMachineState)
984 return E_POINTER;
985
986 AutoCaller autoCaller (this);
987 CheckComRCReturnRC (autoCaller.rc());
988
989 AutoReaderLock alock (this);
990
991 /* we return our local state (since it's always the same as on the server) */
992 *aMachineState = mMachineState;
993
994 return S_OK;
995}
996
997STDMETHODIMP Console::COMGETTER(Guest) (IGuest **aGuest)
998{
999 if (!aGuest)
1000 return E_POINTER;
1001
1002 AutoCaller autoCaller (this);
1003 CheckComRCReturnRC (autoCaller.rc());
1004
1005 /* mGuest is constant during life time, no need to lock */
1006 mGuest.queryInterfaceTo (aGuest);
1007
1008 return S_OK;
1009}
1010
1011STDMETHODIMP Console::COMGETTER(Keyboard) (IKeyboard **aKeyboard)
1012{
1013 if (!aKeyboard)
1014 return E_POINTER;
1015
1016 AutoCaller autoCaller (this);
1017 CheckComRCReturnRC (autoCaller.rc());
1018
1019 /* mKeyboard is constant during life time, no need to lock */
1020 mKeyboard.queryInterfaceTo (aKeyboard);
1021
1022 return S_OK;
1023}
1024
1025STDMETHODIMP Console::COMGETTER(Mouse) (IMouse **aMouse)
1026{
1027 if (!aMouse)
1028 return E_POINTER;
1029
1030 AutoCaller autoCaller (this);
1031 CheckComRCReturnRC (autoCaller.rc());
1032
1033 /* mMouse is constant during life time, no need to lock */
1034 mMouse.queryInterfaceTo (aMouse);
1035
1036 return S_OK;
1037}
1038
1039STDMETHODIMP Console::COMGETTER(Display) (IDisplay **aDisplay)
1040{
1041 if (!aDisplay)
1042 return E_POINTER;
1043
1044 AutoCaller autoCaller (this);
1045 CheckComRCReturnRC (autoCaller.rc());
1046
1047 /* mDisplay is constant during life time, no need to lock */
1048 mDisplay.queryInterfaceTo (aDisplay);
1049
1050 return S_OK;
1051}
1052
1053STDMETHODIMP Console::COMGETTER(Debugger) (IMachineDebugger **aDebugger)
1054{
1055 if (!aDebugger)
1056 return E_POINTER;
1057
1058 AutoCaller autoCaller (this);
1059 CheckComRCReturnRC (autoCaller.rc());
1060
1061 /* we need a write lock because of the lazy mDebugger initialization*/
1062 AutoLock alock (this);
1063
1064 /* check if we have to create the debugger object */
1065 if (!mDebugger)
1066 {
1067 unconst (mDebugger).createObject();
1068 mDebugger->init (this);
1069 }
1070
1071 mDebugger.queryInterfaceTo (aDebugger);
1072
1073 return S_OK;
1074}
1075
1076STDMETHODIMP Console::COMGETTER(USBDevices) (IUSBDeviceCollection **aUSBDevices)
1077{
1078 if (!aUSBDevices)
1079 return E_POINTER;
1080
1081 AutoCaller autoCaller (this);
1082 CheckComRCReturnRC (autoCaller.rc());
1083
1084 AutoReaderLock alock (this);
1085
1086 ComObjPtr <OUSBDeviceCollection> collection;
1087 collection.createObject();
1088 collection->init (mUSBDevices);
1089 collection.queryInterfaceTo (aUSBDevices);
1090
1091 return S_OK;
1092}
1093
1094STDMETHODIMP Console::COMGETTER(RemoteUSBDevices) (IHostUSBDeviceCollection **aRemoteUSBDevices)
1095{
1096 if (!aRemoteUSBDevices)
1097 return E_POINTER;
1098
1099 AutoCaller autoCaller (this);
1100 CheckComRCReturnRC (autoCaller.rc());
1101
1102 AutoReaderLock alock (this);
1103
1104 ComObjPtr <RemoteUSBDeviceCollection> collection;
1105 collection.createObject();
1106 collection->init (mRemoteUSBDevices);
1107 collection.queryInterfaceTo (aRemoteUSBDevices);
1108
1109 return S_OK;
1110}
1111
1112STDMETHODIMP Console::COMGETTER(RemoteDisplayInfo) (IRemoteDisplayInfo **aRemoteDisplayInfo)
1113{
1114 if (!aRemoteDisplayInfo)
1115 return E_POINTER;
1116
1117 AutoCaller autoCaller (this);
1118 CheckComRCReturnRC (autoCaller.rc());
1119
1120 /* mDisplay is constant during life time, no need to lock */
1121 mRemoteDisplayInfo.queryInterfaceTo (aRemoteDisplayInfo);
1122
1123 return S_OK;
1124}
1125
1126STDMETHODIMP
1127Console::COMGETTER(SharedFolders) (ISharedFolderCollection **aSharedFolders)
1128{
1129 if (!aSharedFolders)
1130 return E_POINTER;
1131
1132 AutoCaller autoCaller (this);
1133 CheckComRCReturnRC (autoCaller.rc());
1134
1135 /* loadDataFromSavedState() needs a write lock */
1136 AutoLock alock (this);
1137
1138 /* Read console data stored in the saved state file (if not yet done) */
1139 HRESULT rc = loadDataFromSavedState();
1140 CheckComRCReturnRC (rc);
1141
1142 ComObjPtr <SharedFolderCollection> coll;
1143 coll.createObject();
1144 coll->init (mSharedFolders);
1145 coll.queryInterfaceTo (aSharedFolders);
1146
1147 return S_OK;
1148}
1149
1150// IConsole methods
1151/////////////////////////////////////////////////////////////////////////////
1152
1153STDMETHODIMP Console::PowerUp (IProgress **aProgress)
1154{
1155 LogFlowThisFuncEnter();
1156 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1157
1158 AutoCaller autoCaller (this);
1159 CheckComRCReturnRC (autoCaller.rc());
1160
1161 AutoLock alock (this);
1162
1163 if (mMachineState >= MachineState_Running)
1164 return setError(E_FAIL, tr ("Cannot power up the machine as it is "
1165 "already running (machine state: %d)"),
1166 mMachineState);
1167
1168 /*
1169 * First check whether all disks are accessible. This is not a 100%
1170 * bulletproof approach (race condition, it might become inaccessible
1171 * right after the check) but it's convenient as it will cover 99.9%
1172 * of the cases and here, we're able to provide meaningful error
1173 * information.
1174 */
1175 ComPtr<IHardDiskAttachmentCollection> coll;
1176 mMachine->COMGETTER(HardDiskAttachments)(coll.asOutParam());
1177 ComPtr<IHardDiskAttachmentEnumerator> enumerator;
1178 coll->Enumerate(enumerator.asOutParam());
1179 BOOL fHasMore;
1180 while (SUCCEEDED(enumerator->HasMore(&fHasMore)) && fHasMore)
1181 {
1182 ComPtr<IHardDiskAttachment> attach;
1183 enumerator->GetNext(attach.asOutParam());
1184 ComPtr<IHardDisk> hdd;
1185 attach->COMGETTER(HardDisk)(hdd.asOutParam());
1186 Assert(hdd);
1187 BOOL fAccessible;
1188 HRESULT rc = hdd->COMGETTER(AllAccessible)(&fAccessible);
1189 CheckComRCReturnRC (rc);
1190 if (!fAccessible)
1191 {
1192 Bstr loc;
1193 hdd->COMGETTER(Location) (loc.asOutParam());
1194 Bstr errMsg;
1195 hdd->COMGETTER(LastAccessError) (errMsg.asOutParam());
1196 return setError (E_FAIL,
1197 tr ("VM cannot start because the hard disk '%ls' is not accessible "
1198 "(%ls)"),
1199 loc.raw(), errMsg.raw());
1200 }
1201 }
1202
1203 /* now perform the same check if a ISO is mounted */
1204 ComPtr<IDVDDrive> dvdDrive;
1205 mMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam());
1206 ComPtr<IDVDImage> dvdImage;
1207 dvdDrive->GetImage(dvdImage.asOutParam());
1208 if (dvdImage)
1209 {
1210 BOOL fAccessible;
1211 HRESULT rc = dvdImage->COMGETTER(Accessible)(&fAccessible);
1212 CheckComRCReturnRC (rc);
1213 if (!fAccessible)
1214 {
1215 Bstr filePath;
1216 dvdImage->COMGETTER(FilePath)(filePath.asOutParam());
1217 /// @todo (r=dmik) grab the last access error once
1218 // IDVDImage::lastAccessError is there
1219 return setError (E_FAIL,
1220 tr ("The virtual machine could not be started because the DVD image '%ls' which is attached to it could not be found or could not be opened. Please detach the image and try again"),
1221 filePath.raw());
1222 }
1223 }
1224
1225 /* now perform the same check if a floppy is mounted */
1226 ComPtr<IFloppyDrive> floppyDrive;
1227 mMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam());
1228 ComPtr<IFloppyImage> floppyImage;
1229 floppyDrive->GetImage(floppyImage.asOutParam());
1230 if (floppyImage)
1231 {
1232 BOOL fAccessible;
1233 HRESULT rc = floppyImage->COMGETTER(Accessible)(&fAccessible);
1234 CheckComRCReturnRC (rc);
1235 if (!fAccessible)
1236 {
1237 Bstr filePath;
1238 floppyImage->COMGETTER(FilePath)(filePath.asOutParam());
1239 /// @todo (r=dmik) grab the last access error once
1240 // IDVDImage::lastAccessError is there
1241 return setError (E_FAIL,
1242 tr ("The virtual machine could not be started because the floppy image '%ls' which is attached to it could not be found or could not be opened. Please detach the image and try again"),
1243 filePath.raw());
1244 }
1245 }
1246
1247 /* now the network cards will undergo a quick consistency check */
1248 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
1249 {
1250 ComPtr<INetworkAdapter> adapter;
1251 mMachine->GetNetworkAdapter (slot, adapter.asOutParam());
1252 BOOL enabled = FALSE;
1253 adapter->COMGETTER(Enabled) (&enabled);
1254 if (!enabled)
1255 continue;
1256
1257 NetworkAttachmentType_T netattach;
1258 adapter->COMGETTER(AttachmentType)(&netattach);
1259 switch (netattach)
1260 {
1261 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
1262 {
1263#ifdef RT_OS_WINDOWS
1264 /* a valid host interface must have been set */
1265 Bstr hostif;
1266 adapter->COMGETTER(HostInterface)(hostif.asOutParam());
1267 if (!hostif)
1268 {
1269 return setError (E_FAIL,
1270 tr ("VM cannot start because host interface networking "
1271 "requires a host interface name to be set"));
1272 }
1273 ComPtr<IVirtualBox> virtualBox;
1274 mMachine->COMGETTER(Parent)(virtualBox.asOutParam());
1275 ComPtr<IHost> host;
1276 virtualBox->COMGETTER(Host)(host.asOutParam());
1277 ComPtr<IHostNetworkInterfaceCollection> coll;
1278 host->COMGETTER(NetworkInterfaces)(coll.asOutParam());
1279 ComPtr<IHostNetworkInterface> hostInterface;
1280 if (!SUCCEEDED(coll->FindByName(hostif, hostInterface.asOutParam())))
1281 {
1282 return setError (E_FAIL,
1283 tr ("VM cannot start because the host interface '%ls' "
1284 "does not exist"),
1285 hostif.raw());
1286 }
1287#endif /* RT_OS_WINDOWS */
1288 break;
1289 }
1290 default:
1291 break;
1292 }
1293 }
1294
1295 /* Read console data stored in the saved state file (if not yet done) */
1296 {
1297 HRESULT rc = loadDataFromSavedState();
1298 CheckComRCReturnRC (rc);
1299 }
1300
1301 /* Check all types of shared folders and compose a single list */
1302 SharedFolderDataMap sharedFolders;
1303 {
1304 /* first, insert global folders */
1305 for (SharedFolderDataMap::const_iterator it = mGlobalSharedFolders.begin();
1306 it != mGlobalSharedFolders.end(); ++ it)
1307 sharedFolders [it->first] = it->second;
1308
1309 /* second, insert machine folders */
1310 for (SharedFolderDataMap::const_iterator it = mMachineSharedFolders.begin();
1311 it != mMachineSharedFolders.end(); ++ it)
1312 sharedFolders [it->first] = it->second;
1313
1314 /* third, insert console folders */
1315 for (SharedFolderMap::const_iterator it = mSharedFolders.begin();
1316 it != mSharedFolders.end(); ++ it)
1317 sharedFolders [it->first] = it->second->hostPath();
1318 }
1319
1320 Bstr savedStateFile;
1321
1322 /*
1323 * Saved VMs will have to prove that their saved states are kosher.
1324 */
1325 if (mMachineState == MachineState_Saved)
1326 {
1327 HRESULT rc = mMachine->COMGETTER(StateFilePath) (savedStateFile.asOutParam());
1328 CheckComRCReturnRC (rc);
1329 ComAssertRet (!!savedStateFile, E_FAIL);
1330 int vrc = SSMR3ValidateFile (Utf8Str (savedStateFile));
1331 if (VBOX_FAILURE (vrc))
1332 return setError (E_FAIL,
1333 tr ("VM cannot start because the saved state file '%ls' is invalid (%Vrc). "
1334 "Discard the saved state prior to starting the VM"),
1335 savedStateFile.raw(), vrc);
1336 }
1337
1338 /* create an IProgress object to track progress of this operation */
1339 ComObjPtr <Progress> progress;
1340 progress.createObject();
1341 Bstr progressDesc;
1342 if (mMachineState == MachineState_Saved)
1343 progressDesc = tr ("Restoring the virtual machine");
1344 else
1345 progressDesc = tr ("Starting the virtual machine");
1346 progress->init (static_cast <IConsole *> (this),
1347 progressDesc, FALSE /* aCancelable */);
1348
1349 /* pass reference to caller if requested */
1350 if (aProgress)
1351 progress.queryInterfaceTo (aProgress);
1352
1353 /* setup task object and thread to carry out the operation asynchronously */
1354 std::auto_ptr <VMPowerUpTask> task (new VMPowerUpTask (this, progress));
1355 ComAssertComRCRetRC (task->rc());
1356
1357 task->mSetVMErrorCallback = setVMErrorCallback;
1358 task->mConfigConstructor = configConstructor;
1359 task->mSharedFolders = sharedFolders;
1360 if (mMachineState == MachineState_Saved)
1361 task->mSavedStateFile = savedStateFile;
1362
1363 int vrc = RTThreadCreate (NULL, Console::powerUpThread, (void *) task.get(),
1364 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMPowerUp");
1365
1366 ComAssertMsgRCRet (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc),
1367 E_FAIL);
1368
1369 /* task is now owned by powerUpThread(), so release it */
1370 task.release();
1371
1372 if (mMachineState == MachineState_Saved)
1373 setMachineState (MachineState_Restoring);
1374 else
1375 setMachineState (MachineState_Starting);
1376
1377 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1378 LogFlowThisFuncLeave();
1379 return S_OK;
1380}
1381
1382STDMETHODIMP Console::PowerDown()
1383{
1384 LogFlowThisFuncEnter();
1385 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1386
1387 AutoCaller autoCaller (this);
1388 CheckComRCReturnRC (autoCaller.rc());
1389
1390 AutoLock alock (this);
1391
1392 if (mMachineState != MachineState_Running &&
1393 mMachineState != MachineState_Paused &&
1394 mMachineState != MachineState_Stuck)
1395 {
1396 /* extra nice error message for a common case */
1397 if (mMachineState == MachineState_Saved)
1398 return setError(E_FAIL, tr ("Cannot power off a saved machine"));
1399 else
1400 return setError(E_FAIL, tr ("Cannot power off the machine as it is "
1401 "not running or paused (machine state: %d)"),
1402 mMachineState);
1403 }
1404
1405 LogFlowThisFunc (("Sending SHUTDOWN request...\n"));
1406
1407 HRESULT rc = powerDown();
1408
1409 LogFlowThisFunc (("mMachineState=%d, rc=%08X\n", mMachineState, rc));
1410 LogFlowThisFuncLeave();
1411 return rc;
1412}
1413
1414STDMETHODIMP Console::Reset()
1415{
1416 LogFlowThisFuncEnter();
1417 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1418
1419 AutoCaller autoCaller (this);
1420 CheckComRCReturnRC (autoCaller.rc());
1421
1422 AutoLock alock (this);
1423
1424 if (mMachineState != MachineState_Running)
1425 return setError(E_FAIL, tr ("Cannot reset the machine as it is "
1426 "not running (machine state: %d)"),
1427 mMachineState);
1428
1429 /* protect mpVM */
1430 AutoVMCaller autoVMCaller (this);
1431 CheckComRCReturnRC (autoVMCaller.rc());
1432
1433 /* leave the lock before a VMR3* call (EMT will call us back)! */
1434 alock.leave();
1435
1436 int vrc = VMR3Reset (mpVM);
1437
1438 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1439 setError (E_FAIL, tr ("Could not reset the machine (%Vrc)"), vrc);
1440
1441 LogFlowThisFunc (("mMachineState=%d, rc=%08X\n", mMachineState, rc));
1442 LogFlowThisFuncLeave();
1443 return rc;
1444}
1445
1446STDMETHODIMP Console::Pause()
1447{
1448 LogFlowThisFuncEnter();
1449
1450 AutoCaller autoCaller (this);
1451 CheckComRCReturnRC (autoCaller.rc());
1452
1453 AutoLock alock (this);
1454
1455 if (mMachineState != MachineState_Running)
1456 return setError (E_FAIL, tr ("Cannot pause the machine as it is "
1457 "not running (machine state: %d)"),
1458 mMachineState);
1459
1460 /* protect mpVM */
1461 AutoVMCaller autoVMCaller (this);
1462 CheckComRCReturnRC (autoVMCaller.rc());
1463
1464 LogFlowThisFunc (("Sending PAUSE request...\n"));
1465
1466 /* leave the lock before a VMR3* call (EMT will call us back)! */
1467 alock.leave();
1468
1469 int vrc = VMR3Suspend (mpVM);
1470
1471 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1472 setError (E_FAIL,
1473 tr ("Could not suspend the machine execution (%Vrc)"), vrc);
1474
1475 LogFlowThisFunc (("rc=%08X\n", rc));
1476 LogFlowThisFuncLeave();
1477 return rc;
1478}
1479
1480STDMETHODIMP Console::Resume()
1481{
1482 LogFlowThisFuncEnter();
1483
1484 AutoCaller autoCaller (this);
1485 CheckComRCReturnRC (autoCaller.rc());
1486
1487 AutoLock alock (this);
1488
1489 if (mMachineState != MachineState_Paused)
1490 return setError (E_FAIL, tr ("Cannot resume the machine as it is "
1491 "not paused (machine state: %d)"),
1492 mMachineState);
1493
1494 /* protect mpVM */
1495 AutoVMCaller autoVMCaller (this);
1496 CheckComRCReturnRC (autoVMCaller.rc());
1497
1498 LogFlowThisFunc (("Sending RESUME request...\n"));
1499
1500 /* leave the lock before a VMR3* call (EMT will call us back)! */
1501 alock.leave();
1502
1503 int vrc = VMR3Resume (mpVM);
1504
1505 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1506 setError (E_FAIL,
1507 tr ("Could not resume the machine execution (%Vrc)"), vrc);
1508
1509 LogFlowThisFunc (("rc=%08X\n", rc));
1510 LogFlowThisFuncLeave();
1511 return rc;
1512}
1513
1514STDMETHODIMP Console::PowerButton()
1515{
1516 LogFlowThisFuncEnter();
1517
1518 AutoCaller autoCaller (this);
1519 CheckComRCReturnRC (autoCaller.rc());
1520
1521 AutoLock lock (this);
1522
1523 if (mMachineState != MachineState_Running)
1524 return setError (E_FAIL, tr ("Cannot power off the machine as it is "
1525 "not running (machine state: %d)"),
1526 mMachineState);
1527
1528 /* protect mpVM */
1529 AutoVMCaller autoVMCaller (this);
1530 CheckComRCReturnRC (autoVMCaller.rc());
1531
1532 PPDMIBASE pBase;
1533 int vrc = PDMR3QueryDeviceLun (mpVM, "acpi", 0, 0, &pBase);
1534 if (VBOX_SUCCESS (vrc))
1535 {
1536 Assert (pBase);
1537 PPDMIACPIPORT pPort =
1538 (PPDMIACPIPORT) pBase->pfnQueryInterface(pBase, PDMINTERFACE_ACPI_PORT);
1539 vrc = pPort ? pPort->pfnPowerButtonPress(pPort) : VERR_INVALID_POINTER;
1540 }
1541
1542 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1543 setError (E_FAIL,
1544 tr ("Controlled power off failed (%Vrc)"), vrc);
1545
1546 LogFlowThisFunc (("rc=%08X\n", rc));
1547 LogFlowThisFuncLeave();
1548 return rc;
1549}
1550
1551STDMETHODIMP Console::SleepButton()
1552{
1553 LogFlowThisFuncEnter();
1554
1555 AutoCaller autoCaller (this);
1556 CheckComRCReturnRC (autoCaller.rc());
1557
1558 AutoLock lock (this);
1559
1560 if (mMachineState != MachineState_Running)
1561 return setError (E_FAIL, tr ("Cannot send the sleep button event as it is "
1562 "not running (machine state: %d)"),
1563 mMachineState);
1564
1565 /* protect mpVM */
1566 AutoVMCaller autoVMCaller (this);
1567 CheckComRCReturnRC (autoVMCaller.rc());
1568
1569 PPDMIBASE pBase;
1570 int vrc = PDMR3QueryDeviceLun (mpVM, "acpi", 0, 0, &pBase);
1571 if (VBOX_SUCCESS (vrc))
1572 {
1573 Assert (pBase);
1574 PPDMIACPIPORT pPort =
1575 (PPDMIACPIPORT) pBase->pfnQueryInterface(pBase, PDMINTERFACE_ACPI_PORT);
1576 vrc = pPort ? pPort->pfnSleepButtonPress(pPort) : VERR_INVALID_POINTER;
1577 }
1578
1579 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1580 setError (E_FAIL,
1581 tr ("Sending sleep button event failed (%Vrc)"), vrc);
1582
1583 LogFlowThisFunc (("rc=%08X\n", rc));
1584 LogFlowThisFuncLeave();
1585 return rc;
1586}
1587
1588STDMETHODIMP Console::SaveState (IProgress **aProgress)
1589{
1590 LogFlowThisFuncEnter();
1591 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1592
1593 if (!aProgress)
1594 return E_POINTER;
1595
1596 AutoCaller autoCaller (this);
1597 CheckComRCReturnRC (autoCaller.rc());
1598
1599 AutoLock alock (this);
1600
1601 if (mMachineState != MachineState_Running &&
1602 mMachineState != MachineState_Paused)
1603 {
1604 return setError (E_FAIL,
1605 tr ("Cannot save the execution state as the machine "
1606 "is not running (machine state: %d)"), mMachineState);
1607 }
1608
1609 /* memorize the current machine state */
1610 MachineState_T lastMachineState = mMachineState;
1611
1612 if (mMachineState == MachineState_Running)
1613 {
1614 HRESULT rc = Pause();
1615 CheckComRCReturnRC (rc);
1616 }
1617
1618 HRESULT rc = S_OK;
1619
1620 /* create a progress object to track operation completion */
1621 ComObjPtr <Progress> progress;
1622 progress.createObject();
1623 progress->init (static_cast <IConsole *> (this),
1624 Bstr (tr ("Saving the execution state of the virtual machine")),
1625 FALSE /* aCancelable */);
1626
1627 bool beganSavingState = false;
1628 bool taskCreationFailed = false;
1629
1630 do
1631 {
1632 /* create a task object early to ensure mpVM protection is successful */
1633 std::auto_ptr <VMSaveTask> task (new VMSaveTask (this, progress));
1634 rc = task->rc();
1635 /*
1636 * If we fail here it means a PowerDown() call happened on another
1637 * thread while we were doing Pause() (which leaves the Console lock).
1638 * We assign PowerDown() a higher precendence than SaveState(),
1639 * therefore just return the error to the caller.
1640 */
1641 if (FAILED (rc))
1642 {
1643 taskCreationFailed = true;
1644 break;
1645 }
1646
1647 Bstr stateFilePath;
1648
1649 /*
1650 * request a saved state file path from the server
1651 * (this will set the machine state to Saving on the server to block
1652 * others from accessing this machine)
1653 */
1654 rc = mControl->BeginSavingState (progress, stateFilePath.asOutParam());
1655 CheckComRCBreakRC (rc);
1656
1657 beganSavingState = true;
1658
1659 /* sync the state with the server */
1660 setMachineStateLocally (MachineState_Saving);
1661
1662 /* ensure the directory for the saved state file exists */
1663 {
1664 Utf8Str dir = stateFilePath;
1665 RTPathStripFilename (dir.mutableRaw());
1666 if (!RTDirExists (dir))
1667 {
1668 int vrc = RTDirCreateFullPath (dir, 0777);
1669 if (VBOX_FAILURE (vrc))
1670 {
1671 rc = setError (E_FAIL,
1672 tr ("Could not create a directory '%s' to save the state to (%Vrc)"),
1673 dir.raw(), vrc);
1674 break;
1675 }
1676 }
1677 }
1678
1679 /* setup task object and thread to carry out the operation asynchronously */
1680 task->mIsSnapshot = false;
1681 task->mSavedStateFile = stateFilePath;
1682 /* set the state the operation thread will restore when it is finished */
1683 task->mLastMachineState = lastMachineState;
1684
1685 /* create a thread to wait until the VM state is saved */
1686 int vrc = RTThreadCreate (NULL, Console::saveStateThread, (void *) task.get(),
1687 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
1688
1689 ComAssertMsgRCBreak (vrc, ("Could not create VMSave thread (%Vrc)\n", vrc),
1690 rc = E_FAIL);
1691
1692 /* task is now owned by saveStateThread(), so release it */
1693 task.release();
1694
1695 /* return the progress to the caller */
1696 progress.queryInterfaceTo (aProgress);
1697 }
1698 while (0);
1699
1700 if (FAILED (rc) && !taskCreationFailed)
1701 {
1702 /* preserve existing error info */
1703 ErrorInfoKeeper eik;
1704
1705 if (beganSavingState)
1706 {
1707 /*
1708 * cancel the requested save state procedure.
1709 * This will reset the machine state to the state it had right
1710 * before calling mControl->BeginSavingState().
1711 */
1712 mControl->EndSavingState (FALSE);
1713 }
1714
1715 if (lastMachineState == MachineState_Running)
1716 {
1717 /* restore the paused state if appropriate */
1718 setMachineStateLocally (MachineState_Paused);
1719 /* restore the running state if appropriate */
1720 Resume();
1721 }
1722 else
1723 setMachineStateLocally (lastMachineState);
1724 }
1725
1726 LogFlowThisFunc (("rc=%08X\n", rc));
1727 LogFlowThisFuncLeave();
1728 return rc;
1729}
1730
1731STDMETHODIMP Console::AdoptSavedState (INPTR BSTR aSavedStateFile)
1732{
1733 if (!aSavedStateFile)
1734 return E_INVALIDARG;
1735
1736 AutoCaller autoCaller (this);
1737 CheckComRCReturnRC (autoCaller.rc());
1738
1739 AutoLock alock (this);
1740
1741 if (mMachineState != MachineState_PoweredOff &&
1742 mMachineState != MachineState_Aborted)
1743 return setError (E_FAIL,
1744 tr ("Cannot adopt the saved machine state as the machine is "
1745 "not in Powered Off or Aborted state (machine state: %d)"),
1746 mMachineState);
1747
1748 return mControl->AdoptSavedState (aSavedStateFile);
1749}
1750
1751STDMETHODIMP Console::DiscardSavedState()
1752{
1753 AutoCaller autoCaller (this);
1754 CheckComRCReturnRC (autoCaller.rc());
1755
1756 AutoLock alock (this);
1757
1758 if (mMachineState != MachineState_Saved)
1759 return setError (E_FAIL,
1760 tr ("Cannot discard the machine state as the machine is "
1761 "not in the saved state (machine state: %d)"),
1762 mMachineState);
1763
1764 /*
1765 * Saved -> PoweredOff transition will be detected in the SessionMachine
1766 * and properly handled.
1767 */
1768 setMachineState (MachineState_PoweredOff);
1769
1770 return S_OK;
1771}
1772
1773/** read the value of a LEd. */
1774inline uint32_t readAndClearLed(PPDMLED pLed)
1775{
1776 if (!pLed)
1777 return 0;
1778 uint32_t u32 = pLed->Actual.u32 | pLed->Asserted.u32;
1779 pLed->Asserted.u32 = 0;
1780 return u32;
1781}
1782
1783STDMETHODIMP Console::GetDeviceActivity (DeviceType_T aDeviceType,
1784 DeviceActivity_T *aDeviceActivity)
1785{
1786 if (!aDeviceActivity)
1787 return E_INVALIDARG;
1788
1789 AutoCaller autoCaller (this);
1790 CheckComRCReturnRC (autoCaller.rc());
1791
1792 /*
1793 * Note: we don't lock the console object here because
1794 * readAndClearLed() should be thread safe.
1795 */
1796
1797 /* Get LED array to read */
1798 PDMLEDCORE SumLed = {0};
1799 switch (aDeviceType)
1800 {
1801 case DeviceType_FloppyDevice:
1802 {
1803 for (unsigned i = 0; i < ELEMENTS(mapFDLeds); i++)
1804 SumLed.u32 |= readAndClearLed(mapFDLeds[i]);
1805 break;
1806 }
1807
1808 case DeviceType_DVDDevice:
1809 {
1810 SumLed.u32 |= readAndClearLed(mapIDELeds[2]);
1811 break;
1812 }
1813
1814 case DeviceType_HardDiskDevice:
1815 {
1816 SumLed.u32 |= readAndClearLed(mapIDELeds[0]);
1817 SumLed.u32 |= readAndClearLed(mapIDELeds[1]);
1818 SumLed.u32 |= readAndClearLed(mapIDELeds[3]);
1819 break;
1820 }
1821
1822 case DeviceType_NetworkDevice:
1823 {
1824 for (unsigned i = 0; i < ELEMENTS(mapNetworkLeds); i++)
1825 SumLed.u32 |= readAndClearLed(mapNetworkLeds[i]);
1826 break;
1827 }
1828
1829 case DeviceType_USBDevice:
1830 {
1831 SumLed.u32 |= readAndClearLed(mapUSBLed);
1832 break;
1833 }
1834
1835 case DeviceType_SharedFolderDevice:
1836 {
1837 SumLed.u32 |= readAndClearLed(mapSharedFolderLed);
1838 break;
1839 }
1840
1841 default:
1842 return setError (E_INVALIDARG,
1843 tr ("Invalid device type: %d"), aDeviceType);
1844 }
1845
1846 /* Compose the result */
1847 switch (SumLed.u32 & (PDMLED_READING | PDMLED_WRITING))
1848 {
1849 case 0:
1850 *aDeviceActivity = DeviceActivity_DeviceIdle;
1851 break;
1852 case PDMLED_READING:
1853 *aDeviceActivity = DeviceActivity_DeviceReading;
1854 break;
1855 case PDMLED_WRITING:
1856 case PDMLED_READING | PDMLED_WRITING:
1857 *aDeviceActivity = DeviceActivity_DeviceWriting;
1858 break;
1859 }
1860
1861 return S_OK;
1862}
1863
1864STDMETHODIMP Console::AttachUSBDevice (INPTR GUIDPARAM aId)
1865{
1866#ifdef VBOX_WITH_USB
1867 AutoCaller autoCaller (this);
1868 CheckComRCReturnRC (autoCaller.rc());
1869
1870 AutoLock alock (this);
1871
1872 /// @todo (r=dmik) is it legal to attach USB devices when the machine is
1873 // Paused, Starting, Saving, Stopping, etc? if not, we should make a
1874 // stricter check (mMachineState != MachineState_Running).
1875 //
1876 // I'm changing it to the semi-strict check for the time being. We'll
1877 // consider the below later.
1878 //
1879 /* bird: It is not permitted to attach or detach while the VM is saving,
1880 * is restoring or has stopped - definintly not.
1881 *
1882 * Attaching while starting, well, if you don't create any deadlock it
1883 * should work... Paused should work I guess, but we shouldn't push our
1884 * luck if we're pausing because an runtime error condition was raised
1885 * (which is one of the reasons there better be a separate state for that
1886 * in the VMM).
1887 */
1888 if (mMachineState != MachineState_Running &&
1889 mMachineState != MachineState_Paused)
1890 return setError (E_FAIL,
1891 tr ("Cannot attach a USB device to the machine which is not running"
1892 "(machine state: %d)"),
1893 mMachineState);
1894
1895 /* protect mpVM */
1896 AutoVMCaller autoVMCaller (this);
1897 CheckComRCReturnRC (autoVMCaller.rc());
1898
1899 /* Don't proceed unless we've found the usb controller. */
1900 PPDMIBASE pBase = NULL;
1901 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
1902 if (VBOX_FAILURE (vrc))
1903 return setError (E_FAIL,
1904 tr ("The virtual machine does not have a USB controller"));
1905
1906 /* leave the lock because the USB Proxy service may call us back
1907 * (via onUSBDeviceAttach()) */
1908 alock.leave();
1909
1910 /* Request the device capture */
1911 HRESULT rc = mControl->CaptureUSBDevice (aId);
1912 CheckComRCReturnRC (rc);
1913
1914 return rc;
1915
1916#else /* !VBOX_WITH_USB */
1917 return setError (E_FAIL,
1918 tr ("The virtual machine does not have a USB controller"));
1919#endif /* !VBOX_WITH_USB */
1920}
1921
1922STDMETHODIMP Console::DetachUSBDevice (INPTR GUIDPARAM aId, IUSBDevice **aDevice)
1923{
1924#ifdef VBOX_WITH_USB
1925 if (!aDevice)
1926 return E_POINTER;
1927
1928 AutoCaller autoCaller (this);
1929 CheckComRCReturnRC (autoCaller.rc());
1930
1931 AutoLock alock (this);
1932
1933 /* Find it. */
1934 ComObjPtr <OUSBDevice> device;
1935 USBDeviceList::iterator it = mUSBDevices.begin();
1936 while (it != mUSBDevices.end())
1937 {
1938 if ((*it)->id() == aId)
1939 {
1940 device = *it;
1941 break;
1942 }
1943 ++ it;
1944 }
1945
1946 if (!device)
1947 return setError (E_INVALIDARG,
1948 tr ("USB device with UUID {%Vuuid} is not attached to this machine"),
1949 Guid (aId).raw());
1950
1951# ifdef RT_OS_DARWIN
1952 /* Notify the USB Proxy that we're about to detach the device. Since
1953 * we don't dare do IPC when holding the console lock, so we'll have
1954 * to revalidate the device when we get back. */
1955 alock.leave();
1956 HRESULT rc2 = mControl->DetachUSBDevice (aId, false /* aDone */);
1957 if (FAILED (rc2))
1958 return rc2;
1959 alock.enter();
1960
1961 for (it = mUSBDevices.begin(); it != mUSBDevices.end(); ++ it)
1962 if ((*it)->id() == aId)
1963 break;
1964 if (it == mUSBDevices.end())
1965 return S_OK;
1966# endif
1967
1968 /* First, request VMM to detach the device */
1969 HRESULT rc = detachUSBDevice (it);
1970
1971 if (SUCCEEDED (rc))
1972 {
1973 /* leave the lock since we don't need it any more (note though that
1974 * the USB Proxy service must not call us back here) */
1975 alock.leave();
1976
1977 /* Request the device release. Even if it fails, the device will
1978 * remain as held by proxy, which is OK for us (the VM process). */
1979 rc = mControl->DetachUSBDevice (aId, true /* aDone */);
1980 }
1981
1982 return rc;
1983
1984
1985#else /* !VBOX_WITH_USB */
1986 return setError (E_INVALIDARG,
1987 tr ("USB device with UUID {%Vuuid} is not attached to this machine"),
1988 Guid (aId).raw());
1989#endif /* !VBOX_WITH_USB */
1990}
1991
1992STDMETHODIMP
1993Console::CreateSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath)
1994{
1995 if (!aName || !aHostPath)
1996 return E_INVALIDARG;
1997
1998 AutoCaller autoCaller (this);
1999 CheckComRCReturnRC (autoCaller.rc());
2000
2001 AutoLock alock (this);
2002
2003 /// @todo see @todo in AttachUSBDevice() about the Paused state
2004 if (mMachineState == MachineState_Saved)
2005 return setError (E_FAIL,
2006 tr ("Cannot create a transient shared folder on the "
2007 "machine in the saved state"));
2008 if (mMachineState > MachineState_Paused)
2009 return setError (E_FAIL,
2010 tr ("Cannot create a transient shared folder on the "
2011 "machine while it is changing the state (machine state: %d)"),
2012 mMachineState);
2013
2014 ComObjPtr <SharedFolder> sharedFolder;
2015 HRESULT rc = findSharedFolder (aName, sharedFolder, false /* aSetError */);
2016 if (SUCCEEDED (rc))
2017 return setError (E_FAIL,
2018 tr ("Shared folder named '%ls' already exists"), aName);
2019
2020 sharedFolder.createObject();
2021 rc = sharedFolder->init (this, aName, aHostPath);
2022 CheckComRCReturnRC (rc);
2023
2024 BOOL accessible = FALSE;
2025 rc = sharedFolder->COMGETTER(Accessible) (&accessible);
2026 CheckComRCReturnRC (rc);
2027
2028 if (!accessible)
2029 return setError (E_FAIL,
2030 tr ("Shared folder host path '%ls' is not accessible"), aHostPath);
2031
2032 /* protect mpVM (if not NULL) */
2033 AutoVMCallerQuietWeak autoVMCaller (this);
2034
2035 if (mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive())
2036 {
2037 /* If the VM is online and supports shared folders, share this folder
2038 * under the specified name. */
2039
2040 /* first, remove the machine or the global folder if there is any */
2041 SharedFolderDataMap::const_iterator it;
2042 if (findOtherSharedFolder (aName, it))
2043 {
2044 rc = removeSharedFolder (aName);
2045 CheckComRCReturnRC (rc);
2046 }
2047
2048 /* second, create the given folder */
2049 rc = createSharedFolder (aName, aHostPath);
2050 CheckComRCReturnRC (rc);
2051 }
2052
2053 mSharedFolders.insert (std::make_pair (aName, sharedFolder));
2054
2055 /* notify console callbacks after the folder is added to the list */
2056 {
2057 CallbackList::iterator it = mCallbacks.begin();
2058 while (it != mCallbacks.end())
2059 (*it++)->OnSharedFolderChange (Scope_SessionScope);
2060 }
2061
2062 return rc;
2063}
2064
2065STDMETHODIMP Console::RemoveSharedFolder (INPTR BSTR aName)
2066{
2067 if (!aName)
2068 return E_INVALIDARG;
2069
2070 AutoCaller autoCaller (this);
2071 CheckComRCReturnRC (autoCaller.rc());
2072
2073 AutoLock alock (this);
2074
2075 /// @todo see @todo in AttachUSBDevice() about the Paused state
2076 if (mMachineState == MachineState_Saved)
2077 return setError (E_FAIL,
2078 tr ("Cannot remove a transient shared folder from the "
2079 "machine in the saved state"));
2080 if (mMachineState > MachineState_Paused)
2081 return setError (E_FAIL,
2082 tr ("Cannot remove a transient shared folder from the "
2083 "machine while it is changing the state (machine state: %d)"),
2084 mMachineState);
2085
2086 ComObjPtr <SharedFolder> sharedFolder;
2087 HRESULT rc = findSharedFolder (aName, sharedFolder, true /* aSetError */);
2088 CheckComRCReturnRC (rc);
2089
2090 /* protect mpVM (if not NULL) */
2091 AutoVMCallerQuietWeak autoVMCaller (this);
2092
2093 if (mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive())
2094 {
2095 /* if the VM is online and supports shared folders, UNshare this
2096 * folder. */
2097
2098 /* first, remove the given folder */
2099 rc = removeSharedFolder (aName);
2100 CheckComRCReturnRC (rc);
2101
2102 /* first, remove the machine or the global folder if there is any */
2103 SharedFolderDataMap::const_iterator it;
2104 if (findOtherSharedFolder (aName, it))
2105 {
2106 rc = createSharedFolder (aName, it->second);
2107 /* don't check rc here because we need to remove the console
2108 * folder from the collection even on failure */
2109 }
2110 }
2111
2112 mSharedFolders.erase (aName);
2113
2114 /* notify console callbacks after the folder is removed to the list */
2115 {
2116 CallbackList::iterator it = mCallbacks.begin();
2117 while (it != mCallbacks.end())
2118 (*it++)->OnSharedFolderChange (Scope_SessionScope);
2119 }
2120
2121 return rc;
2122}
2123
2124STDMETHODIMP Console::TakeSnapshot (INPTR BSTR aName, INPTR BSTR aDescription,
2125 IProgress **aProgress)
2126{
2127 LogFlowThisFuncEnter();
2128 LogFlowThisFunc (("aName='%ls' mMachineState=%08X\n", aName, mMachineState));
2129
2130 if (!aName)
2131 return E_INVALIDARG;
2132 if (!aProgress)
2133 return E_POINTER;
2134
2135 AutoCaller autoCaller (this);
2136 CheckComRCReturnRC (autoCaller.rc());
2137
2138 AutoLock alock (this);
2139
2140 if (mMachineState > MachineState_Paused)
2141 {
2142 return setError (E_FAIL,
2143 tr ("Cannot take a snapshot of the machine "
2144 "while it is changing the state (machine state: %d)"),
2145 mMachineState);
2146 }
2147
2148 /* memorize the current machine state */
2149 MachineState_T lastMachineState = mMachineState;
2150
2151 if (mMachineState == MachineState_Running)
2152 {
2153 HRESULT rc = Pause();
2154 CheckComRCReturnRC (rc);
2155 }
2156
2157 HRESULT rc = S_OK;
2158
2159 bool takingSnapshotOnline = mMachineState == MachineState_Paused;
2160
2161 /*
2162 * create a descriptionless VM-side progress object
2163 * (only when creating a snapshot online)
2164 */
2165 ComObjPtr <Progress> saveProgress;
2166 if (takingSnapshotOnline)
2167 {
2168 saveProgress.createObject();
2169 rc = saveProgress->init (FALSE, 1, Bstr (tr ("Saving the execution state")));
2170 AssertComRCReturn (rc, rc);
2171 }
2172
2173 bool beganTakingSnapshot = false;
2174 bool taskCreationFailed = false;
2175
2176 do
2177 {
2178 /* create a task object early to ensure mpVM protection is successful */
2179 std::auto_ptr <VMSaveTask> task;
2180 if (takingSnapshotOnline)
2181 {
2182 task.reset (new VMSaveTask (this, saveProgress));
2183 rc = task->rc();
2184 /*
2185 * If we fail here it means a PowerDown() call happened on another
2186 * thread while we were doing Pause() (which leaves the Console lock).
2187 * We assign PowerDown() a higher precendence than TakeSnapshot(),
2188 * therefore just return the error to the caller.
2189 */
2190 if (FAILED (rc))
2191 {
2192 taskCreationFailed = true;
2193 break;
2194 }
2195 }
2196
2197 Bstr stateFilePath;
2198 ComPtr <IProgress> serverProgress;
2199
2200 /*
2201 * request taking a new snapshot object on the server
2202 * (this will set the machine state to Saving on the server to block
2203 * others from accessing this machine)
2204 */
2205 rc = mControl->BeginTakingSnapshot (this, aName, aDescription,
2206 saveProgress, stateFilePath.asOutParam(),
2207 serverProgress.asOutParam());
2208 if (FAILED (rc))
2209 break;
2210
2211 /*
2212 * state file is non-null only when the VM is paused
2213 * (i.e. createing a snapshot online)
2214 */
2215 ComAssertBreak (
2216 (!stateFilePath.isNull() && takingSnapshotOnline) ||
2217 (stateFilePath.isNull() && !takingSnapshotOnline),
2218 rc = E_FAIL);
2219
2220 beganTakingSnapshot = true;
2221
2222 /* sync the state with the server */
2223 setMachineStateLocally (MachineState_Saving);
2224
2225 /*
2226 * create a combined VM-side progress object and start the save task
2227 * (only when creating a snapshot online)
2228 */
2229 ComObjPtr <CombinedProgress> combinedProgress;
2230 if (takingSnapshotOnline)
2231 {
2232 combinedProgress.createObject();
2233 rc = combinedProgress->init (static_cast <IConsole *> (this),
2234 Bstr (tr ("Taking snapshot of virtual machine")),
2235 serverProgress, saveProgress);
2236 AssertComRCBreakRC (rc);
2237
2238 /* setup task object and thread to carry out the operation asynchronously */
2239 task->mIsSnapshot = true;
2240 task->mSavedStateFile = stateFilePath;
2241 task->mServerProgress = serverProgress;
2242 /* set the state the operation thread will restore when it is finished */
2243 task->mLastMachineState = lastMachineState;
2244
2245 /* create a thread to wait until the VM state is saved */
2246 int vrc = RTThreadCreate (NULL, Console::saveStateThread, (void *) task.get(),
2247 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMTakeSnap");
2248
2249 ComAssertMsgRCBreak (vrc, ("Could not create VMTakeSnap thread (%Vrc)\n", vrc),
2250 rc = E_FAIL);
2251
2252 /* task is now owned by saveStateThread(), so release it */
2253 task.release();
2254 }
2255
2256 if (SUCCEEDED (rc))
2257 {
2258 /* return the correct progress to the caller */
2259 if (combinedProgress)
2260 combinedProgress.queryInterfaceTo (aProgress);
2261 else
2262 serverProgress.queryInterfaceTo (aProgress);
2263 }
2264 }
2265 while (0);
2266
2267 if (FAILED (rc) && !taskCreationFailed)
2268 {
2269 /* preserve existing error info */
2270 ErrorInfoKeeper eik;
2271
2272 if (beganTakingSnapshot && takingSnapshotOnline)
2273 {
2274 /*
2275 * cancel the requested snapshot (only when creating a snapshot
2276 * online, otherwise the server will cancel the snapshot itself).
2277 * This will reset the machine state to the state it had right
2278 * before calling mControl->BeginTakingSnapshot().
2279 */
2280 mControl->EndTakingSnapshot (FALSE);
2281 }
2282
2283 if (lastMachineState == MachineState_Running)
2284 {
2285 /* restore the paused state if appropriate */
2286 setMachineStateLocally (MachineState_Paused);
2287 /* restore the running state if appropriate */
2288 Resume();
2289 }
2290 else
2291 setMachineStateLocally (lastMachineState);
2292 }
2293
2294 LogFlowThisFunc (("rc=%08X\n", rc));
2295 LogFlowThisFuncLeave();
2296 return rc;
2297}
2298
2299STDMETHODIMP Console::DiscardSnapshot (INPTR GUIDPARAM aId, IProgress **aProgress)
2300{
2301 if (Guid (aId).isEmpty())
2302 return E_INVALIDARG;
2303 if (!aProgress)
2304 return E_POINTER;
2305
2306 AutoCaller autoCaller (this);
2307 CheckComRCReturnRC (autoCaller.rc());
2308
2309 AutoLock alock (this);
2310
2311 if (mMachineState >= MachineState_Running)
2312 return setError (E_FAIL,
2313 tr ("Cannot discard a snapshot of the running machine "
2314 "(machine state: %d)"),
2315 mMachineState);
2316
2317 MachineState_T machineState = MachineState_InvalidMachineState;
2318 HRESULT rc = mControl->DiscardSnapshot (this, aId, &machineState, aProgress);
2319 CheckComRCReturnRC (rc);
2320
2321 setMachineStateLocally (machineState);
2322 return S_OK;
2323}
2324
2325STDMETHODIMP Console::DiscardCurrentState (IProgress **aProgress)
2326{
2327 AutoCaller autoCaller (this);
2328 CheckComRCReturnRC (autoCaller.rc());
2329
2330 AutoLock alock (this);
2331
2332 if (mMachineState >= MachineState_Running)
2333 return setError (E_FAIL,
2334 tr ("Cannot discard the current state of the running machine "
2335 "(nachine state: %d)"),
2336 mMachineState);
2337
2338 MachineState_T machineState = MachineState_InvalidMachineState;
2339 HRESULT rc = mControl->DiscardCurrentState (this, &machineState, aProgress);
2340 CheckComRCReturnRC (rc);
2341
2342 setMachineStateLocally (machineState);
2343 return S_OK;
2344}
2345
2346STDMETHODIMP Console::DiscardCurrentSnapshotAndState (IProgress **aProgress)
2347{
2348 AutoCaller autoCaller (this);
2349 CheckComRCReturnRC (autoCaller.rc());
2350
2351 AutoLock alock (this);
2352
2353 if (mMachineState >= MachineState_Running)
2354 return setError (E_FAIL,
2355 tr ("Cannot discard the current snapshot and state of the "
2356 "running machine (machine state: %d)"),
2357 mMachineState);
2358
2359 MachineState_T machineState = MachineState_InvalidMachineState;
2360 HRESULT rc =
2361 mControl->DiscardCurrentSnapshotAndState (this, &machineState, aProgress);
2362 CheckComRCReturnRC (rc);
2363
2364 setMachineStateLocally (machineState);
2365 return S_OK;
2366}
2367
2368STDMETHODIMP Console::RegisterCallback (IConsoleCallback *aCallback)
2369{
2370 if (!aCallback)
2371 return E_INVALIDARG;
2372
2373 AutoCaller autoCaller (this);
2374 CheckComRCReturnRC (autoCaller.rc());
2375
2376 AutoLock alock (this);
2377
2378 mCallbacks.push_back (CallbackList::value_type (aCallback));
2379
2380 /* Inform the callback about the current status (for example, the new
2381 * callback must know the current mouse capabilities and the pointer
2382 * shape in order to properly integrate the mouse pointer). */
2383
2384 if (mCallbackData.mpsc.valid)
2385 aCallback->OnMousePointerShapeChange (mCallbackData.mpsc.visible,
2386 mCallbackData.mpsc.alpha,
2387 mCallbackData.mpsc.xHot,
2388 mCallbackData.mpsc.yHot,
2389 mCallbackData.mpsc.width,
2390 mCallbackData.mpsc.height,
2391 mCallbackData.mpsc.shape);
2392 if (mCallbackData.mcc.valid)
2393 aCallback->OnMouseCapabilityChange (mCallbackData.mcc.supportsAbsolute,
2394 mCallbackData.mcc.needsHostCursor);
2395
2396 aCallback->OnAdditionsStateChange();
2397
2398 if (mCallbackData.klc.valid)
2399 aCallback->OnKeyboardLedsChange (mCallbackData.klc.numLock,
2400 mCallbackData.klc.capsLock,
2401 mCallbackData.klc.scrollLock);
2402
2403 /* Note: we don't call OnStateChange for new callbacks because the
2404 * machine state is a) not actually changed on callback registration
2405 * and b) can be always queried from Console. */
2406
2407 return S_OK;
2408}
2409
2410STDMETHODIMP Console::UnregisterCallback (IConsoleCallback *aCallback)
2411{
2412 if (!aCallback)
2413 return E_INVALIDARG;
2414
2415 AutoCaller autoCaller (this);
2416 CheckComRCReturnRC (autoCaller.rc());
2417
2418 AutoLock alock (this);
2419
2420 CallbackList::iterator it;
2421 it = std::find (mCallbacks.begin(),
2422 mCallbacks.end(),
2423 CallbackList::value_type (aCallback));
2424 if (it == mCallbacks.end())
2425 return setError (E_INVALIDARG,
2426 tr ("The given callback handler is not registered"));
2427
2428 mCallbacks.erase (it);
2429 return S_OK;
2430}
2431
2432// Non-interface public methods
2433/////////////////////////////////////////////////////////////////////////////
2434
2435/**
2436 * Called by IInternalSessionControl::OnDVDDriveChange().
2437 *
2438 * @note Locks this object for reading.
2439 */
2440HRESULT Console::onDVDDriveChange()
2441{
2442 LogFlowThisFunc (("\n"));
2443
2444 AutoCaller autoCaller (this);
2445 AssertComRCReturnRC (autoCaller.rc());
2446
2447 AutoReaderLock alock (this);
2448
2449 /* Ignore callbacks when there's no VM around */
2450 if (!mpVM)
2451 return S_OK;
2452
2453 /* protect mpVM */
2454 AutoVMCaller autoVMCaller (this);
2455 CheckComRCReturnRC (autoVMCaller.rc());
2456
2457 /* Get the current DVD state */
2458 HRESULT rc;
2459 DriveState_T eState;
2460
2461 rc = mDVDDrive->COMGETTER (State) (&eState);
2462 ComAssertComRCRetRC (rc);
2463
2464 /* Paranoia */
2465 if ( eState == DriveState_NotMounted
2466 && meDVDState == DriveState_NotMounted)
2467 {
2468 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2469 return S_OK;
2470 }
2471
2472 /* Get the path string and other relevant properties */
2473 Bstr Path;
2474 bool fPassthrough = false;
2475 switch (eState)
2476 {
2477 case DriveState_ImageMounted:
2478 {
2479 ComPtr <IDVDImage> ImagePtr;
2480 rc = mDVDDrive->GetImage (ImagePtr.asOutParam());
2481 if (SUCCEEDED (rc))
2482 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2483 break;
2484 }
2485
2486 case DriveState_HostDriveCaptured:
2487 {
2488 ComPtr <IHostDVDDrive> DrivePtr;
2489 BOOL enabled;
2490 rc = mDVDDrive->GetHostDrive (DrivePtr.asOutParam());
2491 if (SUCCEEDED (rc))
2492 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2493 if (SUCCEEDED (rc))
2494 rc = mDVDDrive->COMGETTER (Passthrough) (&enabled);
2495 if (SUCCEEDED (rc))
2496 fPassthrough = !!enabled;
2497 break;
2498 }
2499
2500 case DriveState_NotMounted:
2501 break;
2502
2503 default:
2504 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2505 rc = E_FAIL;
2506 break;
2507 }
2508
2509 AssertComRC (rc);
2510 if (FAILED (rc))
2511 {
2512 LogFlowThisFunc (("Returns %#x\n", rc));
2513 return rc;
2514 }
2515
2516 rc = doDriveChange ("piix3ide", 0, 2, eState, &meDVDState,
2517 Utf8Str (Path).raw(), fPassthrough);
2518
2519 /* notify console callbacks on success */
2520 if (SUCCEEDED (rc))
2521 {
2522 CallbackList::iterator it = mCallbacks.begin();
2523 while (it != mCallbacks.end())
2524 (*it++)->OnDVDDriveChange();
2525 }
2526
2527 return rc;
2528}
2529
2530
2531/**
2532 * Called by IInternalSessionControl::OnFloppyDriveChange().
2533 *
2534 * @note Locks this object for reading.
2535 */
2536HRESULT Console::onFloppyDriveChange()
2537{
2538 LogFlowThisFunc (("\n"));
2539
2540 AutoCaller autoCaller (this);
2541 AssertComRCReturnRC (autoCaller.rc());
2542
2543 AutoReaderLock alock (this);
2544
2545 /* Ignore callbacks when there's no VM around */
2546 if (!mpVM)
2547 return S_OK;
2548
2549 /* protect mpVM */
2550 AutoVMCaller autoVMCaller (this);
2551 CheckComRCReturnRC (autoVMCaller.rc());
2552
2553 /* Get the current floppy state */
2554 HRESULT rc;
2555 DriveState_T eState;
2556
2557 /* If the floppy drive is disabled, we're not interested */
2558 BOOL fEnabled;
2559 rc = mFloppyDrive->COMGETTER (Enabled) (&fEnabled);
2560 ComAssertComRCRetRC (rc);
2561
2562 if (!fEnabled)
2563 return S_OK;
2564
2565 rc = mFloppyDrive->COMGETTER (State) (&eState);
2566 ComAssertComRCRetRC (rc);
2567
2568 Log2 (("onFloppyDriveChange: eState=%d meFloppyState=%d\n", eState, meFloppyState));
2569
2570
2571 /* Paranoia */
2572 if ( eState == DriveState_NotMounted
2573 && meFloppyState == DriveState_NotMounted)
2574 {
2575 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2576 return S_OK;
2577 }
2578
2579 /* Get the path string and other relevant properties */
2580 Bstr Path;
2581 switch (eState)
2582 {
2583 case DriveState_ImageMounted:
2584 {
2585 ComPtr <IFloppyImage> ImagePtr;
2586 rc = mFloppyDrive->GetImage (ImagePtr.asOutParam());
2587 if (SUCCEEDED (rc))
2588 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2589 break;
2590 }
2591
2592 case DriveState_HostDriveCaptured:
2593 {
2594 ComPtr <IHostFloppyDrive> DrivePtr;
2595 rc = mFloppyDrive->GetHostDrive (DrivePtr.asOutParam());
2596 if (SUCCEEDED (rc))
2597 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2598 break;
2599 }
2600
2601 case DriveState_NotMounted:
2602 break;
2603
2604 default:
2605 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2606 rc = E_FAIL;
2607 break;
2608 }
2609
2610 AssertComRC (rc);
2611 if (FAILED (rc))
2612 {
2613 LogFlowThisFunc (("Returns %#x\n", rc));
2614 return rc;
2615 }
2616
2617 rc = doDriveChange ("i82078", 0, 0, eState, &meFloppyState,
2618 Utf8Str (Path).raw(), false);
2619
2620 /* notify console callbacks on success */
2621 if (SUCCEEDED (rc))
2622 {
2623 CallbackList::iterator it = mCallbacks.begin();
2624 while (it != mCallbacks.end())
2625 (*it++)->OnFloppyDriveChange();
2626 }
2627
2628 return rc;
2629}
2630
2631
2632/**
2633 * Process a floppy or dvd change.
2634 *
2635 * @returns COM status code.
2636 *
2637 * @param pszDevice The PDM device name.
2638 * @param uInstance The PDM device instance.
2639 * @param uLun The PDM LUN number of the drive.
2640 * @param eState The new state.
2641 * @param peState Pointer to the variable keeping the actual state of the drive.
2642 * This will be both read and updated to eState or other appropriate state.
2643 * @param pszPath The path to the media / drive which is now being mounted / captured.
2644 * If NULL no media or drive is attached and the lun will be configured with
2645 * the default block driver with no media. This will also be the state if
2646 * mounting / capturing the specified media / drive fails.
2647 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2648 *
2649 * @note Locks this object for reading.
2650 */
2651HRESULT Console::doDriveChange (const char *pszDevice, unsigned uInstance, unsigned uLun, DriveState_T eState,
2652 DriveState_T *peState, const char *pszPath, bool fPassthrough)
2653{
2654 LogFlowThisFunc (("pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2655 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2656 pszDevice, pszDevice, uInstance, uLun, eState,
2657 peState, *peState, pszPath, pszPath, fPassthrough));
2658
2659 AutoCaller autoCaller (this);
2660 AssertComRCReturnRC (autoCaller.rc());
2661
2662 AutoReaderLock alock (this);
2663
2664 /* protect mpVM */
2665 AutoVMCaller autoVMCaller (this);
2666 CheckComRCReturnRC (autoVMCaller.rc());
2667
2668 /*
2669 * Call worker in EMT, that's faster and safer than doing everything
2670 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2671 * here to make requests from under the lock in order to serialize them.
2672 */
2673 PVMREQ pReq;
2674 int vrc = VMR3ReqCall (mpVM, &pReq, 0 /* no wait! */,
2675 (PFNRT) Console::changeDrive, 8,
2676 this, pszDevice, uInstance, uLun, eState, peState,
2677 pszPath, fPassthrough);
2678 /// @todo (r=dmik) bird, it would be nice to have a special VMR3Req method
2679 // for that purpose, that doesn't return useless VERR_TIMEOUT
2680 if (vrc == VERR_TIMEOUT)
2681 vrc = VINF_SUCCESS;
2682
2683 /* leave the lock before waiting for a result (EMT will call us back!) */
2684 alock.leave();
2685
2686 if (VBOX_SUCCESS (vrc))
2687 {
2688 vrc = VMR3ReqWait (pReq, RT_INDEFINITE_WAIT);
2689 AssertRC (vrc);
2690 if (VBOX_SUCCESS (vrc))
2691 vrc = pReq->iStatus;
2692 }
2693 VMR3ReqFree (pReq);
2694
2695 if (VBOX_SUCCESS (vrc))
2696 {
2697 LogFlowThisFunc (("Returns S_OK\n"));
2698 return S_OK;
2699 }
2700
2701 if (pszPath)
2702 return setError (E_FAIL,
2703 tr ("Could not mount the media/drive '%s' (%Vrc)"), pszPath, vrc);
2704
2705 return setError (E_FAIL,
2706 tr ("Could not unmount the currently mounted media/drive (%Vrc)"), vrc);
2707}
2708
2709
2710/**
2711 * Performs the Floppy/DVD change in EMT.
2712 *
2713 * @returns VBox status code.
2714 *
2715 * @param pThis Pointer to the Console object.
2716 * @param pszDevice The PDM device name.
2717 * @param uInstance The PDM device instance.
2718 * @param uLun The PDM LUN number of the drive.
2719 * @param eState The new state.
2720 * @param peState Pointer to the variable keeping the actual state of the drive.
2721 * This will be both read and updated to eState or other appropriate state.
2722 * @param pszPath The path to the media / drive which is now being mounted / captured.
2723 * If NULL no media or drive is attached and the lun will be configured with
2724 * the default block driver with no media. This will also be the state if
2725 * mounting / capturing the specified media / drive fails.
2726 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2727 *
2728 * @thread EMT
2729 * @note Locks the Console object for writing
2730 */
2731DECLCALLBACK(int) Console::changeDrive (Console *pThis, const char *pszDevice, unsigned uInstance, unsigned uLun,
2732 DriveState_T eState, DriveState_T *peState,
2733 const char *pszPath, bool fPassthrough)
2734{
2735 LogFlowFunc (("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2736 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2737 pThis, pszDevice, pszDevice, uInstance, uLun, eState,
2738 peState, *peState, pszPath, pszPath, fPassthrough));
2739
2740 AssertReturn (pThis, VERR_INVALID_PARAMETER);
2741
2742 AssertMsg ( (!strcmp (pszDevice, "i82078") && uLun == 0 && uInstance == 0)
2743 || (!strcmp (pszDevice, "piix3ide") && uLun == 2 && uInstance == 0),
2744 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
2745
2746 AutoCaller autoCaller (pThis);
2747 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
2748
2749 /*
2750 * Locking the object before doing VMR3* calls is quite safe here,
2751 * since we're on EMT. Write lock is necessary because we're indirectly
2752 * modify the meDVDState/meFloppyState members (pointed to by peState).
2753 */
2754 AutoLock alock (pThis);
2755
2756 /* protect mpVM */
2757 AutoVMCaller autoVMCaller (pThis);
2758 CheckComRCReturnRC (autoVMCaller.rc());
2759
2760 PVM pVM = pThis->mpVM;
2761
2762 /*
2763 * Suspend the VM first.
2764 *
2765 * The VM must not be running since it might have pending I/O to
2766 * the drive which is being changed.
2767 */
2768 bool fResume;
2769 VMSTATE enmVMState = VMR3GetState (pVM);
2770 switch (enmVMState)
2771 {
2772 case VMSTATE_RESETTING:
2773 case VMSTATE_RUNNING:
2774 {
2775 LogFlowFunc (("Suspending the VM...\n"));
2776 /* disable the callback to prevent Console-level state change */
2777 pThis->mVMStateChangeCallbackDisabled = true;
2778 int rc = VMR3Suspend (pVM);
2779 pThis->mVMStateChangeCallbackDisabled = false;
2780 AssertRCReturn (rc, rc);
2781 fResume = true;
2782 break;
2783 }
2784
2785 case VMSTATE_SUSPENDED:
2786 case VMSTATE_CREATED:
2787 case VMSTATE_OFF:
2788 fResume = false;
2789 break;
2790
2791 default:
2792 AssertMsgFailedReturn (("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
2793 }
2794
2795 int rc = VINF_SUCCESS;
2796 int rcRet = VINF_SUCCESS;
2797
2798 do
2799 {
2800 /*
2801 * Unmount existing media / detach host drive.
2802 */
2803 PPDMIMOUNT pIMount = NULL;
2804 switch (*peState)
2805 {
2806
2807 case DriveState_ImageMounted:
2808 {
2809 /*
2810 * Resolve the interface.
2811 */
2812 PPDMIBASE pBase;
2813 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2814 if (VBOX_FAILURE (rc))
2815 {
2816 if (rc == VERR_PDM_LUN_NOT_FOUND)
2817 rc = VINF_SUCCESS;
2818 AssertRC (rc);
2819 break;
2820 }
2821
2822 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2823 AssertBreak (pIMount, rc = VERR_INVALID_POINTER);
2824
2825 /*
2826 * Unmount the media.
2827 */
2828 rc = pIMount->pfnUnmount (pIMount, false);
2829 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2830 rc = VINF_SUCCESS;
2831 break;
2832 }
2833
2834 case DriveState_HostDriveCaptured:
2835 {
2836 rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2837 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2838 rc = VINF_SUCCESS;
2839 AssertRC (rc);
2840 break;
2841 }
2842
2843 case DriveState_NotMounted:
2844 break;
2845
2846 default:
2847 AssertMsgFailed (("Invalid *peState: %d\n", peState));
2848 break;
2849 }
2850
2851 if (VBOX_FAILURE (rc))
2852 {
2853 rcRet = rc;
2854 break;
2855 }
2856
2857 /*
2858 * Nothing is currently mounted.
2859 */
2860 *peState = DriveState_NotMounted;
2861
2862
2863 /*
2864 * Process the HostDriveCaptured state first, as the fallback path
2865 * means mounting the normal block driver without media.
2866 */
2867 if (eState == DriveState_HostDriveCaptured)
2868 {
2869 /*
2870 * Detach existing driver chain (block).
2871 */
2872 int rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2873 if (VBOX_FAILURE (rc))
2874 {
2875 if (rc == VERR_PDM_LUN_NOT_FOUND)
2876 rc = VINF_SUCCESS;
2877 AssertReleaseRC (rc);
2878 break; /* we're toast */
2879 }
2880 pIMount = NULL;
2881
2882 /*
2883 * Construct a new driver configuration.
2884 */
2885 PCFGMNODE pInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2886 AssertRelease (pInst);
2887 /* nuke anything which might have been left behind. */
2888 CFGMR3RemoveNode (CFGMR3GetChildF (pInst, "LUN#%d", uLun));
2889
2890 /* create a new block driver config */
2891 PCFGMNODE pLunL0;
2892 PCFGMNODE pCfg;
2893 if ( VBOX_SUCCESS (rc = CFGMR3InsertNodeF (pInst, &pLunL0, "LUN#%u", uLun))
2894 && VBOX_SUCCESS (rc = CFGMR3InsertString (pLunL0, "Driver", !strcmp (pszDevice, "i82078") ? "HostFloppy" : "HostDVD"))
2895 && VBOX_SUCCESS (rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg))
2896 && VBOX_SUCCESS (rc = CFGMR3InsertString (pCfg, "Path", pszPath))
2897 && VBOX_SUCCESS (rc = !strcmp (pszDevice, "i82078") ? VINF_SUCCESS : CFGMR3InsertInteger(pCfg, "Passthrough", fPassthrough)))
2898 {
2899 /*
2900 * Attempt to attach the driver.
2901 */
2902 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, NULL);
2903 AssertRC (rc);
2904 }
2905 if (VBOX_FAILURE (rc))
2906 rcRet = rc;
2907 }
2908
2909 /*
2910 * Process the ImageMounted, NotMounted and failed HostDriveCapture cases.
2911 */
2912 rc = VINF_SUCCESS;
2913 switch (eState)
2914 {
2915#define RC_CHECK() do { if (VBOX_FAILURE (rc)) { AssertReleaseRC (rc); break; } } while (0)
2916
2917 case DriveState_HostDriveCaptured:
2918 if (VBOX_SUCCESS (rcRet))
2919 break;
2920 /* fallback: umounted block driver. */
2921 pszPath = NULL;
2922 eState = DriveState_NotMounted;
2923 /* fallthru */
2924 case DriveState_ImageMounted:
2925 case DriveState_NotMounted:
2926 {
2927 /*
2928 * Resolve the drive interface / create the driver.
2929 */
2930 if (!pIMount)
2931 {
2932 PPDMIBASE pBase;
2933 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2934 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2935 {
2936 /*
2937 * We have to create it, so we'll do the full config setup and everything.
2938 */
2939 PCFGMNODE pIdeInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2940 AssertRelease (pIdeInst);
2941
2942 /* nuke anything which might have been left behind. */
2943 CFGMR3RemoveNode (CFGMR3GetChildF (pIdeInst, "LUN#%d", uLun));
2944
2945 /* create a new block driver config */
2946 PCFGMNODE pLunL0;
2947 rc = CFGMR3InsertNodeF (pIdeInst, &pLunL0, "LUN#%d", uLun); RC_CHECK();
2948 rc = CFGMR3InsertString (pLunL0, "Driver", "Block"); RC_CHECK();
2949 PCFGMNODE pCfg;
2950 rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg); RC_CHECK();
2951 rc = CFGMR3InsertString (pCfg, "Type", !strcmp (pszDevice, "i82078") ? "Floppy 1.44" : "DVD");
2952 RC_CHECK();
2953 rc = CFGMR3InsertInteger (pCfg, "Mountable", 1); RC_CHECK();
2954
2955 /*
2956 * Attach the driver.
2957 */
2958 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, &pBase);
2959 RC_CHECK();
2960 }
2961 else if (VBOX_FAILURE(rc))
2962 {
2963 AssertRC (rc);
2964 return rc;
2965 }
2966
2967 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2968 if (!pIMount)
2969 {
2970 AssertFailed();
2971 return rc;
2972 }
2973 }
2974
2975 /*
2976 * If we've got an image, let's mount it.
2977 */
2978 if (pszPath && *pszPath)
2979 {
2980 rc = pIMount->pfnMount (pIMount, pszPath, strcmp (pszDevice, "i82078") ? "MediaISO" : "RawImage");
2981 if (VBOX_FAILURE (rc))
2982 eState = DriveState_NotMounted;
2983 }
2984 break;
2985 }
2986
2987 default:
2988 AssertMsgFailed (("Invalid eState: %d\n", eState));
2989 break;
2990
2991#undef RC_CHECK
2992 }
2993
2994 if (VBOX_FAILURE (rc) && VBOX_SUCCESS (rcRet))
2995 rcRet = rc;
2996
2997 *peState = eState;
2998 }
2999 while (0);
3000
3001 /*
3002 * Resume the VM if necessary.
3003 */
3004 if (fResume)
3005 {
3006 LogFlowFunc (("Resuming the VM...\n"));
3007 /* disable the callback to prevent Console-level state change */
3008 pThis->mVMStateChangeCallbackDisabled = true;
3009 rc = VMR3Resume (pVM);
3010 pThis->mVMStateChangeCallbackDisabled = false;
3011 AssertRC (rc);
3012 if (VBOX_FAILURE (rc))
3013 {
3014 /* too bad, we failed. try to sync the console state with the VMM state */
3015 vmstateChangeCallback (pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
3016 }
3017 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
3018 // error (if any) will be hidden from the caller. For proper reporting
3019 // of such multiple errors to the caller we need to enhance the
3020 // IVurtualBoxError interface. For now, give the first error the higher
3021 // priority.
3022 if (VBOX_SUCCESS (rcRet))
3023 rcRet = rc;
3024 }
3025
3026 LogFlowFunc (("Returning %Vrc\n", rcRet));
3027 return rcRet;
3028}
3029
3030
3031/**
3032 * Called by IInternalSessionControl::OnNetworkAdapterChange().
3033 *
3034 * @note Locks this object for writing.
3035 */
3036HRESULT Console::onNetworkAdapterChange (INetworkAdapter *aNetworkAdapter)
3037{
3038 LogFlowThisFunc (("\n"));
3039
3040 AutoCaller autoCaller (this);
3041 AssertComRCReturnRC (autoCaller.rc());
3042
3043 AutoLock alock (this);
3044
3045 /* Don't do anything if the VM isn't running */
3046 if (!mpVM)
3047 return S_OK;
3048
3049 /* protect mpVM */
3050 AutoVMCaller autoVMCaller (this);
3051 CheckComRCReturnRC (autoVMCaller.rc());
3052
3053 /* Get the properties we need from the adapter */
3054 BOOL fCableConnected;
3055 HRESULT rc = aNetworkAdapter->COMGETTER(CableConnected) (&fCableConnected);
3056 AssertComRC(rc);
3057 if (SUCCEEDED(rc))
3058 {
3059 ULONG ulInstance;
3060 rc = aNetworkAdapter->COMGETTER(Slot) (&ulInstance);
3061 AssertComRC (rc);
3062 if (SUCCEEDED (rc))
3063 {
3064 /*
3065 * Find the pcnet instance, get the config interface and update
3066 * the link state.
3067 */
3068 PPDMIBASE pBase;
3069 int vrc = PDMR3QueryDeviceLun (mpVM, "pcnet", (unsigned) ulInstance,
3070 0, &pBase);
3071 ComAssertRC (vrc);
3072 if (VBOX_SUCCESS (vrc))
3073 {
3074 Assert(pBase);
3075 PPDMINETWORKCONFIG pINetCfg = (PPDMINETWORKCONFIG) pBase->
3076 pfnQueryInterface(pBase, PDMINTERFACE_NETWORK_CONFIG);
3077 if (pINetCfg)
3078 {
3079 Log (("Console::onNetworkAdapterChange: setting link state to %d\n",
3080 fCableConnected));
3081 vrc = pINetCfg->pfnSetLinkState (pINetCfg,
3082 fCableConnected ? PDMNETWORKLINKSTATE_UP
3083 : PDMNETWORKLINKSTATE_DOWN);
3084 ComAssertRC (vrc);
3085 }
3086 }
3087
3088 if (VBOX_FAILURE (vrc))
3089 rc = E_FAIL;
3090 }
3091 }
3092
3093 /* notify console callbacks on success */
3094 if (SUCCEEDED (rc))
3095 {
3096 CallbackList::iterator it = mCallbacks.begin();
3097 while (it != mCallbacks.end())
3098 (*it++)->OnNetworkAdapterChange (aNetworkAdapter);
3099 }
3100
3101 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3102 return rc;
3103}
3104
3105/**
3106 * Called by IInternalSessionControl::OnSerialPortChange().
3107 *
3108 * @note Locks this object for writing.
3109 */
3110HRESULT Console::onSerialPortChange (ISerialPort *aSerialPort)
3111{
3112 LogFlowThisFunc (("\n"));
3113
3114 AutoCaller autoCaller (this);
3115 AssertComRCReturnRC (autoCaller.rc());
3116
3117 AutoLock alock (this);
3118
3119 /* Don't do anything if the VM isn't running */
3120 if (!mpVM)
3121 return S_OK;
3122
3123 HRESULT rc = S_OK;
3124
3125 /* protect mpVM */
3126 AutoVMCaller autoVMCaller (this);
3127 CheckComRCReturnRC (autoVMCaller.rc());
3128
3129 /* nothing to do so far */
3130
3131 /* notify console callbacks on success */
3132 if (SUCCEEDED (rc))
3133 {
3134 CallbackList::iterator it = mCallbacks.begin();
3135 while (it != mCallbacks.end())
3136 (*it++)->OnSerialPortChange (aSerialPort);
3137 }
3138
3139 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3140 return rc;
3141}
3142
3143/**
3144 * Called by IInternalSessionControl::OnParallelPortChange().
3145 *
3146 * @note Locks this object for writing.
3147 */
3148HRESULT Console::onParallelPortChange (IParallelPort *aParallelPort)
3149{
3150 LogFlowThisFunc (("\n"));
3151
3152 AutoCaller autoCaller (this);
3153 AssertComRCReturnRC (autoCaller.rc());
3154
3155 AutoLock alock (this);
3156
3157 /* Don't do anything if the VM isn't running */
3158 if (!mpVM)
3159 return S_OK;
3160
3161 HRESULT rc = S_OK;
3162
3163 /* protect mpVM */
3164 AutoVMCaller autoVMCaller (this);
3165 CheckComRCReturnRC (autoVMCaller.rc());
3166
3167 /* nothing to do so far */
3168
3169 /* notify console callbacks on success */
3170 if (SUCCEEDED (rc))
3171 {
3172 CallbackList::iterator it = mCallbacks.begin();
3173 while (it != mCallbacks.end())
3174 (*it++)->OnParallelPortChange (aParallelPort);
3175 }
3176
3177 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3178 return rc;
3179}
3180
3181/**
3182 * Called by IInternalSessionControl::OnVRDPServerChange().
3183 *
3184 * @note Locks this object for writing.
3185 */
3186HRESULT Console::onVRDPServerChange()
3187{
3188 AutoCaller autoCaller (this);
3189 AssertComRCReturnRC (autoCaller.rc());
3190
3191 AutoLock alock (this);
3192
3193 HRESULT rc = S_OK;
3194
3195 if (mVRDPServer && mMachineState == MachineState_Running)
3196 {
3197 BOOL vrdpEnabled = FALSE;
3198
3199 rc = mVRDPServer->COMGETTER(Enabled) (&vrdpEnabled);
3200 ComAssertComRCRetRC (rc);
3201
3202 if (vrdpEnabled)
3203 {
3204 // If there was no VRDP server started the 'stop' will do nothing.
3205 // However if a server was started and this notification was called,
3206 // we have to restart the server.
3207 mConsoleVRDPServer->Stop ();
3208
3209 if (VBOX_FAILURE(mConsoleVRDPServer->Launch ()))
3210 {
3211 rc = E_FAIL;
3212 }
3213 else
3214 {
3215 mConsoleVRDPServer->EnableConnections ();
3216 }
3217 }
3218 else
3219 {
3220 mConsoleVRDPServer->Stop ();
3221 }
3222 }
3223
3224 /* notify console callbacks on success */
3225 if (SUCCEEDED (rc))
3226 {
3227 CallbackList::iterator it = mCallbacks.begin();
3228 while (it != mCallbacks.end())
3229 (*it++)->OnVRDPServerChange();
3230 }
3231
3232 return rc;
3233}
3234
3235/**
3236 * Called by IInternalSessionControl::OnUSBControllerChange().
3237 *
3238 * @note Locks this object for writing.
3239 */
3240HRESULT Console::onUSBControllerChange()
3241{
3242 LogFlowThisFunc (("\n"));
3243
3244 AutoCaller autoCaller (this);
3245 AssertComRCReturnRC (autoCaller.rc());
3246
3247 AutoLock alock (this);
3248
3249 /* Ignore if no VM is running yet. */
3250 if (!mpVM)
3251 return S_OK;
3252
3253 HRESULT rc = S_OK;
3254
3255/// @todo (dmik)
3256// check for the Enabled state and disable virtual USB controller??
3257// Anyway, if we want to query the machine's USB Controller we need to cache
3258// it to to mUSBController in #init() (as it is done with mDVDDrive).
3259//
3260// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
3261//
3262// /* protect mpVM */
3263// AutoVMCaller autoVMCaller (this);
3264// CheckComRCReturnRC (autoVMCaller.rc());
3265
3266 /* notify console callbacks on success */
3267 if (SUCCEEDED (rc))
3268 {
3269 CallbackList::iterator it = mCallbacks.begin();
3270 while (it != mCallbacks.end())
3271 (*it++)->OnUSBControllerChange();
3272 }
3273
3274 return rc;
3275}
3276
3277/**
3278 * Called by IInternalSessionControl::OnSharedFolderChange().
3279 *
3280 * @note Locks this object for writing.
3281 */
3282HRESULT Console::onSharedFolderChange (BOOL aGlobal)
3283{
3284 LogFlowThisFunc (("aGlobal=%RTbool\n", aGlobal));
3285
3286 AutoCaller autoCaller (this);
3287 AssertComRCReturnRC (autoCaller.rc());
3288
3289 AutoLock alock (this);
3290
3291 HRESULT rc = fetchSharedFolders (aGlobal);
3292
3293 /* notify console callbacks on success */
3294 if (SUCCEEDED (rc))
3295 {
3296 CallbackList::iterator it = mCallbacks.begin();
3297 while (it != mCallbacks.end())
3298 (*it++)->OnSharedFolderChange (aGlobal ? (Scope_T)Scope_GlobalScope
3299 : (Scope_T)Scope_MachineScope);
3300 }
3301
3302 return rc;
3303}
3304
3305/**
3306 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
3307 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
3308 * returns TRUE for a given remote USB device.
3309 *
3310 * @return S_OK if the device was attached to the VM.
3311 * @return failure if not attached.
3312 *
3313 * @param aDevice
3314 * The device in question.
3315 * @param aMaskedIfs
3316 * The interfaces to hide from the guest.
3317 *
3318 * @note Locks this object for writing.
3319 */
3320HRESULT Console::onUSBDeviceAttach (IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
3321{
3322#ifdef VBOX_WITH_USB
3323 LogFlowThisFunc (("aDevice=%p aError=%p\n", aDevice, aError));
3324
3325 AutoCaller autoCaller (this);
3326 ComAssertComRCRetRC (autoCaller.rc());
3327
3328 AutoLock alock (this);
3329
3330 /* protect mpVM (we don't need error info, since it's a callback) */
3331 AutoVMCallerQuiet autoVMCaller (this);
3332 if (FAILED (autoVMCaller.rc()))
3333 {
3334 /* The VM may be no more operational when this message arrives
3335 * (e.g. it may be Saving or Stopping or just PoweredOff) --
3336 * autoVMCaller.rc() will return a failure in this case. */
3337 LogFlowThisFunc (("Attach request ignored (mMachineState=%d).\n",
3338 mMachineState));
3339 return autoVMCaller.rc();
3340 }
3341
3342 if (aError != NULL)
3343 {
3344 /* notify callbacks about the error */
3345 onUSBDeviceStateChange (aDevice, true /* aAttached */, aError);
3346 return S_OK;
3347 }
3348
3349 /* Don't proceed unless there's at least one USB hub. */
3350 if (!PDMR3USBHasHub (mpVM))
3351 {
3352 LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
3353 return E_FAIL;
3354 }
3355
3356 HRESULT rc = attachUSBDevice (aDevice, aMaskedIfs);
3357 if (FAILED (rc))
3358 {
3359 /* take the current error info */
3360 com::ErrorInfoKeeper eik;
3361 /* the error must be a VirtualBoxErrorInfo instance */
3362 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3363 Assert (!error.isNull());
3364 if (!error.isNull())
3365 {
3366 /* notify callbacks about the error */
3367 onUSBDeviceStateChange (aDevice, true /* aAttached */, error);
3368 }
3369 }
3370
3371 return rc;
3372
3373#else /* !VBOX_WITH_USB */
3374 return E_FAIL;
3375#endif /* !VBOX_WITH_USB */
3376}
3377
3378/**
3379 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
3380 * processRemoteUSBDevices().
3381 *
3382 * @note Locks this object for writing.
3383 */
3384HRESULT Console::onUSBDeviceDetach (INPTR GUIDPARAM aId,
3385 IVirtualBoxErrorInfo *aError)
3386{
3387#ifdef VBOX_WITH_USB
3388 Guid Uuid (aId);
3389 LogFlowThisFunc (("aId={%Vuuid} aError=%p\n", Uuid.raw(), aError));
3390
3391 AutoCaller autoCaller (this);
3392 AssertComRCReturnRC (autoCaller.rc());
3393
3394 AutoLock alock (this);
3395
3396 /* Find the device. */
3397 ComObjPtr <OUSBDevice> device;
3398 USBDeviceList::iterator it = mUSBDevices.begin();
3399 while (it != mUSBDevices.end())
3400 {
3401 LogFlowThisFunc (("it={%Vuuid}\n", (*it)->id().raw()));
3402 if ((*it)->id() == Uuid)
3403 {
3404 device = *it;
3405 break;
3406 }
3407 ++ it;
3408 }
3409
3410
3411 if (device.isNull())
3412 {
3413 LogFlowThisFunc (("USB device not found.\n"));
3414
3415 /* The VM may be no more operational when this message arrives
3416 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
3417 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
3418 * failure in this case. */
3419
3420 AutoVMCallerQuiet autoVMCaller (this);
3421 if (FAILED (autoVMCaller.rc()))
3422 {
3423 LogFlowThisFunc (("Detach request ignored (mMachineState=%d).\n",
3424 mMachineState));
3425 return autoVMCaller.rc();
3426 }
3427
3428 /* the device must be in the list otherwise */
3429 AssertFailedReturn (E_FAIL);
3430 }
3431
3432 if (aError != NULL)
3433 {
3434 /* notify callback about an error */
3435 onUSBDeviceStateChange (device, false /* aAttached */, aError);
3436 return S_OK;
3437 }
3438
3439 HRESULT rc = detachUSBDevice (it);
3440
3441 if (FAILED (rc))
3442 {
3443 /* take the current error info */
3444 com::ErrorInfoKeeper eik;
3445 /* the error must be a VirtualBoxErrorInfo instance */
3446 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3447 Assert (!error.isNull());
3448 if (!error.isNull())
3449 {
3450 /* notify callbacks about the error */
3451 onUSBDeviceStateChange (device, false /* aAttached */, error);
3452 }
3453 }
3454
3455 return rc;
3456
3457#else /* !VBOX_WITH_USB */
3458 return E_FAIL;
3459#endif /* !VBOX_WITH_USB */
3460}
3461
3462/**
3463 * Gets called by Session::UpdateMachineState()
3464 * (IInternalSessionControl::updateMachineState()).
3465 *
3466 * Must be called only in certain cases (see the implementation).
3467 *
3468 * @note Locks this object for writing.
3469 */
3470HRESULT Console::updateMachineState (MachineState_T aMachineState)
3471{
3472 AutoCaller autoCaller (this);
3473 AssertComRCReturnRC (autoCaller.rc());
3474
3475 AutoLock alock (this);
3476
3477 AssertReturn (mMachineState == MachineState_Saving ||
3478 mMachineState == MachineState_Discarding,
3479 E_FAIL);
3480
3481 return setMachineStateLocally (aMachineState);
3482}
3483
3484/**
3485 * @note Locks this object for writing.
3486 */
3487void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3488 uint32_t xHot, uint32_t yHot,
3489 uint32_t width, uint32_t height,
3490 void *pShape)
3491{
3492#if 0
3493 LogFlowThisFuncEnter();
3494 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3495 "height=%d, shape=%p\n",
3496 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3497#endif
3498
3499 AutoCaller autoCaller (this);
3500 AssertComRCReturnVoid (autoCaller.rc());
3501
3502 /* We need a write lock because we alter the cached callback data */
3503 AutoLock alock (this);
3504
3505 /* Save the callback arguments */
3506 mCallbackData.mpsc.visible = fVisible;
3507 mCallbackData.mpsc.alpha = fAlpha;
3508 mCallbackData.mpsc.xHot = xHot;
3509 mCallbackData.mpsc.yHot = yHot;
3510 mCallbackData.mpsc.width = width;
3511 mCallbackData.mpsc.height = height;
3512
3513 /* start with not valid */
3514 bool wasValid = mCallbackData.mpsc.valid;
3515 mCallbackData.mpsc.valid = false;
3516
3517 if (pShape != NULL)
3518 {
3519 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3520 cb = ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3521 /* try to reuse the old shape buffer if the size is the same */
3522 if (!wasValid)
3523 mCallbackData.mpsc.shape = NULL;
3524 else
3525 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3526 {
3527 RTMemFree (mCallbackData.mpsc.shape);
3528 mCallbackData.mpsc.shape = NULL;
3529 }
3530 if (mCallbackData.mpsc.shape == NULL)
3531 {
3532 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3533 AssertReturnVoid (mCallbackData.mpsc.shape);
3534 }
3535 mCallbackData.mpsc.shapeSize = cb;
3536 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3537 }
3538 else
3539 {
3540 if (wasValid && mCallbackData.mpsc.shape != NULL)
3541 RTMemFree (mCallbackData.mpsc.shape);
3542 mCallbackData.mpsc.shape = NULL;
3543 mCallbackData.mpsc.shapeSize = 0;
3544 }
3545
3546 mCallbackData.mpsc.valid = true;
3547
3548 CallbackList::iterator it = mCallbacks.begin();
3549 while (it != mCallbacks.end())
3550 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3551 width, height, (BYTE *) pShape);
3552
3553#if 0
3554 LogFlowThisFuncLeave();
3555#endif
3556}
3557
3558/**
3559 * @note Locks this object for writing.
3560 */
3561void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3562{
3563 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3564 supportsAbsolute, needsHostCursor));
3565
3566 AutoCaller autoCaller (this);
3567 AssertComRCReturnVoid (autoCaller.rc());
3568
3569 /* We need a write lock because we alter the cached callback data */
3570 AutoLock alock (this);
3571
3572 /* save the callback arguments */
3573 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3574 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3575 mCallbackData.mcc.valid = true;
3576
3577 CallbackList::iterator it = mCallbacks.begin();
3578 while (it != mCallbacks.end())
3579 {
3580 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3581 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3582 }
3583}
3584
3585/**
3586 * @note Locks this object for reading.
3587 */
3588void Console::onStateChange (MachineState_T machineState)
3589{
3590 AutoCaller autoCaller (this);
3591 AssertComRCReturnVoid (autoCaller.rc());
3592
3593 AutoReaderLock alock (this);
3594
3595 CallbackList::iterator it = mCallbacks.begin();
3596 while (it != mCallbacks.end())
3597 (*it++)->OnStateChange (machineState);
3598}
3599
3600/**
3601 * @note Locks this object for reading.
3602 */
3603void Console::onAdditionsStateChange()
3604{
3605 AutoCaller autoCaller (this);
3606 AssertComRCReturnVoid (autoCaller.rc());
3607
3608 AutoReaderLock alock (this);
3609
3610 CallbackList::iterator it = mCallbacks.begin();
3611 while (it != mCallbacks.end())
3612 (*it++)->OnAdditionsStateChange();
3613}
3614
3615/**
3616 * @note Locks this object for reading.
3617 */
3618void Console::onAdditionsOutdated()
3619{
3620 AutoCaller autoCaller (this);
3621 AssertComRCReturnVoid (autoCaller.rc());
3622
3623 AutoReaderLock alock (this);
3624
3625 /** @todo Use the On-Screen Display feature to report the fact.
3626 * The user should be told to install additions that are
3627 * provided with the current VBox build:
3628 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3629 */
3630}
3631
3632/**
3633 * @note Locks this object for writing.
3634 */
3635void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3636{
3637 AutoCaller autoCaller (this);
3638 AssertComRCReturnVoid (autoCaller.rc());
3639
3640 /* We need a write lock because we alter the cached callback data */
3641 AutoLock alock (this);
3642
3643 /* save the callback arguments */
3644 mCallbackData.klc.numLock = fNumLock;
3645 mCallbackData.klc.capsLock = fCapsLock;
3646 mCallbackData.klc.scrollLock = fScrollLock;
3647 mCallbackData.klc.valid = true;
3648
3649 CallbackList::iterator it = mCallbacks.begin();
3650 while (it != mCallbacks.end())
3651 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3652}
3653
3654/**
3655 * @note Locks this object for reading.
3656 */
3657void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
3658 IVirtualBoxErrorInfo *aError)
3659{
3660 AutoCaller autoCaller (this);
3661 AssertComRCReturnVoid (autoCaller.rc());
3662
3663 AutoReaderLock alock (this);
3664
3665 CallbackList::iterator it = mCallbacks.begin();
3666 while (it != mCallbacks.end())
3667 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
3668}
3669
3670/**
3671 * @note Locks this object for reading.
3672 */
3673void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3674{
3675 AutoCaller autoCaller (this);
3676 AssertComRCReturnVoid (autoCaller.rc());
3677
3678 AutoReaderLock alock (this);
3679
3680 CallbackList::iterator it = mCallbacks.begin();
3681 while (it != mCallbacks.end())
3682 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3683}
3684
3685/**
3686 * @note Locks this object for reading.
3687 */
3688HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
3689{
3690 AssertReturn (aCanShow, E_POINTER);
3691 AssertReturn (aWinId, E_POINTER);
3692
3693 *aCanShow = FALSE;
3694 *aWinId = 0;
3695
3696 AutoCaller autoCaller (this);
3697 AssertComRCReturnRC (autoCaller.rc());
3698
3699 AutoReaderLock alock (this);
3700
3701 HRESULT rc = S_OK;
3702 CallbackList::iterator it = mCallbacks.begin();
3703
3704 if (aCheck)
3705 {
3706 while (it != mCallbacks.end())
3707 {
3708 BOOL canShow = FALSE;
3709 rc = (*it++)->OnCanShowWindow (&canShow);
3710 AssertComRC (rc);
3711 if (FAILED (rc) || !canShow)
3712 return rc;
3713 }
3714 *aCanShow = TRUE;
3715 }
3716 else
3717 {
3718 while (it != mCallbacks.end())
3719 {
3720 ULONG64 winId = 0;
3721 rc = (*it++)->OnShowWindow (&winId);
3722 AssertComRC (rc);
3723 if (FAILED (rc))
3724 return rc;
3725 /* only one callback may return non-null winId */
3726 Assert (*aWinId == 0 || winId == 0);
3727 if (*aWinId == 0)
3728 *aWinId = winId;
3729 }
3730 }
3731
3732 return S_OK;
3733}
3734
3735// private mehtods
3736////////////////////////////////////////////////////////////////////////////////
3737
3738/**
3739 * Increases the usage counter of the mpVM pointer. Guarantees that
3740 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
3741 * is called.
3742 *
3743 * If this method returns a failure, the caller is not allowed to use mpVM
3744 * and may return the failed result code to the upper level. This method sets
3745 * the extended error info on failure if \a aQuiet is false.
3746 *
3747 * Setting \a aQuiet to true is useful for methods that don't want to return
3748 * the failed result code to the caller when this method fails (e.g. need to
3749 * silently check for the mpVM avaliability).
3750 *
3751 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
3752 * returned instead of asserting. Having it false is intended as a sanity check
3753 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
3754 *
3755 * @param aQuiet true to suppress setting error info
3756 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
3757 * (otherwise this method will assert if mpVM is NULL)
3758 *
3759 * @note Locks this object for writing.
3760 */
3761HRESULT Console::addVMCaller (bool aQuiet /* = false */,
3762 bool aAllowNullVM /* = false */)
3763{
3764 AutoCaller autoCaller (this);
3765 AssertComRCReturnRC (autoCaller.rc());
3766
3767 AutoLock alock (this);
3768
3769 if (mVMDestroying)
3770 {
3771 /* powerDown() is waiting for all callers to finish */
3772 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3773 tr ("Virtual machine is being powered down"));
3774 }
3775
3776 if (mpVM == NULL)
3777 {
3778 Assert (aAllowNullVM == true);
3779
3780 /* The machine is not powered up */
3781 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3782 tr ("Virtual machine is not powered up"));
3783 }
3784
3785 ++ mVMCallers;
3786
3787 return S_OK;
3788}
3789
3790/**
3791 * Decreases the usage counter of the mpVM pointer. Must always complete
3792 * the addVMCaller() call after the mpVM pointer is no more necessary.
3793 *
3794 * @note Locks this object for writing.
3795 */
3796void Console::releaseVMCaller()
3797{
3798 AutoCaller autoCaller (this);
3799 AssertComRCReturnVoid (autoCaller.rc());
3800
3801 AutoLock alock (this);
3802
3803 AssertReturnVoid (mpVM != NULL);
3804
3805 Assert (mVMCallers > 0);
3806 -- mVMCallers;
3807
3808 if (mVMCallers == 0 && mVMDestroying)
3809 {
3810 /* inform powerDown() there are no more callers */
3811 RTSemEventSignal (mVMZeroCallersSem);
3812 }
3813}
3814
3815/**
3816 * Internal power off worker routine.
3817 *
3818 * This method may be called only at certain places with the folliwing meaning
3819 * as shown below:
3820 *
3821 * - if the machine state is either Running or Paused, a normal
3822 * Console-initiated powerdown takes place (e.g. PowerDown());
3823 * - if the machine state is Saving, saveStateThread() has successfully
3824 * done its job;
3825 * - if the machine state is Starting or Restoring, powerUpThread() has
3826 * failed to start/load the VM;
3827 * - if the machine state is Stopping, the VM has powered itself off
3828 * (i.e. not as a result of the powerDown() call).
3829 *
3830 * Calling it in situations other than the above will cause unexpected
3831 * behavior.
3832 *
3833 * Note that this method should be the only one that destroys mpVM and sets
3834 * it to NULL.
3835 *
3836 * @note Locks this object for writing.
3837 *
3838 * @note Never call this method from a thread that called addVMCaller() or
3839 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
3840 * release(). Otherwise it will deadlock.
3841 */
3842HRESULT Console::powerDown()
3843{
3844 LogFlowThisFuncEnter();
3845
3846 AutoCaller autoCaller (this);
3847 AssertComRCReturnRC (autoCaller.rc());
3848
3849 AutoLock alock (this);
3850
3851 /* sanity */
3852 AssertReturn (mVMDestroying == false, E_FAIL);
3853
3854 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
3855 "(mMachineState=%d, InUninit=%d)\n",
3856 mMachineState, autoCaller.state() == InUninit));
3857
3858 /*
3859 * Stop the VRDP server to prevent new clients connection while VM is being powered off.
3860 */
3861 if (mConsoleVRDPServer)
3862 {
3863 LogFlowThisFunc (("Stopping VRDP server...\n"));
3864
3865 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
3866 alock.leave();
3867
3868 mConsoleVRDPServer->Stop();
3869
3870 alock.enter();
3871 }
3872
3873
3874#ifdef VBOX_HGCM
3875 /*
3876 * Shutdown HGCM services before stopping the guest, because they might need a cleanup.
3877 */
3878 if (mVMMDev)
3879 {
3880 LogFlowThisFunc (("Shutdown HGCM...\n"));
3881
3882 /* Leave the lock. */
3883 alock.leave();
3884
3885 mVMMDev->hgcmShutdown ();
3886
3887 alock.enter();
3888 }
3889#endif /* VBOX_HGCM */
3890
3891 /* First, wait for all mpVM callers to finish their work if necessary */
3892 if (mVMCallers > 0)
3893 {
3894 /* go to the destroying state to prevent from adding new callers */
3895 mVMDestroying = true;
3896
3897 /* lazy creation */
3898 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
3899 RTSemEventCreate (&mVMZeroCallersSem);
3900
3901 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
3902 mVMCallers));
3903
3904 alock.leave();
3905
3906 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
3907
3908 alock.enter();
3909 }
3910
3911 AssertReturn (mpVM, E_FAIL);
3912
3913 AssertMsg (mMachineState == MachineState_Running ||
3914 mMachineState == MachineState_Paused ||
3915 mMachineState == MachineState_Stuck ||
3916 mMachineState == MachineState_Saving ||
3917 mMachineState == MachineState_Starting ||
3918 mMachineState == MachineState_Restoring ||
3919 mMachineState == MachineState_Stopping,
3920 ("Invalid machine state: %d\n", mMachineState));
3921
3922 HRESULT rc = S_OK;
3923 int vrc = VINF_SUCCESS;
3924
3925 /*
3926 * Power off the VM if not already done that. In case of Stopping, the VM
3927 * has powered itself off and notified Console in vmstateChangeCallback().
3928 * In case of Starting or Restoring, powerUpThread() is calling us on
3929 * failure, so the VM is already off at that point.
3930 */
3931 if (mMachineState != MachineState_Stopping &&
3932 mMachineState != MachineState_Starting &&
3933 mMachineState != MachineState_Restoring)
3934 {
3935 /*
3936 * don't go from Saving to Stopping, vmstateChangeCallback needs it
3937 * to set the state to Saved on VMSTATE_TERMINATED.
3938 */
3939 if (mMachineState != MachineState_Saving)
3940 setMachineState (MachineState_Stopping);
3941
3942 LogFlowThisFunc (("Powering off the VM...\n"));
3943
3944 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
3945 alock.leave();
3946
3947 vrc = VMR3PowerOff (mpVM);
3948 /*
3949 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
3950 * VM-(guest-)initiated power off happened in parallel a ms before
3951 * this call. So far, we let this error pop up on the user's side.
3952 */
3953
3954 alock.enter();
3955 }
3956
3957 LogFlowThisFunc (("Ready for VM destruction\n"));
3958
3959 /*
3960 * If we are called from Console::uninit(), then try to destroy the VM
3961 * even on failure (this will most likely fail too, but what to do?..)
3962 */
3963 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
3964 {
3965 /* If the machine has an USB comtroller, release all USB devices
3966 * (symmetric to the code in captureUSBDevices()) */
3967 bool fHasUSBController = false;
3968 {
3969 PPDMIBASE pBase;
3970 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3971 if (VBOX_SUCCESS (vrc))
3972 {
3973 fHasUSBController = true;
3974 detachAllUSBDevices (false /* aDone */);
3975 }
3976 }
3977
3978 /*
3979 * Now we've got to destroy the VM as well. (mpVM is not valid
3980 * beyond this point). We leave the lock before calling VMR3Destroy()
3981 * because it will result into calling destructors of drivers
3982 * associated with Console children which may in turn try to lock
3983 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
3984 * here because mVMDestroying is set which should prevent any activity.
3985 */
3986
3987 /*
3988 * Set mpVM to NULL early just in case if some old code is not using
3989 * addVMCaller()/releaseVMCaller().
3990 */
3991 PVM pVM = mpVM;
3992 mpVM = NULL;
3993
3994 LogFlowThisFunc (("Destroying the VM...\n"));
3995
3996 alock.leave();
3997
3998 vrc = VMR3Destroy (pVM);
3999
4000 /* take the lock again */
4001 alock.enter();
4002
4003 if (VBOX_SUCCESS (vrc))
4004 {
4005 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
4006 mMachineState));
4007 /*
4008 * Note: the Console-level machine state change happens on the
4009 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
4010 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
4011 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
4012 * occured yet. This is okay, because mMachineState is already
4013 * Stopping in this case, so any other attempt to call PowerDown()
4014 * will be rejected.
4015 */
4016 }
4017 else
4018 {
4019 /* bad bad bad, but what to do? */
4020 mpVM = pVM;
4021 rc = setError (E_FAIL,
4022 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
4023 }
4024
4025 /*
4026 * Complete the detaching of the USB devices.
4027 */
4028 if (fHasUSBController)
4029 detachAllUSBDevices (true /* aDone */);
4030 }
4031 else
4032 {
4033 rc = setError (E_FAIL,
4034 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
4035 }
4036
4037 /*
4038 * Finished with destruction. Note that if something impossible happened
4039 * and we've failed to destroy the VM, mVMDestroying will remain false and
4040 * mMachineState will be something like Stopping, so most Console methods
4041 * will return an error to the caller.
4042 */
4043 if (mpVM == NULL)
4044 mVMDestroying = false;
4045
4046 if (SUCCEEDED (rc))
4047 {
4048 /* uninit dynamically allocated members of mCallbackData */
4049 if (mCallbackData.mpsc.valid)
4050 {
4051 if (mCallbackData.mpsc.shape != NULL)
4052 RTMemFree (mCallbackData.mpsc.shape);
4053 }
4054 memset (&mCallbackData, 0, sizeof (mCallbackData));
4055 }
4056
4057 LogFlowThisFuncLeave();
4058 return rc;
4059}
4060
4061/**
4062 * @note Locks this object for writing.
4063 */
4064HRESULT Console::setMachineState (MachineState_T aMachineState,
4065 bool aUpdateServer /* = true */)
4066{
4067 AutoCaller autoCaller (this);
4068 AssertComRCReturnRC (autoCaller.rc());
4069
4070 AutoLock alock (this);
4071
4072 HRESULT rc = S_OK;
4073
4074 if (mMachineState != aMachineState)
4075 {
4076 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4077 mMachineState = aMachineState;
4078
4079 /// @todo (dmik)
4080 // possibly, we need to redo onStateChange() using the dedicated
4081 // Event thread, like it is done in VirtualBox. This will make it
4082 // much safer (no deadlocks possible if someone tries to use the
4083 // console from the callback), however, listeners will lose the
4084 // ability to synchronously react to state changes (is it really
4085 // necessary??)
4086 LogFlowThisFunc (("Doing onStateChange()...\n"));
4087 onStateChange (aMachineState);
4088 LogFlowThisFunc (("Done onStateChange()\n"));
4089
4090 if (aUpdateServer)
4091 {
4092 /*
4093 * Server notification MUST be done from under the lock; otherwise
4094 * the machine state here and on the server might go out of sync, that
4095 * can lead to various unexpected results (like the machine state being
4096 * >= MachineState_Running on the server, while the session state is
4097 * already SessionState_SessionClosed at the same time there).
4098 *
4099 * Cross-lock conditions should be carefully watched out: calling
4100 * UpdateState we will require Machine and SessionMachine locks
4101 * (remember that here we're holding the Console lock here, and
4102 * also all locks that have been entered by the thread before calling
4103 * this method).
4104 */
4105 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4106 rc = mControl->UpdateState (aMachineState);
4107 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4108 }
4109 }
4110
4111 return rc;
4112}
4113
4114/**
4115 * Searches for a shared folder with the given logical name
4116 * in the collection of shared folders.
4117 *
4118 * @param aName logical name of the shared folder
4119 * @param aSharedFolder where to return the found object
4120 * @param aSetError whether to set the error info if the folder is
4121 * not found
4122 * @return
4123 * S_OK when found or E_INVALIDARG when not found
4124 *
4125 * @note The caller must lock this object for writing.
4126 */
4127HRESULT Console::findSharedFolder (const BSTR aName,
4128 ComObjPtr <SharedFolder> &aSharedFolder,
4129 bool aSetError /* = false */)
4130{
4131 /* sanity check */
4132 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4133
4134 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4135 if (it != mSharedFolders.end())
4136 {
4137 aSharedFolder = it->second;
4138 return S_OK;
4139 }
4140
4141 if (aSetError)
4142 setError (E_INVALIDARG,
4143 tr ("Could not find a shared folder named '%ls'."), aName);
4144
4145 return E_INVALIDARG;
4146}
4147
4148/**
4149 * Fetches the list of global or machine shared folders from the server.
4150 *
4151 * @param aGlobal true to fetch global folders.
4152 *
4153 * @note The caller must lock this object for writing.
4154 */
4155HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4156{
4157 /* sanity check */
4158 AssertReturn (AutoCaller (this).state() == InInit ||
4159 isLockedOnCurrentThread(), E_FAIL);
4160
4161 /* protect mpVM (if not NULL) */
4162 AutoVMCallerQuietWeak autoVMCaller (this);
4163
4164 HRESULT rc = S_OK;
4165
4166 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4167
4168 if (aGlobal)
4169 {
4170 /// @todo grab & process global folders when they are done
4171 }
4172 else
4173 {
4174 SharedFolderDataMap oldFolders;
4175 if (online)
4176 oldFolders = mMachineSharedFolders;
4177
4178 mMachineSharedFolders.clear();
4179
4180 ComPtr <ISharedFolderCollection> coll;
4181 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
4182 AssertComRCReturnRC (rc);
4183
4184 ComPtr <ISharedFolderEnumerator> en;
4185 rc = coll->Enumerate (en.asOutParam());
4186 AssertComRCReturnRC (rc);
4187
4188 BOOL hasMore = FALSE;
4189 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
4190 {
4191 ComPtr <ISharedFolder> folder;
4192 rc = en->GetNext (folder.asOutParam());
4193 CheckComRCBreakRC (rc);
4194
4195 Bstr name;
4196 Bstr hostPath;
4197
4198 rc = folder->COMGETTER(Name) (name.asOutParam());
4199 CheckComRCBreakRC (rc);
4200 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
4201 CheckComRCBreakRC (rc);
4202
4203 mMachineSharedFolders.insert (std::make_pair (name, hostPath));
4204
4205 /* send changes to HGCM if the VM is running */
4206 /// @todo report errors as runtime warnings through VMSetError
4207 if (online)
4208 {
4209 SharedFolderDataMap::iterator it = oldFolders.find (name);
4210 if (it == oldFolders.end() || it->second != hostPath)
4211 {
4212 /* a new machine folder is added or
4213 * the existing machine folder is changed */
4214 if (mSharedFolders.find (name) != mSharedFolders.end())
4215 ; /* the console folder exists, nothing to do */
4216 else
4217 {
4218 /* remove the old machhine folder (when changed)
4219 * or the global folder if any (when new) */
4220 if (it != oldFolders.end() ||
4221 mGlobalSharedFolders.find (name) !=
4222 mGlobalSharedFolders.end())
4223 rc = removeSharedFolder (name);
4224 /* create the new machine folder */
4225 rc = createSharedFolder (name, hostPath);
4226 }
4227 }
4228 /* forget the processed (or identical) folder */
4229 if (it != oldFolders.end())
4230 oldFolders.erase (it);
4231
4232 rc = S_OK;
4233 }
4234 }
4235
4236 AssertComRCReturnRC (rc);
4237
4238 /* process outdated (removed) folders */
4239 /// @todo report errors as runtime warnings through VMSetError
4240 if (online)
4241 {
4242 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
4243 it != oldFolders.end(); ++ it)
4244 {
4245 if (mSharedFolders.find (it->first) != mSharedFolders.end())
4246 ; /* the console folder exists, nothing to do */
4247 else
4248 {
4249 /* remove the outdated machine folder */
4250 rc = removeSharedFolder (it->first);
4251 /* create the global folder if there is any */
4252 SharedFolderDataMap::const_iterator git =
4253 mGlobalSharedFolders.find (it->first);
4254 if (git != mGlobalSharedFolders.end())
4255 rc = createSharedFolder (git->first, git->second);
4256 }
4257 }
4258
4259 rc = S_OK;
4260 }
4261 }
4262
4263 return rc;
4264}
4265
4266/**
4267 * Searches for a shared folder with the given name in the list of machine
4268 * shared folders and then in the list of the global shared folders.
4269 *
4270 * @param aName Name of the folder to search for.
4271 * @param aIt Where to store the pointer to the found folder.
4272 * @return @c true if the folder was found and @c false otherwise.
4273 *
4274 * @note The caller must lock this object for reading.
4275 */
4276bool Console::findOtherSharedFolder (INPTR BSTR aName,
4277 SharedFolderDataMap::const_iterator &aIt)
4278{
4279 /* sanity check */
4280 AssertReturn (isLockedOnCurrentThread(), false);
4281
4282 /* first, search machine folders */
4283 aIt = mMachineSharedFolders.find (aName);
4284 if (aIt != mMachineSharedFolders.end())
4285 return true;
4286
4287 /* second, search machine folders */
4288 aIt = mGlobalSharedFolders.find (aName);
4289 if (aIt != mGlobalSharedFolders.end())
4290 return true;
4291
4292 return false;
4293}
4294
4295/**
4296 * Calls the HGCM service to add a shared folder definition.
4297 *
4298 * @param aName Shared folder name.
4299 * @param aHostPath Shared folder path.
4300 *
4301 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4302 * @note Doesn't lock anything.
4303 */
4304HRESULT Console::createSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath)
4305{
4306 ComAssertRet (aName && *aName, E_FAIL);
4307 ComAssertRet (aHostPath && *aHostPath, E_FAIL);
4308
4309 /* sanity checks */
4310 AssertReturn (mpVM, E_FAIL);
4311 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4312
4313 VBOXHGCMSVCPARM parms[2];
4314 SHFLSTRING *pFolderName, *pMapName;
4315 size_t cbString;
4316
4317 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aHostPath));
4318
4319 cbString = (RTStrUcs2Len (aHostPath) + 1) * sizeof (RTUCS2);
4320 if (cbString >= UINT16_MAX)
4321 return setError (E_INVALIDARG, tr ("The name is too long"));
4322 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4323 Assert (pFolderName);
4324 memcpy (pFolderName->String.ucs2, aHostPath, cbString);
4325
4326 pFolderName->u16Size = (uint16_t)cbString;
4327 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUCS2);
4328
4329 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4330 parms[0].u.pointer.addr = pFolderName;
4331 parms[0].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4332
4333 cbString = (RTStrUcs2Len (aName) + 1) * sizeof (RTUCS2);
4334 if (cbString >= UINT16_MAX)
4335 {
4336 RTMemFree (pFolderName);
4337 return setError (E_INVALIDARG, tr ("The host path is too long"));
4338 }
4339 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
4340 Assert (pMapName);
4341 memcpy (pMapName->String.ucs2, aName, cbString);
4342
4343 pMapName->u16Size = (uint16_t)cbString;
4344 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUCS2);
4345
4346 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4347 parms[1].u.pointer.addr = pMapName;
4348 parms[1].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4349
4350 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4351 SHFL_FN_ADD_MAPPING,
4352 2, &parms[0]);
4353 RTMemFree (pFolderName);
4354 RTMemFree (pMapName);
4355
4356 if (VBOX_FAILURE (vrc))
4357 return setError (E_FAIL,
4358 tr ("Could not create a shared folder '%ls' "
4359 "mapped to '%ls' (%Vrc)"),
4360 aName, aHostPath, vrc);
4361
4362 return S_OK;
4363}
4364
4365/**
4366 * Calls the HGCM service to remove the shared folder definition.
4367 *
4368 * @param aName Shared folder name.
4369 *
4370 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4371 * @note Doesn't lock anything.
4372 */
4373HRESULT Console::removeSharedFolder (INPTR BSTR aName)
4374{
4375 ComAssertRet (aName && *aName, E_FAIL);
4376
4377 /* sanity checks */
4378 AssertReturn (mpVM, E_FAIL);
4379 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4380
4381 VBOXHGCMSVCPARM parms;
4382 SHFLSTRING *pMapName;
4383 size_t cbString;
4384
4385 Log (("Removing shared folder '%ls'\n", aName));
4386
4387 cbString = (RTStrUcs2Len (aName) + 1) * sizeof (RTUCS2);
4388 if (cbString >= UINT16_MAX)
4389 return setError (E_INVALIDARG, tr ("The name is too long"));
4390 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4391 Assert (pMapName);
4392 memcpy (pMapName->String.ucs2, aName, cbString);
4393
4394 pMapName->u16Size = (uint16_t)cbString;
4395 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUCS2);
4396
4397 parms.type = VBOX_HGCM_SVC_PARM_PTR;
4398 parms.u.pointer.addr = pMapName;
4399 parms.u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4400
4401 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4402 SHFL_FN_REMOVE_MAPPING,
4403 1, &parms);
4404 RTMemFree(pMapName);
4405 if (VBOX_FAILURE (vrc))
4406 return setError (E_FAIL,
4407 tr ("Could not remove the shared folder '%ls' (%Vrc)"),
4408 aName, vrc);
4409
4410 return S_OK;
4411}
4412
4413/**
4414 * VM state callback function. Called by the VMM
4415 * using its state machine states.
4416 *
4417 * Primarily used to handle VM initiated power off, suspend and state saving,
4418 * but also for doing termination completed work (VMSTATE_TERMINATE).
4419 *
4420 * In general this function is called in the context of the EMT.
4421 *
4422 * @param aVM The VM handle.
4423 * @param aState The new state.
4424 * @param aOldState The old state.
4425 * @param aUser The user argument (pointer to the Console object).
4426 *
4427 * @note Locks the Console object for writing.
4428 */
4429DECLCALLBACK(void)
4430Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
4431 void *aUser)
4432{
4433 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
4434 aOldState, aState, aVM));
4435
4436 Console *that = static_cast <Console *> (aUser);
4437 AssertReturnVoid (that);
4438
4439 AutoCaller autoCaller (that);
4440 /*
4441 * Note that we must let this method proceed even if Console::uninit() has
4442 * been already called. In such case this VMSTATE change is a result of:
4443 * 1) powerDown() called from uninit() itself, or
4444 * 2) VM-(guest-)initiated power off.
4445 */
4446 AssertReturnVoid (autoCaller.isOk() ||
4447 autoCaller.state() == InUninit);
4448
4449 switch (aState)
4450 {
4451 /*
4452 * The VM has terminated
4453 */
4454 case VMSTATE_OFF:
4455 {
4456 AutoLock alock (that);
4457
4458 if (that->mVMStateChangeCallbackDisabled)
4459 break;
4460
4461 /*
4462 * Do we still think that it is running? It may happen if this is
4463 * a VM-(guest-)initiated shutdown/poweroff.
4464 */
4465 if (that->mMachineState != MachineState_Stopping &&
4466 that->mMachineState != MachineState_Saving &&
4467 that->mMachineState != MachineState_Restoring)
4468 {
4469 LogFlowFunc (("VM has powered itself off but Console still "
4470 "thinks it is running. Notifying.\n"));
4471
4472 /* prevent powerDown() from calling VMR3PowerOff() again */
4473 that->setMachineState (MachineState_Stopping);
4474
4475 /*
4476 * Setup task object and thread to carry out the operation
4477 * asynchronously (if we call powerDown() right here but there
4478 * is one or more mpVM callers (added with addVMCaller()) we'll
4479 * deadlock.
4480 */
4481 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
4482 /*
4483 * If creating a task is falied, this can currently mean one
4484 * of two: either Console::uninit() has been called just a ms
4485 * before (so a powerDown() call is already on the way), or
4486 * powerDown() itself is being already executed. Just do
4487 * nothing .
4488 */
4489 if (!task->isOk())
4490 {
4491 LogFlowFunc (("Console is already being uninitialized.\n"));
4492 break;
4493 }
4494
4495 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
4496 (void *) task.get(), 0,
4497 RTTHREADTYPE_MAIN_WORKER, 0,
4498 "VMPowerDowm");
4499
4500 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
4501 if (VBOX_FAILURE (vrc))
4502 break;
4503
4504 /* task is now owned by powerDownThread(), so release it */
4505 task.release();
4506 }
4507 break;
4508 }
4509
4510 /*
4511 * The VM has been completely destroyed.
4512 *
4513 * Note: This state change can happen at two points:
4514 * 1) At the end of VMR3Destroy() if it was not called from EMT.
4515 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
4516 * called by EMT.
4517 */
4518 case VMSTATE_TERMINATED:
4519 {
4520 AutoLock alock (that);
4521
4522 if (that->mVMStateChangeCallbackDisabled)
4523 break;
4524
4525 /*
4526 * Terminate host interface networking. If aVM is NULL, we've been
4527 * manually called from powerUpThread() either before calling
4528 * VMR3Create() or after VMR3Create() failed, so no need to touch
4529 * networking.
4530 */
4531 if (aVM)
4532 that->powerDownHostInterfaces();
4533
4534 /*
4535 * From now on the machine is officially powered down or
4536 * remains in the Saved state.
4537 */
4538 switch (that->mMachineState)
4539 {
4540 default:
4541 AssertFailed();
4542 /* fall through */
4543 case MachineState_Stopping:
4544 /* successfully powered down */
4545 that->setMachineState (MachineState_PoweredOff);
4546 break;
4547 case MachineState_Saving:
4548 /*
4549 * successfully saved (note that the machine is already
4550 * in the Saved state on the server due to EndSavingState()
4551 * called from saveStateThread(), so only change the local
4552 * state)
4553 */
4554 that->setMachineStateLocally (MachineState_Saved);
4555 break;
4556 case MachineState_Starting:
4557 /*
4558 * failed to start, but be patient: set back to PoweredOff
4559 * (for similarity with the below)
4560 */
4561 that->setMachineState (MachineState_PoweredOff);
4562 break;
4563 case MachineState_Restoring:
4564 /*
4565 * failed to load the saved state file, but be patient:
4566 * set back to Saved (to preserve the saved state file)
4567 */
4568 that->setMachineState (MachineState_Saved);
4569 break;
4570 }
4571
4572 break;
4573 }
4574
4575 case VMSTATE_SUSPENDED:
4576 {
4577 if (aOldState == VMSTATE_RUNNING)
4578 {
4579 AutoLock alock (that);
4580
4581 if (that->mVMStateChangeCallbackDisabled)
4582 break;
4583
4584 /* Change the machine state from Running to Paused */
4585 Assert (that->mMachineState == MachineState_Running);
4586 that->setMachineState (MachineState_Paused);
4587 }
4588
4589 break;
4590 }
4591
4592 case VMSTATE_RUNNING:
4593 {
4594 if (aOldState == VMSTATE_CREATED ||
4595 aOldState == VMSTATE_SUSPENDED)
4596 {
4597 AutoLock alock (that);
4598
4599 if (that->mVMStateChangeCallbackDisabled)
4600 break;
4601
4602 /*
4603 * Change the machine state from Starting, Restoring or Paused
4604 * to Running
4605 */
4606 Assert ((that->mMachineState == MachineState_Starting &&
4607 aOldState == VMSTATE_CREATED) ||
4608 ((that->mMachineState == MachineState_Restoring ||
4609 that->mMachineState == MachineState_Paused) &&
4610 aOldState == VMSTATE_SUSPENDED));
4611
4612 that->setMachineState (MachineState_Running);
4613 }
4614
4615 break;
4616 }
4617
4618 case VMSTATE_GURU_MEDITATION:
4619 {
4620 AutoLock alock (that);
4621
4622 if (that->mVMStateChangeCallbackDisabled)
4623 break;
4624
4625 /* Guru respects only running VMs */
4626 Assert ((that->mMachineState >= MachineState_Running));
4627
4628 that->setMachineState (MachineState_Stuck);
4629
4630 break;
4631 }
4632
4633 default: /* shut up gcc */
4634 break;
4635 }
4636}
4637
4638#ifdef VBOX_WITH_USB
4639
4640/**
4641 * Sends a request to VMM to attach the given host device.
4642 * After this method succeeds, the attached device will appear in the
4643 * mUSBDevices collection.
4644 *
4645 * @param aHostDevice device to attach
4646 *
4647 * @note Synchronously calls EMT.
4648 * @note Must be called from under this object's lock.
4649 */
4650HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, ULONG aMaskedIfs)
4651{
4652 AssertReturn (aHostDevice, E_FAIL);
4653 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4654
4655 /* still want a lock object because we need to leave it */
4656 AutoLock alock (this);
4657
4658 HRESULT hrc;
4659
4660 /*
4661 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
4662 * method in EMT (using usbAttachCallback()).
4663 */
4664 Bstr BstrAddress;
4665 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
4666 ComAssertComRCRetRC (hrc);
4667
4668 Utf8Str Address (BstrAddress);
4669
4670 Guid Uuid;
4671 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
4672 ComAssertComRCRetRC (hrc);
4673
4674 BOOL fRemote = FALSE;
4675 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
4676 ComAssertComRCRetRC (hrc);
4677
4678 /* protect mpVM */
4679 AutoVMCaller autoVMCaller (this);
4680 CheckComRCReturnRC (autoVMCaller.rc());
4681
4682 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
4683 Address.raw(), Uuid.ptr()));
4684
4685 /* leave the lock before a VMR3* call (EMT will call us back)! */
4686 alock.leave();
4687
4688/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
4689 PVMREQ pReq = NULL;
4690 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4691 (PFNRT) usbAttachCallback, 6, this, aHostDevice, Uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
4692 if (VBOX_SUCCESS (vrc))
4693 vrc = pReq->iStatus;
4694 VMR3ReqFree (pReq);
4695
4696 /* restore the lock */
4697 alock.enter();
4698
4699 /* hrc is S_OK here */
4700
4701 if (VBOX_FAILURE (vrc))
4702 {
4703 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
4704 Address.raw(), Uuid.ptr(), vrc));
4705
4706 switch (vrc)
4707 {
4708 case VERR_VUSB_NO_PORTS:
4709 hrc = setError (E_FAIL,
4710 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
4711 break;
4712 case VERR_VUSB_USBFS_PERMISSION:
4713 hrc = setError (E_FAIL,
4714 tr ("Not permitted to open the USB device, check usbfs options"));
4715 break;
4716 default:
4717 hrc = setError (E_FAIL,
4718 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
4719 break;
4720 }
4721 }
4722
4723 return hrc;
4724}
4725
4726/**
4727 * USB device attach callback used by AttachUSBDevice().
4728 * Note that AttachUSBDevice() doesn't return until this callback is executed,
4729 * so we don't use AutoCaller and don't care about reference counters of
4730 * interface pointers passed in.
4731 *
4732 * @thread EMT
4733 * @note Locks the console object for writing.
4734 */
4735//static
4736DECLCALLBACK(int)
4737Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
4738{
4739 LogFlowFuncEnter();
4740 LogFlowFunc (("that={%p}\n", that));
4741
4742 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
4743
4744 void *pvRemoteBackend = NULL;
4745 if (aRemote)
4746 {
4747 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
4748 Guid guid (*aUuid);
4749
4750 pvRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
4751 if (!pvRemoteBackend)
4752 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
4753 }
4754
4755 USHORT portVersion = 1;
4756 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
4757 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
4758 Assert(portVersion == 1 || portVersion == 2);
4759
4760 int vrc = PDMR3USBCreateProxyDevice (that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
4761 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
4762 if (VBOX_SUCCESS (vrc))
4763 {
4764 /* Create a OUSBDevice and add it to the device list */
4765 ComObjPtr <OUSBDevice> device;
4766 device.createObject();
4767 HRESULT hrc = device->init (aHostDevice);
4768 AssertComRC (hrc);
4769
4770 AutoLock alock (that);
4771 that->mUSBDevices.push_back (device);
4772 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
4773
4774 /* notify callbacks */
4775 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
4776 }
4777
4778 LogFlowFunc (("vrc=%Vrc\n", vrc));
4779 LogFlowFuncLeave();
4780 return vrc;
4781}
4782
4783/**
4784 * Sends a request to VMM to detach the given host device. After this method
4785 * succeeds, the detached device will disappear from the mUSBDevices
4786 * collection.
4787 *
4788 * @param aIt Iterator pointing to the device to detach.
4789 *
4790 * @note Synchronously calls EMT.
4791 * @note Must be called from under this object's lock.
4792 */
4793HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
4794{
4795 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4796
4797 /* still want a lock object because we need to leave it */
4798 AutoLock alock (this);
4799
4800 /* protect mpVM */
4801 AutoVMCaller autoVMCaller (this);
4802 CheckComRCReturnRC (autoVMCaller.rc());
4803
4804 /* if the device is attached, then there must at least one USB hub. */
4805 AssertReturn (PDMR3USBHasHub (mpVM), E_FAIL);
4806
4807 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
4808 (*aIt)->id().raw()));
4809
4810 /* leave the lock before a VMR3* call (EMT will call us back)! */
4811 alock.leave();
4812
4813 PVMREQ pReq;
4814/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
4815 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4816 (PFNRT) usbDetachCallback, 4,
4817 this, &aIt, (*aIt)->id().raw());
4818 if (VBOX_SUCCESS (vrc))
4819 vrc = pReq->iStatus;
4820 VMR3ReqFree (pReq);
4821
4822 ComAssertRCRet (vrc, E_FAIL);
4823
4824 return S_OK;
4825}
4826
4827/**
4828 * USB device detach callback used by DetachUSBDevice().
4829 * Note that DetachUSBDevice() doesn't return until this callback is executed,
4830 * so we don't use AutoCaller and don't care about reference counters of
4831 * interface pointers passed in.
4832 *
4833 * @thread EMT
4834 * @note Locks the console object for writing.
4835 */
4836//static
4837DECLCALLBACK(int)
4838Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
4839{
4840 LogFlowFuncEnter();
4841 LogFlowFunc (("that={%p}\n", that));
4842
4843 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
4844
4845 /*
4846 * If that was a remote device, release the backend pointer.
4847 * The pointer was requested in usbAttachCallback.
4848 */
4849 BOOL fRemote = FALSE;
4850
4851 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
4852 ComAssertComRC (hrc2);
4853
4854 if (fRemote)
4855 {
4856 Guid guid (*aUuid);
4857 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
4858 }
4859
4860 int vrc = PDMR3USBDetachDevice (that->mpVM, aUuid);
4861
4862 if (VBOX_SUCCESS (vrc))
4863 {
4864 AutoLock alock (that);
4865
4866 /* Remove the device from the collection */
4867 that->mUSBDevices.erase (*aIt);
4868 LogFlowFunc (("Detached device {%Vuuid}\n", (**aIt)->id().raw()));
4869
4870 /* notify callbacks */
4871 that->onUSBDeviceStateChange (**aIt, false /* aAttached */, NULL);
4872 }
4873
4874 LogFlowFunc (("vrc=%Vrc\n", vrc));
4875 LogFlowFuncLeave();
4876 return vrc;
4877}
4878
4879#endif /* VBOX_WITH_USB */
4880
4881/**
4882 * Call the initialisation script for a dynamic TAP interface.
4883 *
4884 * The initialisation script should create a TAP interface, set it up and write its name to
4885 * standard output followed by a carriage return. Anything further written to standard
4886 * output will be ignored. If it returns a non-zero exit code, or does not write an
4887 * intelligable interface name to standard output, it will be treated as having failed.
4888 * For now, this method only works on Linux.
4889 *
4890 * @returns COM status code
4891 * @param tapDevice string to store the name of the tap device created to
4892 * @param tapSetupApplication the name of the setup script
4893 */
4894HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
4895 Bstr &tapSetupApplication)
4896{
4897 LogFlowThisFunc(("\n"));
4898#ifdef RT_OS_LINUX
4899 /* Command line to start the script with. */
4900 char szCommand[4096];
4901 /* Result code */
4902 int rc;
4903
4904 /* Get the script name. */
4905 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
4906 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
4907 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
4908 /*
4909 * Create the process and read its output.
4910 */
4911 Log2(("About to start the TAP setup script with the following command line: %s\n",
4912 szCommand));
4913 FILE *pfScriptHandle = popen(szCommand, "r");
4914 if (pfScriptHandle == 0)
4915 {
4916 int iErr = errno;
4917 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
4918 szCommand, strerror(iErr)));
4919 LogFlowThisFunc(("rc=E_FAIL\n"));
4920 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
4921 szCommand, strerror(iErr));
4922 }
4923 /* If we are using a dynamic TAP interface, we need to get the interface name. */
4924 if (!isStatic)
4925 {
4926 /* Buffer to read the application output to. It doesn't have to be long, as we are only
4927 interested in the first few (normally 5 or 6) bytes. */
4928 char acBuffer[64];
4929 /* The length of the string returned by the application. We only accept strings of 63
4930 characters or less. */
4931 size_t cBufSize;
4932
4933 /* Read the name of the device from the application. */
4934 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
4935 cBufSize = strlen(acBuffer);
4936 /* The script must return the name of the interface followed by a carriage return as the
4937 first line of its output. We need a null-terminated string. */
4938 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
4939 {
4940 pclose(pfScriptHandle);
4941 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
4942 LogFlowThisFunc(("rc=E_FAIL\n"));
4943 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
4944 }
4945 /* Overwrite the terminating newline character. */
4946 acBuffer[cBufSize - 1] = 0;
4947 tapDevice = acBuffer;
4948 }
4949 rc = pclose(pfScriptHandle);
4950 if (!WIFEXITED(rc))
4951 {
4952 LogRel(("The TAP interface setup script terminated abnormally.\n"));
4953 LogFlowThisFunc(("rc=E_FAIL\n"));
4954 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
4955 }
4956 if (WEXITSTATUS(rc) != 0)
4957 {
4958 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
4959 LogFlowThisFunc(("rc=E_FAIL\n"));
4960 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
4961 }
4962 LogFlowThisFunc(("rc=S_OK\n"));
4963 return S_OK;
4964#else /* RT_OS_LINUX not defined */
4965 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
4966 return E_NOTIMPL; /* not yet supported */
4967#endif
4968}
4969
4970/**
4971 * Helper function to handle host interface device creation and attachment.
4972 *
4973 * @param networkAdapter the network adapter which attachment should be reset
4974 * @return COM status code
4975 *
4976 * @note The caller must lock this object for writing.
4977 */
4978HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
4979{
4980 LogFlowThisFunc(("\n"));
4981 /* sanity check */
4982 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4983
4984#ifdef DEBUG
4985 /* paranoia */
4986 NetworkAttachmentType_T attachment;
4987 networkAdapter->COMGETTER(AttachmentType)(&attachment);
4988 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
4989#endif /* DEBUG */
4990
4991 HRESULT rc = S_OK;
4992
4993#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
4994 ULONG slot = 0;
4995 rc = networkAdapter->COMGETTER(Slot)(&slot);
4996 AssertComRC(rc);
4997
4998 /*
4999 * Try get the FD.
5000 */
5001 LONG ltapFD;
5002 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5003 if (SUCCEEDED(rc))
5004 maTapFD[slot] = (RTFILE)ltapFD;
5005 else
5006 maTapFD[slot] = NIL_RTFILE;
5007
5008 /*
5009 * Are we supposed to use an existing TAP interface?
5010 */
5011 if (maTapFD[slot] != NIL_RTFILE)
5012 {
5013 /* nothing to do */
5014 Assert(ltapFD >= 0);
5015 Assert((LONG)maTapFD[slot] == ltapFD);
5016 rc = S_OK;
5017 }
5018 else
5019#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5020 {
5021 /*
5022 * Allocate a host interface device
5023 */
5024#ifdef RT_OS_WINDOWS
5025 /* nothing to do */
5026 int rcVBox = VINF_SUCCESS;
5027#elif defined(RT_OS_LINUX)
5028 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5029 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5030 if (VBOX_SUCCESS(rcVBox))
5031 {
5032 /*
5033 * Set/obtain the tap interface.
5034 */
5035 bool isStatic = false;
5036 struct ifreq IfReq;
5037 memset(&IfReq, 0, sizeof(IfReq));
5038 /* The name of the TAP interface we are using and the TAP setup script resp. */
5039 Bstr tapDeviceName, tapSetupApplication;
5040 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5041 if (FAILED(rc))
5042 {
5043 tapDeviceName.setNull(); /* Is this necessary? */
5044 }
5045 else if (!tapDeviceName.isEmpty())
5046 {
5047 isStatic = true;
5048 /* If we are using a static TAP device then try to open it. */
5049 Utf8Str str(tapDeviceName);
5050 if (str.length() <= sizeof(IfReq.ifr_name))
5051 strcpy(IfReq.ifr_name, str.raw());
5052 else
5053 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5054 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5055 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5056 if (rcVBox != 0)
5057 {
5058 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5059 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5060 tapDeviceName.raw());
5061 }
5062 }
5063 if (SUCCEEDED(rc))
5064 {
5065 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5066 if (tapSetupApplication.isEmpty())
5067 {
5068 if (tapDeviceName.isEmpty())
5069 {
5070 LogRel(("No setup application was supplied for the TAP interface.\n"));
5071 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5072 }
5073 }
5074 else
5075 {
5076 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5077 tapSetupApplication);
5078 }
5079 }
5080 if (SUCCEEDED(rc))
5081 {
5082 if (!isStatic)
5083 {
5084 Utf8Str str(tapDeviceName);
5085 if (str.length() <= sizeof(IfReq.ifr_name))
5086 strcpy(IfReq.ifr_name, str.raw());
5087 else
5088 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5089 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5090 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5091 if (rcVBox != 0)
5092 {
5093 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5094 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5095 }
5096 }
5097 if (SUCCEEDED(rc))
5098 {
5099 /*
5100 * Make it pollable.
5101 */
5102 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5103 {
5104 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5105
5106 /*
5107 * Here is the right place to communicate the TAP file descriptor and
5108 * the host interface name to the server if/when it becomes really
5109 * necessary.
5110 */
5111 maTAPDeviceName[slot] = tapDeviceName;
5112 rcVBox = VINF_SUCCESS;
5113 }
5114 else
5115 {
5116 int iErr = errno;
5117
5118 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5119 rcVBox = VERR_HOSTIF_BLOCKING;
5120 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5121 strerror(errno));
5122 }
5123 }
5124 }
5125 }
5126 else
5127 {
5128 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5129 switch (rcVBox)
5130 {
5131 case VERR_ACCESS_DENIED:
5132 /* will be handled by our caller */
5133 rc = rcVBox;
5134 break;
5135 default:
5136 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
5137 break;
5138 }
5139 }
5140#elif defined(RT_OS_DARWIN)
5141 /** @todo Implement tap networking for Darwin. */
5142 int rcVBox = VERR_NOT_IMPLEMENTED;
5143#elif defined(RT_OS_FREEBSD)
5144 /** @todo Implement tap networking for FreeBSD. */
5145 int rcVBox = VERR_NOT_IMPLEMENTED;
5146#elif defined(RT_OS_OS2)
5147 /** @todo Implement tap networking for OS/2. */
5148 int rcVBox = VERR_NOT_IMPLEMENTED;
5149#elif defined(RT_OS_SOLARIS)
5150 /* nothing to do */
5151 int rcVBox = VINF_SUCCESS;
5152#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
5153# error "PORTME: Implement OS specific TAP interface open/creation."
5154#else
5155# error "Unknown host OS"
5156#endif
5157 /* in case of failure, cleanup. */
5158 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5159 {
5160 LogRel(("General failure attaching to host interface\n"));
5161 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5162 }
5163 }
5164 LogFlowThisFunc(("rc=%d\n", rc));
5165 return rc;
5166}
5167
5168/**
5169 * Helper function to handle detachment from a host interface
5170 *
5171 * @param networkAdapter the network adapter which attachment should be reset
5172 * @return COM status code
5173 *
5174 * @note The caller must lock this object for writing.
5175 */
5176HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5177{
5178 /* sanity check */
5179 LogFlowThisFunc(("\n"));
5180 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5181
5182 HRESULT rc = S_OK;
5183#ifdef DEBUG
5184 /* paranoia */
5185 NetworkAttachmentType_T attachment;
5186 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5187 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5188#endif /* DEBUG */
5189
5190#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5191
5192 ULONG slot = 0;
5193 rc = networkAdapter->COMGETTER(Slot)(&slot);
5194 AssertComRC(rc);
5195
5196 /* is there an open TAP device? */
5197 if (maTapFD[slot] != NIL_RTFILE)
5198 {
5199 /*
5200 * Close the file handle.
5201 */
5202 Bstr tapDeviceName, tapTerminateApplication;
5203 bool isStatic = true;
5204 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5205 if (FAILED(rc) || tapDeviceName.isEmpty())
5206 {
5207 /* If the name is empty, this is a dynamic TAP device, so close it now,
5208 so that the termination script can remove the interface. Otherwise we still
5209 need the FD to pass to the termination script. */
5210 isStatic = false;
5211 int rcVBox = RTFileClose(maTapFD[slot]);
5212 AssertRC(rcVBox);
5213 maTapFD[slot] = NIL_RTFILE;
5214 }
5215 /*
5216 * Execute the termination command.
5217 */
5218 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5219 if (tapTerminateApplication)
5220 {
5221 /* Get the program name. */
5222 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5223
5224 /* Build the command line. */
5225 char szCommand[4096];
5226 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
5227 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
5228
5229 /*
5230 * Create the process and wait for it to complete.
5231 */
5232 Log(("Calling the termination command: %s\n", szCommand));
5233 int rcCommand = system(szCommand);
5234 if (rcCommand == -1)
5235 {
5236 LogRel(("Failed to execute the clean up script for the TAP interface"));
5237 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
5238 }
5239 if (!WIFEXITED(rc))
5240 {
5241 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
5242 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
5243 }
5244 if (WEXITSTATUS(rc) != 0)
5245 {
5246 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
5247 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
5248 }
5249 }
5250
5251 if (isStatic)
5252 {
5253 /* If we are using a static TAP device, we close it now, after having called the
5254 termination script. */
5255 int rcVBox = RTFileClose(maTapFD[slot]);
5256 AssertRC(rcVBox);
5257 }
5258 /* the TAP device name and handle are no longer valid */
5259 maTapFD[slot] = NIL_RTFILE;
5260 maTAPDeviceName[slot] = "";
5261 }
5262#endif
5263 LogFlowThisFunc(("returning %d\n", rc));
5264 return rc;
5265}
5266
5267
5268/**
5269 * Called at power down to terminate host interface networking.
5270 *
5271 * @note The caller must lock this object for writing.
5272 */
5273HRESULT Console::powerDownHostInterfaces()
5274{
5275 LogFlowThisFunc (("\n"));
5276
5277 /* sanity check */
5278 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5279
5280 /*
5281 * host interface termination handling
5282 */
5283 HRESULT rc;
5284 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
5285 {
5286 ComPtr<INetworkAdapter> networkAdapter;
5287 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
5288 CheckComRCBreakRC (rc);
5289
5290 BOOL enabled = FALSE;
5291 networkAdapter->COMGETTER(Enabled) (&enabled);
5292 if (!enabled)
5293 continue;
5294
5295 NetworkAttachmentType_T attachment;
5296 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5297 if (attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment)
5298 {
5299 HRESULT rc2 = detachFromHostInterface(networkAdapter);
5300 if (FAILED(rc2) && SUCCEEDED(rc))
5301 rc = rc2;
5302 }
5303 }
5304
5305 return rc;
5306}
5307
5308
5309/**
5310 * Process callback handler for VMR3Load and VMR3Save.
5311 *
5312 * @param pVM The VM handle.
5313 * @param uPercent Completetion precentage (0-100).
5314 * @param pvUser Pointer to the VMProgressTask structure.
5315 * @return VINF_SUCCESS.
5316 */
5317/*static*/ DECLCALLBACK (int)
5318Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
5319{
5320 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5321 AssertReturn (task, VERR_INVALID_PARAMETER);
5322
5323 /* update the progress object */
5324 if (task->mProgress)
5325 task->mProgress->notifyProgress (uPercent);
5326
5327 return VINF_SUCCESS;
5328}
5329
5330/**
5331 * VM error callback function. Called by the various VM components.
5332 *
5333 * @param pVM VM handle. Can be NULL if an error occurred before
5334 * successfully creating a VM.
5335 * @param pvUser Pointer to the VMProgressTask structure.
5336 * @param rc VBox status code.
5337 * @param pszFormat Printf-like error message.
5338 * @param args Various number of argumens for the error message.
5339 *
5340 * @thread EMT, VMPowerUp...
5341 *
5342 * @note The VMProgressTask structure modified by this callback is not thread
5343 * safe.
5344 */
5345/* static */ DECLCALLBACK (void)
5346Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
5347 const char *pszFormat, va_list args)
5348{
5349 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5350 AssertReturnVoid (task);
5351
5352 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
5353 va_list va2;
5354 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
5355 Utf8Str errorMsg = Utf8StrFmt (tr ("%N.\n"
5356 "VBox status code: %d (%Vrc)"),
5357 pszFormat, &va2, rc, rc);
5358 va_end(va2);
5359
5360 /* For now, this may be called only once. Ignore subsequent calls. */
5361 AssertMsgReturnVoid (task->mErrorMsg.isNull(),
5362 ("Cannot set error to '%s': it is already set to '%s'",
5363 errorMsg.raw(), task->mErrorMsg.raw()));
5364
5365 task->mErrorMsg = errorMsg;
5366}
5367
5368/**
5369 * VM runtime error callback function.
5370 * See VMSetRuntimeError for the detailed description of parameters.
5371 *
5372 * @param pVM The VM handle.
5373 * @param pvUser The user argument.
5374 * @param fFatal Whether it is a fatal error or not.
5375 * @param pszErrorID Error ID string.
5376 * @param pszFormat Error message format string.
5377 * @param args Error message arguments.
5378 * @thread EMT.
5379 */
5380/* static */ DECLCALLBACK(void)
5381Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
5382 const char *pszErrorID,
5383 const char *pszFormat, va_list args)
5384{
5385 LogFlowFuncEnter();
5386
5387 Console *that = static_cast <Console *> (pvUser);
5388 AssertReturnVoid (that);
5389
5390 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
5391
5392 LogRel (("Console: VM runtime error: fatal=%RTbool, "
5393 "errorID=%s message=\"%s\"\n",
5394 fFatal, pszErrorID, message.raw()));
5395
5396 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
5397
5398 LogFlowFuncLeave();
5399}
5400
5401/**
5402 * Captures USB devices that match filters of the VM.
5403 * Called at VM startup.
5404 *
5405 * @param pVM The VM handle.
5406 *
5407 * @note The caller must lock this object for writing.
5408 */
5409HRESULT Console::captureUSBDevices (PVM pVM)
5410{
5411 LogFlowThisFunc (("\n"));
5412
5413 /* sanity check */
5414 ComAssertRet (isLockedOnCurrentThread(), E_FAIL);
5415
5416 /* If the machine has an USB controller, ask the USB proxy service to
5417 * capture devices */
5418 PPDMIBASE pBase;
5419 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
5420 if (VBOX_SUCCESS (vrc))
5421 {
5422 /* leave the lock before calling Host in VBoxSVC since Host may call
5423 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5424 * produce an inter-process dead-lock otherwise. */
5425 AutoLock alock (this);
5426 alock.leave();
5427
5428 HRESULT hrc = mControl->AutoCaptureUSBDevices();
5429 ComAssertComRCRetRC (hrc);
5430 }
5431 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
5432 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
5433 vrc = VINF_SUCCESS;
5434 else
5435 AssertRC (vrc);
5436
5437 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
5438}
5439
5440
5441/**
5442 * Detach all USB device which are attached to the VM for the
5443 * purpose of clean up and such like.
5444 *
5445 * @note The caller must lock this object for writing.
5446 */
5447void Console::detachAllUSBDevices (bool aDone)
5448{
5449 LogFlowThisFunc (("\n"));
5450
5451 /* sanity check */
5452 AssertReturnVoid (isLockedOnCurrentThread());
5453
5454 mUSBDevices.clear();
5455
5456 /* leave the lock before calling Host in VBoxSVC since Host may call
5457 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5458 * produce an inter-process dead-lock otherwise. */
5459 AutoLock alock (this);
5460 alock.leave();
5461
5462 mControl->DetachAllUSBDevices (aDone);
5463}
5464
5465/**
5466 * @note Locks this object for writing.
5467 */
5468void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
5469{
5470 LogFlowThisFuncEnter();
5471 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
5472
5473 AutoCaller autoCaller (this);
5474 if (!autoCaller.isOk())
5475 {
5476 /* Console has been already uninitialized, deny request */
5477 AssertMsgFailed (("Temporary assertion to prove that it happens, "
5478 "please report to dmik\n"));
5479 LogFlowThisFunc (("Console is already uninitialized\n"));
5480 LogFlowThisFuncLeave();
5481 return;
5482 }
5483
5484 AutoLock alock (this);
5485
5486 /*
5487 * Mark all existing remote USB devices as dirty.
5488 */
5489 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
5490 while (it != mRemoteUSBDevices.end())
5491 {
5492 (*it)->dirty (true);
5493 ++ it;
5494 }
5495
5496 /*
5497 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
5498 */
5499 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
5500 VRDPUSBDEVICEDESC *e = pDevList;
5501
5502 /* The cbDevList condition must be checked first, because the function can
5503 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
5504 */
5505 while (cbDevList >= 2 && e->oNext)
5506 {
5507 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
5508 e->idVendor, e->idProduct,
5509 e->oProduct? (char *)e + e->oProduct: ""));
5510
5511 bool fNewDevice = true;
5512
5513 it = mRemoteUSBDevices.begin();
5514 while (it != mRemoteUSBDevices.end())
5515 {
5516 if ((*it)->devId () == e->id
5517 && (*it)->clientId () == u32ClientId)
5518 {
5519 /* The device is already in the list. */
5520 (*it)->dirty (false);
5521 fNewDevice = false;
5522 break;
5523 }
5524
5525 ++ it;
5526 }
5527
5528 if (fNewDevice)
5529 {
5530 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
5531 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
5532 ));
5533
5534 /* Create the device object and add the new device to list. */
5535 ComObjPtr <RemoteUSBDevice> device;
5536 device.createObject();
5537 device->init (u32ClientId, e);
5538
5539 mRemoteUSBDevices.push_back (device);
5540
5541 /* Check if the device is ok for current USB filters. */
5542 BOOL fMatched = FALSE;
5543 ULONG fMaskedIfs = 0;
5544
5545 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
5546
5547 AssertComRC (hrc);
5548
5549 LogFlowThisFunc (("USB filters return %d %#x\n", fMatched, fMaskedIfs));
5550
5551 if (fMatched)
5552 {
5553 hrc = onUSBDeviceAttach (device, NULL, fMaskedIfs);
5554
5555 /// @todo (r=dmik) warning reporting subsystem
5556
5557 if (hrc == S_OK)
5558 {
5559 LogFlowThisFunc (("Device attached\n"));
5560 device->captured (true);
5561 }
5562 }
5563 }
5564
5565 if (cbDevList < e->oNext)
5566 {
5567 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
5568 cbDevList, e->oNext));
5569 break;
5570 }
5571
5572 cbDevList -= e->oNext;
5573
5574 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
5575 }
5576
5577 /*
5578 * Remove dirty devices, that is those which are not reported by the server anymore.
5579 */
5580 for (;;)
5581 {
5582 ComObjPtr <RemoteUSBDevice> device;
5583
5584 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
5585 while (it != mRemoteUSBDevices.end())
5586 {
5587 if ((*it)->dirty ())
5588 {
5589 device = *it;
5590 break;
5591 }
5592
5593 ++ it;
5594 }
5595
5596 if (!device)
5597 {
5598 break;
5599 }
5600
5601 USHORT vendorId = 0;
5602 device->COMGETTER(VendorId) (&vendorId);
5603
5604 USHORT productId = 0;
5605 device->COMGETTER(ProductId) (&productId);
5606
5607 Bstr product;
5608 device->COMGETTER(Product) (product.asOutParam());
5609
5610 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
5611 vendorId, productId, product.raw ()
5612 ));
5613
5614 /* Detach the device from VM. */
5615 if (device->captured ())
5616 {
5617 Guid uuid;
5618 device->COMGETTER (Id) (uuid.asOutParam());
5619 onUSBDeviceDetach (uuid, NULL);
5620 }
5621
5622 /* And remove it from the list. */
5623 mRemoteUSBDevices.erase (it);
5624 }
5625
5626 LogFlowThisFuncLeave();
5627}
5628
5629
5630
5631/**
5632 * Thread function which starts the VM (also from saved state) and
5633 * track progress.
5634 *
5635 * @param Thread The thread id.
5636 * @param pvUser Pointer to a VMPowerUpTask structure.
5637 * @return VINF_SUCCESS (ignored).
5638 *
5639 * @note Locks the Console object for writing.
5640 */
5641/*static*/
5642DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
5643{
5644 LogFlowFuncEnter();
5645
5646 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
5647 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
5648
5649 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
5650 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
5651
5652#if defined(RT_OS_WINDOWS)
5653 {
5654 /* initialize COM */
5655 HRESULT hrc = CoInitializeEx (NULL,
5656 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
5657 COINIT_SPEED_OVER_MEMORY);
5658 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
5659 }
5660#endif
5661
5662 HRESULT hrc = S_OK;
5663 int vrc = VINF_SUCCESS;
5664
5665 /* Set up a build identifier so that it can be seen from core dumps what
5666 * exact build was used to produce the core. */
5667 static char saBuildID[40];
5668 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
5669 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBoxSVNRev (), "BU", "IL", "DI", "D");
5670
5671 ComObjPtr <Console> console = task->mConsole;
5672
5673 /* Note: no need to use addCaller() because VMPowerUpTask does that */
5674
5675 AutoLock alock (console);
5676
5677 /* sanity */
5678 Assert (console->mpVM == NULL);
5679
5680 do
5681 {
5682 /*
5683 * Initialize the release logging facility. In case something
5684 * goes wrong, there will be no release logging. Maybe in the future
5685 * we can add some logic to use different file names in this case.
5686 * Note that the logic must be in sync with Machine::DeleteSettings().
5687 */
5688
5689 Bstr logFolder;
5690 hrc = console->mMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
5691 CheckComRCBreakRC (hrc);
5692
5693 Utf8Str logDir = logFolder;
5694
5695 /* make sure the Logs folder exists */
5696 Assert (!logDir.isEmpty());
5697 if (!RTDirExists (logDir))
5698 RTDirCreateFullPath (logDir, 0777);
5699
5700 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
5701 logDir.raw(), RTPATH_DELIMITER);
5702 Utf8Str pngFile = Utf8StrFmt ("%s%cVBox.png",
5703 logDir.raw(), RTPATH_DELIMITER);
5704
5705 /*
5706 * Age the old log files
5707 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
5708 * Overwrite target files in case they exist.
5709 */
5710 ComPtr<IVirtualBox> virtualBox;
5711 console->mMachine->COMGETTER(Parent)(virtualBox.asOutParam());
5712 ComPtr <ISystemProperties> systemProperties;
5713 virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
5714 ULONG uLogHistoryCount = 3;
5715 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
5716 if (uLogHistoryCount)
5717 {
5718 for (int i = uLogHistoryCount-1; i >= 0; i--)
5719 {
5720 Utf8Str *files[] = { &logFile, &pngFile };
5721 Utf8Str oldName, newName;
5722
5723 for (unsigned int j = 0; j < ELEMENTS (files); ++ j)
5724 {
5725 if (i > 0)
5726 oldName = Utf8StrFmt ("%s.%d", files [j]->raw(), i);
5727 else
5728 oldName = *files [j];
5729 newName = Utf8StrFmt ("%s.%d", files [j]->raw(), i + 1);
5730 /* If the old file doesn't exist, delete the new file (if it
5731 * exists) to provide correct rotation even if the sequence is
5732 * broken */
5733 if (RTFileRename (oldName, newName, RTFILEMOVE_FLAGS_REPLACE) ==
5734 VERR_FILE_NOT_FOUND)
5735 RTFileDelete (newName);
5736 }
5737 }
5738 }
5739
5740 PRTLOGGER loggerRelease;
5741 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
5742 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
5743#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
5744 fFlags |= RTLOGFLAGS_USECRLF;
5745#endif
5746 char szError[RTPATH_MAX + 128] = "";
5747 vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
5748 "VBOX_RELEASE_LOG", ELEMENTS(s_apszGroups), s_apszGroups,
5749 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
5750 if (VBOX_SUCCESS(vrc))
5751 {
5752 /* some introductory information */
5753 RTTIMESPEC timeSpec;
5754 char nowUct[64];
5755 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
5756 RTLogRelLogger(loggerRelease, 0, ~0U,
5757 "VirtualBox %s r%d %s (%s %s) release log\n"
5758 "Log opened %s\n",
5759 VBOX_VERSION_STRING, VBoxSVNRev (), VBOX_BUILD_TARGET,
5760 __DATE__, __TIME__, nowUct);
5761
5762 /* register this logger as the release logger */
5763 RTLogRelSetDefaultInstance(loggerRelease);
5764 }
5765 else
5766 {
5767 hrc = setError (E_FAIL,
5768 tr ("Failed to open release log (%s, %Vrc)"), szError, vrc);
5769 break;
5770 }
5771
5772#ifdef VBOX_VRDP
5773 if (VBOX_SUCCESS (vrc))
5774 {
5775 /* Create the VRDP server. In case of headless operation, this will
5776 * also create the framebuffer, required at VM creation.
5777 */
5778 ConsoleVRDPServer *server = console->consoleVRDPServer();
5779 Assert (server);
5780 /// @todo (dmik)
5781 // does VRDP server call Console from the other thread?
5782 // Not sure, so leave the lock just in case
5783 alock.leave();
5784 vrc = server->Launch();
5785 alock.enter();
5786 if (VBOX_FAILURE (vrc))
5787 {
5788 Utf8Str errMsg;
5789 switch (vrc)
5790 {
5791 case VERR_NET_ADDRESS_IN_USE:
5792 {
5793 ULONG port = 0;
5794 console->mVRDPServer->COMGETTER(Port) (&port);
5795 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
5796 port);
5797 break;
5798 }
5799 default:
5800 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
5801 vrc);
5802 }
5803 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
5804 vrc, errMsg.raw()));
5805 hrc = setError (E_FAIL, errMsg);
5806 break;
5807 }
5808 }
5809#endif /* VBOX_VRDP */
5810
5811 /*
5812 * Create the VM
5813 */
5814 PVM pVM;
5815 /*
5816 * leave the lock since EMT will call Console. It's safe because
5817 * mMachineState is either Starting or Restoring state here.
5818 */
5819 alock.leave();
5820
5821 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
5822 task->mConfigConstructor, static_cast <Console *> (console),
5823 &pVM);
5824
5825 alock.enter();
5826
5827#ifdef VBOX_VRDP
5828 /* Enable client connections to the server. */
5829 console->consoleVRDPServer()->EnableConnections ();
5830#endif /* VBOX_VRDP */
5831
5832 if (VBOX_SUCCESS (vrc))
5833 {
5834 do
5835 {
5836 /*
5837 * Register our load/save state file handlers
5838 */
5839 vrc = SSMR3RegisterExternal (pVM,
5840 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
5841 0 /* cbGuess */,
5842 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
5843 static_cast <Console *> (console));
5844 AssertRC (vrc);
5845 if (VBOX_FAILURE (vrc))
5846 break;
5847
5848 /*
5849 * Synchronize debugger settings
5850 */
5851 MachineDebugger *machineDebugger = console->getMachineDebugger();
5852 if (machineDebugger)
5853 {
5854 machineDebugger->flushQueuedSettings();
5855 }
5856
5857 /*
5858 * Shared Folders
5859 */
5860 if (console->getVMMDev()->isShFlActive())
5861 {
5862 /// @todo (dmik)
5863 // does the code below call Console from the other thread?
5864 // Not sure, so leave the lock just in case
5865 alock.leave();
5866
5867 for (SharedFolderDataMap::const_iterator
5868 it = task->mSharedFolders.begin();
5869 it != task->mSharedFolders.end();
5870 ++ it)
5871 {
5872 hrc = console->createSharedFolder ((*it).first, (*it).second);
5873 CheckComRCBreakRC (hrc);
5874 }
5875
5876 /* enter the lock again */
5877 alock.enter();
5878
5879 CheckComRCBreakRC (hrc);
5880 }
5881
5882 /*
5883 * Capture USB devices.
5884 */
5885 hrc = console->captureUSBDevices (pVM);
5886 CheckComRCBreakRC (hrc);
5887
5888 /* leave the lock before a lengthy operation */
5889 alock.leave();
5890
5891 /* Load saved state? */
5892 if (!!task->mSavedStateFile)
5893 {
5894 LogFlowFunc (("Restoring saved state from '%s'...\n",
5895 task->mSavedStateFile.raw()));
5896
5897 vrc = VMR3Load (pVM, task->mSavedStateFile,
5898 Console::stateProgressCallback,
5899 static_cast <VMProgressTask *> (task.get()));
5900
5901 /* Start/Resume the VM execution */
5902 if (VBOX_SUCCESS (vrc))
5903 {
5904 vrc = VMR3Resume (pVM);
5905 AssertRC (vrc);
5906 }
5907
5908 /* Power off in case we failed loading or resuming the VM */
5909 if (VBOX_FAILURE (vrc))
5910 {
5911 int vrc2 = VMR3PowerOff (pVM);
5912 AssertRC (vrc2);
5913 }
5914 }
5915 else
5916 {
5917 /* Power on the VM (i.e. start executing) */
5918 vrc = VMR3PowerOn(pVM);
5919 AssertRC (vrc);
5920 }
5921
5922 /* enter the lock again */
5923 alock.enter();
5924 }
5925 while (0);
5926
5927 /* On failure, destroy the VM */
5928 if (FAILED (hrc) || VBOX_FAILURE (vrc))
5929 {
5930 /* preserve existing error info */
5931 ErrorInfoKeeper eik;
5932
5933 /* powerDown() will call VMR3Destroy() and do all necessary
5934 * cleanup (VRDP, USB devices) */
5935 HRESULT hrc2 = console->powerDown();
5936 AssertComRC (hrc2);
5937 }
5938 }
5939 else
5940 {
5941 /*
5942 * If VMR3Create() failed it has released the VM memory.
5943 */
5944 console->mpVM = NULL;
5945 }
5946
5947 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
5948 {
5949 /* If VMR3Create() or one of the other calls in this function fail,
5950 * an appropriate error message has been set in task->mErrorMsg.
5951 * However since that happens via a callback, the hrc status code in
5952 * this function is not updated.
5953 */
5954 if (task->mErrorMsg.isNull())
5955 {
5956 /* If the error message is not set but we've got a failure,
5957 * convert the VBox status code into a meaningfulerror message.
5958 * This becomes unused once all the sources of errors set the
5959 * appropriate error message themselves.
5960 */
5961 AssertMsgFailed (("Missing error message during powerup for "
5962 "status code %Vrc\n", vrc));
5963 task->mErrorMsg = Utf8StrFmt (
5964 tr ("Failed to start VM execution (%Vrc)"), vrc);
5965 }
5966
5967 /* Set the error message as the COM error.
5968 * Progress::notifyComplete() will pick it up later. */
5969 hrc = setError (E_FAIL, task->mErrorMsg);
5970 break;
5971 }
5972 }
5973 while (0);
5974
5975 if (console->mMachineState == MachineState_Starting ||
5976 console->mMachineState == MachineState_Restoring)
5977 {
5978 /* We are still in the Starting/Restoring state. This means one of:
5979 *
5980 * 1) we failed before VMR3Create() was called;
5981 * 2) VMR3Create() failed.
5982 *
5983 * In both cases, there is no need to call powerDown(), but we still
5984 * need to go back to the PoweredOff/Saved state. Reuse
5985 * vmstateChangeCallback() for that purpose.
5986 */
5987
5988 /* preserve existing error info */
5989 ErrorInfoKeeper eik;
5990
5991 Assert (console->mpVM == NULL);
5992 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
5993 console);
5994 }
5995
5996 /*
5997 * Evaluate the final result. Note that the appropriate mMachineState value
5998 * is already set by vmstateChangeCallback() in all cases.
5999 */
6000
6001 /* leave the lock, don't need it any more */
6002 alock.leave();
6003
6004 if (SUCCEEDED (hrc))
6005 {
6006 /* Notify the progress object of the success */
6007 task->mProgress->notifyComplete (S_OK);
6008 }
6009 else
6010 {
6011 /* The progress object will fetch the current error info */
6012 task->mProgress->notifyComplete (hrc);
6013
6014 LogRel (("Power up failed (vrc=%Vrc, hrc=0x%08X)\n", vrc, hrc));
6015 }
6016
6017#if defined(RT_OS_WINDOWS)
6018 /* uninitialize COM */
6019 CoUninitialize();
6020#endif
6021
6022 LogFlowFuncLeave();
6023
6024 return VINF_SUCCESS;
6025}
6026
6027
6028/**
6029 * Reconfigures a VDI.
6030 *
6031 * @param pVM The VM handle.
6032 * @param hda The harddisk attachment.
6033 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6034 * @return VBox status code.
6035 */
6036static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6037{
6038 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6039
6040 int rc;
6041 HRESULT hrc;
6042 char *psz = NULL;
6043 BSTR str = NULL;
6044 *phrc = S_OK;
6045#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
6046#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6047#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6048#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6049
6050 /*
6051 * Figure out which IDE device this is.
6052 */
6053 ComPtr<IHardDisk> hardDisk;
6054 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6055 DiskControllerType_T enmCtl;
6056 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
6057 LONG lDev;
6058 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
6059
6060 int i;
6061 switch (enmCtl)
6062 {
6063 case DiskControllerType_IDE0Controller:
6064 i = 0;
6065 break;
6066 case DiskControllerType_IDE1Controller:
6067 i = 2;
6068 break;
6069 default:
6070 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
6071 return VERR_GENERAL_FAILURE;
6072 }
6073
6074 if (lDev < 0 || lDev >= 2)
6075 {
6076 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6077 return VERR_GENERAL_FAILURE;
6078 }
6079
6080 i = i + lDev;
6081
6082 /*
6083 * Is there an existing LUN? If not create it.
6084 * We ASSUME that this will NEVER collide with the DVD.
6085 */
6086 PCFGMNODE pCfg;
6087 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", i);
6088 if (!pLunL1)
6089 {
6090 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6091 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6092
6093 PCFGMNODE pLunL0;
6094 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", i); RC_CHECK();
6095 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6096 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6097 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6098 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6099
6100 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6101 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6102 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6103 }
6104 else
6105 {
6106#ifdef VBOX_STRICT
6107 char *pszDriver;
6108 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6109 Assert(!strcmp(pszDriver, "VBoxHDD"));
6110 MMR3HeapFree(pszDriver);
6111#endif
6112
6113 /*
6114 * Check if things has changed.
6115 */
6116 pCfg = CFGMR3GetChild(pLunL1, "Config");
6117 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6118
6119 /* the image */
6120 /// @todo (dmik) we temporarily use the location property to
6121 // determine the image file name. This is subject to change
6122 // when iSCSI disks are here (we should either query a
6123 // storage-specific interface from IHardDisk, or "standardize"
6124 // the location property)
6125 hrc = hardDisk->COMGETTER(Location)(&str); H();
6126 STR_CONV();
6127 char *pszPath;
6128 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6129 if (!strcmp(psz, pszPath))
6130 {
6131 /* parent images. */
6132 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6133 for (PCFGMNODE pParent = pCfg;;)
6134 {
6135 MMR3HeapFree(pszPath);
6136 pszPath = NULL;
6137 STR_FREE();
6138
6139 /* get parent */
6140 ComPtr<IHardDisk> curHardDisk;
6141 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6142 PCFGMNODE pCur;
6143 pCur = CFGMR3GetChild(pParent, "Parent");
6144 if (!pCur && !curHardDisk)
6145 {
6146 /* no change */
6147 LogFlowFunc (("No change!\n"));
6148 return VINF_SUCCESS;
6149 }
6150 if (!pCur || !curHardDisk)
6151 break;
6152
6153 /* compare paths. */
6154 /// @todo (dmik) we temporarily use the location property to
6155 // determine the image file name. This is subject to change
6156 // when iSCSI disks are here (we should either query a
6157 // storage-specific interface from IHardDisk, or "standardize"
6158 // the location property)
6159 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6160 STR_CONV();
6161 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6162 if (strcmp(psz, pszPath))
6163 break;
6164
6165 /* next */
6166 pParent = pCur;
6167 parentHardDisk = curHardDisk;
6168 }
6169
6170 }
6171 else
6172 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", i, pszPath));
6173
6174 MMR3HeapFree(pszPath);
6175 STR_FREE();
6176
6177 /*
6178 * Detach the driver and replace the config node.
6179 */
6180 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, i); RC_CHECK();
6181 CFGMR3RemoveNode(pCfg);
6182 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6183 }
6184
6185 /*
6186 * Create the driver configuration.
6187 */
6188 /// @todo (dmik) we temporarily use the location property to
6189 // determine the image file name. This is subject to change
6190 // when iSCSI disks are here (we should either query a
6191 // storage-specific interface from IHardDisk, or "standardize"
6192 // the location property)
6193 hrc = hardDisk->COMGETTER(Location)(&str); H();
6194 STR_CONV();
6195 LogFlowFunc (("LUN#%d: leaf image '%s'\n", i, psz));
6196 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6197 STR_FREE();
6198 /* Create an inversed tree of parents. */
6199 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6200 for (PCFGMNODE pParent = pCfg;;)
6201 {
6202 ComPtr<IHardDisk> curHardDisk;
6203 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6204 if (!curHardDisk)
6205 break;
6206
6207 PCFGMNODE pCur;
6208 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6209 /// @todo (dmik) we temporarily use the location property to
6210 // determine the image file name. This is subject to change
6211 // when iSCSI disks are here (we should either query a
6212 // storage-specific interface from IHardDisk, or "standardize"
6213 // the location property)
6214 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6215 STR_CONV();
6216 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6217 STR_FREE();
6218
6219 /* next */
6220 pParent = pCur;
6221 parentHardDisk = curHardDisk;
6222 }
6223
6224 /*
6225 * Attach the new driver.
6226 */
6227 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, i, NULL); RC_CHECK();
6228
6229 LogFlowFunc (("Returns success\n"));
6230 return rc;
6231}
6232
6233
6234/**
6235 * Thread for executing the saved state operation.
6236 *
6237 * @param Thread The thread handle.
6238 * @param pvUser Pointer to a VMSaveTask structure.
6239 * @return VINF_SUCCESS (ignored).
6240 *
6241 * @note Locks the Console object for writing.
6242 */
6243/*static*/
6244DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6245{
6246 LogFlowFuncEnter();
6247
6248 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6249 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6250
6251 Assert (!task->mSavedStateFile.isNull());
6252 Assert (!task->mProgress.isNull());
6253
6254 const ComObjPtr <Console> &that = task->mConsole;
6255
6256 /*
6257 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6258 * protect mpVM because VMSaveTask does that
6259 */
6260
6261 Utf8Str errMsg;
6262 HRESULT rc = S_OK;
6263
6264 if (task->mIsSnapshot)
6265 {
6266 Assert (!task->mServerProgress.isNull());
6267 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6268
6269 rc = task->mServerProgress->WaitForCompletion (-1);
6270 if (SUCCEEDED (rc))
6271 {
6272 HRESULT result = S_OK;
6273 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6274 if (SUCCEEDED (rc))
6275 rc = result;
6276 }
6277 }
6278
6279 if (SUCCEEDED (rc))
6280 {
6281 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6282
6283 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6284 Console::stateProgressCallback,
6285 static_cast <VMProgressTask *> (task.get()));
6286 if (VBOX_FAILURE (vrc))
6287 {
6288 errMsg = Utf8StrFmt (
6289 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6290 task->mSavedStateFile.raw(), vrc);
6291 rc = E_FAIL;
6292 }
6293 }
6294
6295 /* lock the console sonce we're going to access it */
6296 AutoLock thatLock (that);
6297
6298 if (SUCCEEDED (rc))
6299 {
6300 if (task->mIsSnapshot)
6301 do
6302 {
6303 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
6304
6305 ComPtr <IHardDiskAttachmentCollection> hdaColl;
6306 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
6307 if (FAILED (rc))
6308 break;
6309 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
6310 rc = hdaColl->Enumerate (hdaEn.asOutParam());
6311 if (FAILED (rc))
6312 break;
6313 BOOL more = FALSE;
6314 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
6315 {
6316 ComPtr <IHardDiskAttachment> hda;
6317 rc = hdaEn->GetNext (hda.asOutParam());
6318 if (FAILED (rc))
6319 break;
6320
6321 PVMREQ pReq;
6322 IHardDiskAttachment *pHda = hda;
6323 /*
6324 * don't leave the lock since reconfigureVDI isn't going to
6325 * access Console.
6326 */
6327 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
6328 (PFNRT)reconfigureVDI, 3, that->mpVM,
6329 pHda, &rc);
6330 if (VBOX_SUCCESS (rc))
6331 rc = pReq->iStatus;
6332 VMR3ReqFree (pReq);
6333 if (FAILED (rc))
6334 break;
6335 if (VBOX_FAILURE (vrc))
6336 {
6337 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
6338 rc = E_FAIL;
6339 break;
6340 }
6341 }
6342 }
6343 while (0);
6344 }
6345
6346 /* finalize the procedure regardless of the result */
6347 if (task->mIsSnapshot)
6348 {
6349 /*
6350 * finalize the requested snapshot object.
6351 * This will reset the machine state to the state it had right
6352 * before calling mControl->BeginTakingSnapshot().
6353 */
6354 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
6355 }
6356 else
6357 {
6358 /*
6359 * finalize the requested save state procedure.
6360 * In case of success, the server will set the machine state to Saved;
6361 * in case of failure it will reset the it to the state it had right
6362 * before calling mControl->BeginSavingState().
6363 */
6364 that->mControl->EndSavingState (SUCCEEDED (rc));
6365 }
6366
6367 /* synchronize the state with the server */
6368 if (task->mIsSnapshot || FAILED (rc))
6369 {
6370 if (task->mLastMachineState == MachineState_Running)
6371 {
6372 /* restore the paused state if appropriate */
6373 that->setMachineStateLocally (MachineState_Paused);
6374 /* restore the running state if appropriate */
6375 that->Resume();
6376 }
6377 else
6378 that->setMachineStateLocally (task->mLastMachineState);
6379 }
6380 else
6381 {
6382 /*
6383 * The machine has been successfully saved, so power it down
6384 * (vmstateChangeCallback() will set state to Saved on success).
6385 * Note: we release the task's VM caller, otherwise it will
6386 * deadlock.
6387 */
6388 task->releaseVMCaller();
6389
6390 rc = that->powerDown();
6391 }
6392
6393 /* notify the progress object about operation completion */
6394 if (SUCCEEDED (rc))
6395 task->mProgress->notifyComplete (S_OK);
6396 else
6397 {
6398 if (!errMsg.isNull())
6399 task->mProgress->notifyComplete (rc,
6400 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
6401 else
6402 task->mProgress->notifyComplete (rc);
6403 }
6404
6405 LogFlowFuncLeave();
6406 return VINF_SUCCESS;
6407}
6408
6409/**
6410 * Thread for powering down the Console.
6411 *
6412 * @param Thread The thread handle.
6413 * @param pvUser Pointer to the VMTask structure.
6414 * @return VINF_SUCCESS (ignored).
6415 *
6416 * @note Locks the Console object for writing.
6417 */
6418/*static*/
6419DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
6420{
6421 LogFlowFuncEnter();
6422
6423 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
6424 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6425
6426 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
6427
6428 const ComObjPtr <Console> &that = task->mConsole;
6429
6430 /*
6431 * Note: no need to use addCaller() to protect Console
6432 * because VMTask does that
6433 */
6434
6435 /* release VM caller to let powerDown() proceed */
6436 task->releaseVMCaller();
6437
6438 HRESULT rc = that->powerDown();
6439 AssertComRC (rc);
6440
6441 LogFlowFuncLeave();
6442 return VINF_SUCCESS;
6443}
6444
6445/**
6446 * The Main status driver instance data.
6447 */
6448typedef struct DRVMAINSTATUS
6449{
6450 /** The LED connectors. */
6451 PDMILEDCONNECTORS ILedConnectors;
6452 /** Pointer to the LED ports interface above us. */
6453 PPDMILEDPORTS pLedPorts;
6454 /** Pointer to the array of LED pointers. */
6455 PPDMLED *papLeds;
6456 /** The unit number corresponding to the first entry in the LED array. */
6457 RTUINT iFirstLUN;
6458 /** The unit number corresponding to the last entry in the LED array.
6459 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
6460 RTUINT iLastLUN;
6461} DRVMAINSTATUS, *PDRVMAINSTATUS;
6462
6463
6464/**
6465 * Notification about a unit which have been changed.
6466 *
6467 * The driver must discard any pointers to data owned by
6468 * the unit and requery it.
6469 *
6470 * @param pInterface Pointer to the interface structure containing the called function pointer.
6471 * @param iLUN The unit number.
6472 */
6473DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
6474{
6475 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
6476 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
6477 {
6478 PPDMLED pLed;
6479 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
6480 if (VBOX_FAILURE(rc))
6481 pLed = NULL;
6482 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
6483 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
6484 }
6485}
6486
6487
6488/**
6489 * Queries an interface to the driver.
6490 *
6491 * @returns Pointer to interface.
6492 * @returns NULL if the interface was not supported by the driver.
6493 * @param pInterface Pointer to this interface structure.
6494 * @param enmInterface The requested interface identification.
6495 */
6496DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
6497{
6498 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
6499 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6500 switch (enmInterface)
6501 {
6502 case PDMINTERFACE_BASE:
6503 return &pDrvIns->IBase;
6504 case PDMINTERFACE_LED_CONNECTORS:
6505 return &pDrv->ILedConnectors;
6506 default:
6507 return NULL;
6508 }
6509}
6510
6511
6512/**
6513 * Destruct a status driver instance.
6514 *
6515 * @returns VBox status.
6516 * @param pDrvIns The driver instance data.
6517 */
6518DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
6519{
6520 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6521 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6522 if (pData->papLeds)
6523 {
6524 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
6525 while (iLed-- > 0)
6526 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
6527 }
6528}
6529
6530
6531/**
6532 * Construct a status driver instance.
6533 *
6534 * @returns VBox status.
6535 * @param pDrvIns The driver instance data.
6536 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
6537 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
6538 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
6539 * iInstance it's expected to be used a bit in this function.
6540 */
6541DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
6542{
6543 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6544 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6545
6546 /*
6547 * Validate configuration.
6548 */
6549 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
6550 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
6551 PPDMIBASE pBaseIgnore;
6552 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
6553 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
6554 {
6555 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
6556 return VERR_PDM_DRVINS_NO_ATTACH;
6557 }
6558
6559 /*
6560 * Data.
6561 */
6562 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
6563 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
6564
6565 /*
6566 * Read config.
6567 */
6568 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
6569 if (VBOX_FAILURE(rc))
6570 {
6571 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
6572 return rc;
6573 }
6574
6575 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
6576 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
6577 pData->iFirstLUN = 0;
6578 else if (VBOX_FAILURE(rc))
6579 {
6580 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
6581 return rc;
6582 }
6583
6584 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
6585 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
6586 pData->iLastLUN = 0;
6587 else if (VBOX_FAILURE(rc))
6588 {
6589 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
6590 return rc;
6591 }
6592 if (pData->iFirstLUN > pData->iLastLUN)
6593 {
6594 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
6595 return VERR_GENERAL_FAILURE;
6596 }
6597
6598 /*
6599 * Get the ILedPorts interface of the above driver/device and
6600 * query the LEDs we want.
6601 */
6602 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
6603 if (!pData->pLedPorts)
6604 {
6605 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
6606 return VERR_PDM_MISSING_INTERFACE_ABOVE;
6607 }
6608
6609 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
6610 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
6611
6612 return VINF_SUCCESS;
6613}
6614
6615
6616/**
6617 * Keyboard driver registration record.
6618 */
6619const PDMDRVREG Console::DrvStatusReg =
6620{
6621 /* u32Version */
6622 PDM_DRVREG_VERSION,
6623 /* szDriverName */
6624 "MainStatus",
6625 /* pszDescription */
6626 "Main status driver (Main as in the API).",
6627 /* fFlags */
6628 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
6629 /* fClass. */
6630 PDM_DRVREG_CLASS_STATUS,
6631 /* cMaxInstances */
6632 ~0,
6633 /* cbInstance */
6634 sizeof(DRVMAINSTATUS),
6635 /* pfnConstruct */
6636 Console::drvStatus_Construct,
6637 /* pfnDestruct */
6638 Console::drvStatus_Destruct,
6639 /* pfnIOCtl */
6640 NULL,
6641 /* pfnPowerOn */
6642 NULL,
6643 /* pfnReset */
6644 NULL,
6645 /* pfnSuspend */
6646 NULL,
6647 /* pfnResume */
6648 NULL,
6649 /* pfnDetach */
6650 NULL
6651};
6652
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