VirtualBox

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

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

enclosed some more code in VBOX_WITH_VBOX tests.

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