VirtualBox

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

Last change on this file since 497 was 470, checked in by vboxsync, 18 years ago

Main/Frontends: Changed all interface attributes and method parameters that used to use ULONG to pass pointers around; they now use BYTE * for this purpose (should fix problems for 64-bit targets).

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