VirtualBox

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

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

Solaris

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