VirtualBox

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

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

Save/load implemented. Irq thread. It is highly advised to include VBOX_WITH_PDM_LOCK=1 into your LocalConfig.kmk to avoid interrupt storms in Windows guests.

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