VirtualBox

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

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

PDMUsb

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