VirtualBox

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

Last change on this file since 880 was 833, checked in by vboxsync, 18 years ago

Main: Minor message correction.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 243.5 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 VBOX_WITH_UNIXY_TAP_NETWORKING
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,
1844 tr ("Cannot attach a USB device to a machine which is not running "
1845 "(machine state: %d)"), mMachineState);
1846
1847 /* protect mpVM */
1848 AutoVMCaller autoVMCaller (this);
1849 CheckComRCReturnRC (autoVMCaller.rc());
1850
1851 /* Don't proceed unless we've found the usb controller. */
1852 PPDMIBASE pBase = NULL;
1853 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
1854 if (VBOX_FAILURE (vrc))
1855 return setError (E_FAIL,
1856 tr ("The virtual machine does not have a USB controller"));
1857
1858 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
1859 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
1860 ComAssertRet (pRhConfig, E_FAIL);
1861
1862 /// @todo (dmik) REMOTE_USB
1863 // when remote USB devices are ready, first search for a device with the
1864 // given UUID in mRemoteUSBDevices. If found, request a capture from
1865 // a remote client. If not found, search it on the local host as done below
1866
1867 /*
1868 * Try attach the given host USB device (a proper errror message should
1869 * be returned in case of error).
1870 */
1871 ComPtr <IUSBDevice> hostDevice;
1872 HRESULT hrc = mControl->CaptureUSBDevice (aId, hostDevice.asOutParam());
1873 CheckComRCReturnRC (hrc);
1874
1875 return attachUSBDevice (hostDevice, true /* aManual */, pRhConfig);
1876}
1877
1878STDMETHODIMP Console::DetachUSBDevice (INPTR GUIDPARAM aId, IUSBDevice **aDevice)
1879{
1880 if (!aDevice)
1881 return E_POINTER;
1882
1883 AutoCaller autoCaller (this);
1884 CheckComRCReturnRC (autoCaller.rc());
1885
1886 AutoLock alock (this);
1887
1888 /* Find it. */
1889 ComObjPtr <OUSBDevice> device;
1890 USBDeviceList::iterator it = mUSBDevices.begin();
1891 while (it != mUSBDevices.end())
1892 {
1893 if ((*it)->id() == aId)
1894 {
1895 device = *it;
1896 break;
1897 }
1898 ++ it;
1899 }
1900
1901 if (!device)
1902 return setError (E_INVALIDARG,
1903 tr ("Cannot detach the USB device (UUID: %s) as it is not attached here."),
1904 Guid (aId).toString().raw());
1905
1906 /* protect mpVM */
1907 AutoVMCaller autoVMCaller (this);
1908 CheckComRCReturnRC (autoVMCaller.rc());
1909
1910 PPDMIBASE pBase = NULL;
1911 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
1912
1913 /* if the device is attached, then there must be a USB controller */
1914 ComAssertRCRet (vrc, E_FAIL);
1915
1916 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
1917 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
1918 ComAssertRet (pRhConfig, E_FAIL);
1919
1920 Guid Uuid(aId);
1921
1922 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n", Uuid.raw()));
1923
1924 /* leave the lock before a VMR3* call (EMT will call us back)! */
1925 alock.leave();
1926
1927 PVMREQ pReq = NULL;
1928 vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
1929 (PFNRT) usbDetachCallback, 5,
1930 this, &it, true /* aManual */, pRhConfig, Uuid.raw());
1931 if (VBOX_SUCCESS (vrc))
1932 vrc = pReq->iStatus;
1933 VMR3ReqFree (pReq);
1934
1935 HRESULT hrc = S_OK;
1936
1937 if (VBOX_SUCCESS (vrc))
1938 device.queryInterfaceTo (aDevice);
1939 else
1940 hrc = setError (E_FAIL,
1941 tr ("Error detaching the USB device. (Failed to destroy the USB proxy device: %Vrc)"), vrc);
1942
1943 return hrc;
1944}
1945
1946STDMETHODIMP
1947Console::CreateSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath)
1948{
1949 if (!aName || !aHostPath)
1950 return E_INVALIDARG;
1951
1952 AutoCaller autoCaller (this);
1953 CheckComRCReturnRC (autoCaller.rc());
1954
1955 AutoLock alock (this);
1956
1957 if (mMachineState == MachineState_Saved)
1958 return setError (E_FAIL,
1959 tr ("Cannot create a transient shared folder on a "
1960 "machine in the saved state."));
1961
1962 /// @todo (dmik) check globally shared folders when they are done
1963
1964 /* check machine's shared folders */
1965 {
1966 ComPtr <ISharedFolderCollection> coll;
1967 HRESULT rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
1968 if (FAILED (rc))
1969 return rc;
1970
1971 ComPtr <ISharedFolder> machineSharedFolder;
1972 rc = coll->FindByName (aName, machineSharedFolder.asOutParam());
1973 if (SUCCEEDED (rc))
1974 return setError (E_FAIL,
1975 tr ("A permanent shared folder named '%ls' already "
1976 "exists."), aName);
1977 }
1978
1979 ComObjPtr <SharedFolder> sharedFolder;
1980 HRESULT rc = findSharedFolder (aName, sharedFolder, false /* aSetError */);
1981 if (SUCCEEDED (rc))
1982 return setError (E_FAIL,
1983 tr ("A shared folder named '%ls' already exists."), aName);
1984
1985 sharedFolder.createObject();
1986 rc = sharedFolder->init (this, aName, aHostPath);
1987 CheckComRCReturnRC (rc);
1988
1989 BOOL accessible = FALSE;
1990 rc = sharedFolder->COMGETTER(Accessible) (&accessible);
1991 CheckComRCReturnRC (rc);
1992
1993 if (!accessible)
1994 return setError (E_FAIL,
1995 tr ("The shared folder path '%ls' on the host is not accessible."), aHostPath);
1996
1997 /// @todo (r=sander?) should move this into the shared folder class */
1998 if (mpVM && mVMMDev->getShFlClientId())
1999 {
2000 /*
2001 * if the VM is online and supports shared folders, share this folder
2002 * under the specified name. On error, return it to the caller.
2003 */
2004
2005 /* protect mpVM */
2006 AutoVMCaller autoVMCaller (this);
2007 CheckComRCReturnRC (autoVMCaller.rc());
2008
2009 VBOXHGCMSVCPARM parms[2];
2010 SHFLSTRING *pFolderName, *pMapName;
2011 int cbString;
2012
2013 Log(("Add shared folder %ls -> %ls\n", aName, aHostPath));
2014
2015 cbString = (RTStrUcs2Len(aHostPath) + 1) * sizeof(RTUCS2);
2016 pFolderName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
2017 Assert(pFolderName);
2018 memcpy(pFolderName->String.ucs2, aHostPath, cbString);
2019
2020 pFolderName->u16Size = cbString;
2021 pFolderName->u16Length = cbString - sizeof(RTUCS2);
2022
2023 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
2024 parms[0].u.pointer.addr = pFolderName;
2025 parms[0].u.pointer.size = sizeof(SHFLSTRING) + cbString;
2026
2027 cbString = (RTStrUcs2Len(aName) + 1) * sizeof(RTUCS2);
2028 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
2029 Assert(pMapName);
2030 memcpy(pMapName->String.ucs2, aName, cbString);
2031
2032 pMapName->u16Size = cbString;
2033 pMapName->u16Length = cbString - sizeof(RTUCS2);
2034
2035 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
2036 parms[1].u.pointer.addr = pMapName;
2037 parms[1].u.pointer.size = sizeof(SHFLSTRING) + cbString;
2038
2039 rc = mVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_ADD_MAPPING, 2, &parms[0]);
2040 RTMemFree(pFolderName);
2041 RTMemFree(pMapName);
2042 if (rc != VINF_SUCCESS)
2043 return setError (E_FAIL, tr ("Unable to add mapping %ls to %ls."), aHostPath, aName);
2044 }
2045
2046 mSharedFolders.push_back (sharedFolder);
2047 return S_OK;
2048}
2049
2050STDMETHODIMP Console::RemoveSharedFolder (INPTR BSTR aName)
2051{
2052 if (!aName)
2053 return E_INVALIDARG;
2054
2055 AutoCaller autoCaller (this);
2056 CheckComRCReturnRC (autoCaller.rc());
2057
2058 AutoLock alock (this);
2059
2060 if (mMachineState == MachineState_Saved)
2061 return setError (E_FAIL,
2062 tr ("Cannot remove a transient shared folder when the "
2063 "machine is in the saved state."));
2064
2065 ComObjPtr <SharedFolder> sharedFolder;
2066 HRESULT rc = findSharedFolder (aName, sharedFolder, true /* aSetError */);
2067 CheckComRCReturnRC (rc);
2068
2069 /* protect mpVM */
2070 AutoVMCaller autoVMCaller (this);
2071 CheckComRCReturnRC (autoVMCaller.rc());
2072
2073 if (mpVM && mVMMDev->getShFlClientId())
2074 {
2075 /*
2076 * if the VM is online and supports shared folders, UNshare this folder.
2077 * On error, return it to the caller.
2078 */
2079 VBOXHGCMSVCPARM parms;
2080 SHFLSTRING *pMapName;
2081 int cbString;
2082
2083 cbString = (RTStrUcs2Len(aName) + 1) * sizeof(RTUCS2);
2084 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
2085 Assert(pMapName);
2086 memcpy(pMapName->String.ucs2, aName, cbString);
2087
2088 pMapName->u16Size = cbString;
2089 pMapName->u16Length = cbString - sizeof(RTUCS2);
2090
2091 parms.type = VBOX_HGCM_SVC_PARM_PTR;
2092 parms.u.pointer.addr = pMapName;
2093 parms.u.pointer.size = sizeof(SHFLSTRING) + cbString;
2094
2095 rc = mVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_REMOVE_MAPPING, 1, &parms);
2096 RTMemFree(pMapName);
2097 if (rc != VINF_SUCCESS)
2098 rc = setError (E_FAIL, tr ("Unable to remove the mapping %ls."), aName);
2099 }
2100
2101 mSharedFolders.remove (sharedFolder);
2102 return rc;
2103}
2104
2105STDMETHODIMP Console::TakeSnapshot (INPTR BSTR aName, INPTR BSTR aDescription,
2106 IProgress **aProgress)
2107{
2108 LogFlowThisFuncEnter();
2109 LogFlowThisFunc (("aName='%ls' mMachineState=%08X\n", aName, mMachineState));
2110
2111 if (!aName)
2112 return E_INVALIDARG;
2113 if (!aProgress)
2114 return E_POINTER;
2115
2116 AutoCaller autoCaller (this);
2117 CheckComRCReturnRC (autoCaller.rc());
2118
2119 AutoLock alock (this);
2120
2121 if (mMachineState > MachineState_Running &&
2122 mMachineState != MachineState_Paused)
2123 {
2124 return setError (E_FAIL,
2125 tr ("Cannot take a snapshot of a machine while it is changing state. (Machine state: %d)"), mMachineState);
2126 }
2127
2128 /* memorize the current machine state */
2129 MachineState_T lastMachineState = mMachineState;
2130
2131 if (mMachineState == MachineState_Running)
2132 {
2133 HRESULT rc = Pause();
2134 CheckComRCReturnRC (rc);
2135 }
2136
2137 HRESULT rc = S_OK;
2138
2139 bool takingSnapshotOnline = mMachineState == MachineState_Paused;
2140
2141 /*
2142 * create a descriptionless VM-side progress object
2143 * (only when creating a snapshot online)
2144 */
2145 ComObjPtr <Progress> saveProgress;
2146 if (takingSnapshotOnline)
2147 {
2148 saveProgress.createObject();
2149 rc = saveProgress->init (FALSE, 1, Bstr (tr ("Saving the execution state")));
2150 AssertComRCReturn (rc, rc);
2151 }
2152
2153 bool beganTakingSnapshot = false;
2154 bool taskCreationFailed = false;
2155
2156 do
2157 {
2158 /* create a task object early to ensure mpVM protection is successful */
2159 std::auto_ptr <VMSaveTask> task;
2160 if (takingSnapshotOnline)
2161 {
2162 task.reset (new VMSaveTask (this, saveProgress));
2163 rc = task->rc();
2164 /*
2165 * If we fail here it means a PowerDown() call happened on another
2166 * thread while we were doing Pause() (which leaves the Console lock).
2167 * We assign PowerDown() a higher precendence than TakeSnapshot(),
2168 * therefore just return the error to the caller.
2169 */
2170 if (FAILED (rc))
2171 {
2172 taskCreationFailed = true;
2173 break;
2174 }
2175 }
2176
2177 Bstr stateFilePath;
2178 ComPtr <IProgress> serverProgress;
2179
2180 /*
2181 * request taking a new snapshot object on the server
2182 * (this will set the machine state to Saving on the server to block
2183 * others from accessing this machine)
2184 */
2185 rc = mControl->BeginTakingSnapshot (this, aName, aDescription,
2186 saveProgress, stateFilePath.asOutParam(),
2187 serverProgress.asOutParam());
2188 if (FAILED (rc))
2189 break;
2190
2191 /*
2192 * state file is non-null only when the VM is paused
2193 * (i.e. createing a snapshot online)
2194 */
2195 ComAssertBreak (
2196 (!stateFilePath.isNull() && takingSnapshotOnline) ||
2197 (stateFilePath.isNull() && !takingSnapshotOnline),
2198 rc = E_FAIL);
2199
2200 beganTakingSnapshot = true;
2201
2202 /* sync the state with the server */
2203 setMachineStateLocally (MachineState_Saving);
2204
2205 /*
2206 * create a combined VM-side progress object and start the save task
2207 * (only when creating a snapshot online)
2208 */
2209 ComObjPtr <CombinedProgress> combinedProgress;
2210 if (takingSnapshotOnline)
2211 {
2212 combinedProgress.createObject();
2213 rc = combinedProgress->init ((IConsole *) this,
2214 Bstr (tr ("Taking snapshot of virtual machine")),
2215 serverProgress, saveProgress);
2216 AssertComRCBreakRC (rc);
2217
2218 /* setup task object and thread to carry out the operation asynchronously */
2219 task->mIsSnapshot = true;
2220 task->mSavedStateFile = stateFilePath;
2221 task->mServerProgress = serverProgress;
2222 /* set the state the operation thread will restore when it is finished */
2223 task->mLastMachineState = lastMachineState;
2224
2225 /* create a thread to wait until the VM state is saved */
2226 int vrc = RTThreadCreate (NULL, Console::saveStateThread, (void *) task.get(),
2227 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMTakeSnap");
2228
2229 ComAssertMsgRCBreak (vrc, ("Could not create VMTakeSnap thread (%Vrc)\n", vrc),
2230 rc = E_FAIL);
2231
2232 /* task is now owned by saveStateThread(), so release it */
2233 task.release();
2234 }
2235
2236 if (SUCCEEDED (rc))
2237 {
2238 /* return the correct progress to the caller */
2239 if (combinedProgress)
2240 combinedProgress.queryInterfaceTo (aProgress);
2241 else
2242 serverProgress.queryInterfaceTo (aProgress);
2243 }
2244 }
2245 while (0);
2246
2247 if (FAILED (rc) && !taskCreationFailed)
2248 {
2249 /* fetch any existing error info */
2250 ErrorInfo ei;
2251
2252 if (beganTakingSnapshot && takingSnapshotOnline)
2253 {
2254 /*
2255 * cancel the requested snapshot (only when creating a snapshot
2256 * online, otherwise the server will cancel the snapshot itself).
2257 * This will reset the machine state to the state it had right
2258 * before calling mControl->BeginTakingSnapshot().
2259 */
2260 mControl->EndTakingSnapshot (FALSE);
2261 }
2262
2263 if (lastMachineState == MachineState_Running)
2264 {
2265 /* restore the paused state if appropriate */
2266 setMachineStateLocally (MachineState_Paused);
2267 /* restore the running state if appropriate */
2268 Resume();
2269 }
2270 else
2271 setMachineStateLocally (lastMachineState);
2272
2273 /* restore fetched error info */
2274 setError (ei);
2275 }
2276
2277 LogFlowThisFunc (("rc=%08X\n", rc));
2278 LogFlowThisFuncLeave();
2279 return rc;
2280}
2281
2282STDMETHODIMP Console::DiscardSnapshot (INPTR GUIDPARAM aId, IProgress **aProgress)
2283{
2284 if (Guid (aId).isEmpty())
2285 return E_INVALIDARG;
2286 if (!aProgress)
2287 return E_POINTER;
2288
2289 AutoCaller autoCaller (this);
2290 CheckComRCReturnRC (autoCaller.rc());
2291
2292 AutoLock alock (this);
2293
2294 if (mMachineState >= MachineState_Running)
2295 return setError (E_FAIL,
2296 tr ("Cannot discard a snapshot on a running machine (Machine state: %d)"), mMachineState);
2297
2298 MachineState_T machineState = MachineState_InvalidMachineState;
2299 HRESULT rc = mControl->DiscardSnapshot (this, aId, &machineState, aProgress);
2300 CheckComRCReturnRC (rc);
2301
2302 setMachineStateLocally (machineState);
2303 return S_OK;
2304}
2305
2306STDMETHODIMP Console::DiscardCurrentState (IProgress **aProgress)
2307{
2308 AutoCaller autoCaller (this);
2309 CheckComRCReturnRC (autoCaller.rc());
2310
2311 AutoLock alock (this);
2312
2313 if (mMachineState >= MachineState_Running)
2314 return setError (E_FAIL,
2315 tr ("Cannot discard the current state of a running machine. (Machine state: %d)"), mMachineState);
2316
2317 MachineState_T machineState = MachineState_InvalidMachineState;
2318 HRESULT rc = mControl->DiscardCurrentState (this, &machineState, aProgress);
2319 CheckComRCReturnRC (rc);
2320
2321 setMachineStateLocally (machineState);
2322 return S_OK;
2323}
2324
2325STDMETHODIMP Console::DiscardCurrentSnapshotAndState (IProgress **aProgress)
2326{
2327 AutoCaller autoCaller (this);
2328 CheckComRCReturnRC (autoCaller.rc());
2329
2330 AutoLock alock (this);
2331
2332 if (mMachineState >= MachineState_Running)
2333 return setError (E_FAIL,
2334 tr ("Cannot discard the current snapshot and state on a running machine. (Machine state: %d)"), mMachineState);
2335
2336 MachineState_T machineState = MachineState_InvalidMachineState;
2337 HRESULT rc =
2338 mControl->DiscardCurrentSnapshotAndState (this, &machineState, aProgress);
2339 CheckComRCReturnRC (rc);
2340
2341 setMachineStateLocally (machineState);
2342 return S_OK;
2343}
2344
2345STDMETHODIMP Console::RegisterCallback (IConsoleCallback *aCallback)
2346{
2347 if (!aCallback)
2348 return E_INVALIDARG;
2349
2350 AutoCaller autoCaller (this);
2351 CheckComRCReturnRC (autoCaller.rc());
2352
2353 AutoLock alock (this);
2354
2355 mCallbacks.push_back (CallbackList::value_type (aCallback));
2356
2357#if 0
2358 /* @todo dmik please implement this.
2359 * Inform the callback about the current status, because the new callback
2360 * must know at least the current mouse capabilities and the pointer shape.
2361 */
2362 aCallback->OnMousePointerShapeChange (mCallbacksStatus.pointerShape.fVisible,
2363 mCallbackStatus.pointerShape.fAlpha,
2364 mCallbackStatus.pointerShape.xHot,
2365 mCallbackStatus.pointerShape.yHot,
2366 mCallbackStatus.pointerShape.width,
2367 mCallbackStatus.pointerShape.height,
2368 mCallbackStatus.pointerShape.pShape);
2369 aCallback->OnMouseCapabilityChange (mCallbackStatus.mouseCapability.supportsAbsolute,
2370 mCallbackStatus.mouseCapability.needsHostCursor);
2371 aCallback->OnStateChange (mCallbackStatus.machineState);
2372 aCallback->OnAdditionsStateChange();
2373 aCallback->OnKeyboardLedsChange(mCallbackStatus.keyboardLeds.fNumLock,
2374 mCallbackStatus.keyboardLeds.fCapsLock,
2375 mCallbackStatus.keyboardLeds.fScrollLock);
2376#endif
2377
2378 return S_OK;
2379}
2380
2381STDMETHODIMP Console::UnregisterCallback (IConsoleCallback *aCallback)
2382{
2383 if (!aCallback)
2384 return E_INVALIDARG;
2385
2386 AutoCaller autoCaller (this);
2387 CheckComRCReturnRC (autoCaller.rc());
2388
2389 AutoLock alock (this);
2390
2391 CallbackList::iterator it;
2392 it = std::find (mCallbacks.begin(),
2393 mCallbacks.end(),
2394 CallbackList::value_type (aCallback));
2395 if (it == mCallbacks.end())
2396 return setError (E_INVALIDARG,
2397 tr ("The given callback handler is not registered"));
2398
2399 mCallbacks.erase (it);
2400 return S_OK;
2401}
2402
2403// Non-interface public methods
2404/////////////////////////////////////////////////////////////////////////////
2405
2406/**
2407 * Called by IInternalSessionControl::OnDVDDriveChange().
2408 *
2409 * @note Locks this object for reading.
2410 */
2411HRESULT Console::onDVDDriveChange()
2412{
2413 LogFlowThisFunc (("\n"));
2414
2415 AutoCaller autoCaller (this);
2416 AssertComRCReturnRC (autoCaller.rc());
2417
2418 AutoReaderLock alock (this);
2419
2420 /* Ignore callbacks when there's no VM around */
2421 if (!mpVM)
2422 return S_OK;
2423
2424 /* protect mpVM */
2425 AutoVMCaller autoVMCaller (this);
2426 CheckComRCReturnRC (autoVMCaller.rc());
2427
2428 /* Get the current DVD state */
2429 HRESULT rc;
2430 DriveState_T eState;
2431
2432 rc = mDVDDrive->COMGETTER (State) (&eState);
2433 ComAssertComRCRetRC (rc);
2434
2435 /* Paranoia */
2436 if ( eState == DriveState_NotMounted
2437 && meDVDState == DriveState_NotMounted)
2438 {
2439 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2440 return S_OK;
2441 }
2442
2443 /* Get the path string and other relevant properties */
2444 Bstr Path;
2445 bool fPassthrough = false;
2446 switch (eState)
2447 {
2448 case DriveState_ImageMounted:
2449 {
2450 ComPtr <IDVDImage> ImagePtr;
2451 rc = mDVDDrive->GetImage (ImagePtr.asOutParam());
2452 if (SUCCEEDED (rc))
2453 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2454 break;
2455 }
2456
2457 case DriveState_HostDriveCaptured:
2458 {
2459 ComPtr <IHostDVDDrive> DrivePtr;
2460 BOOL enabled;
2461 rc = mDVDDrive->GetHostDrive (DrivePtr.asOutParam());
2462 if (SUCCEEDED (rc))
2463 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2464 if (SUCCEEDED (rc))
2465 rc = mDVDDrive->COMGETTER (Passthrough) (&enabled);
2466 if (SUCCEEDED (rc))
2467 fPassthrough = !!enabled;
2468 break;
2469 }
2470
2471 case DriveState_NotMounted:
2472 break;
2473
2474 default:
2475 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2476 rc = E_FAIL;
2477 break;
2478 }
2479
2480 AssertComRC (rc);
2481 if (FAILED (rc))
2482 {
2483 LogFlowThisFunc (("Returns %#x\n", rc));
2484 return rc;
2485 }
2486
2487 return doDriveChange ("piix3ide", 0, 2, eState, &meDVDState,
2488 Utf8Str (Path).raw(), fPassthrough);
2489}
2490
2491
2492/**
2493 * Called by IInternalSessionControl::OnFloppyDriveChange().
2494 *
2495 * @note Locks this object for reading.
2496 */
2497HRESULT Console::onFloppyDriveChange()
2498{
2499 LogFlowThisFunc (("\n"));
2500
2501 AutoCaller autoCaller (this);
2502 AssertComRCReturnRC (autoCaller.rc());
2503
2504 AutoReaderLock alock (this);
2505
2506 /* Ignore callbacks when there's no VM around */
2507 if (!mpVM)
2508 return S_OK;
2509
2510 /* protect mpVM */
2511 AutoVMCaller autoVMCaller (this);
2512 CheckComRCReturnRC (autoVMCaller.rc());
2513
2514 /* Get the current floppy state */
2515 HRESULT rc;
2516 DriveState_T eState;
2517
2518 /* If the floppy drive is disabled, we're not interested */
2519 BOOL fEnabled;
2520 rc = mFloppyDrive->COMGETTER (Enabled) (&fEnabled);
2521 ComAssertComRCRetRC (rc);
2522
2523 if (!fEnabled)
2524 return S_OK;
2525
2526 rc = mFloppyDrive->COMGETTER (State) (&eState);
2527 ComAssertComRCRetRC (rc);
2528
2529 Log2 (("onFloppyDriveChange: eState=%d meFloppyState=%d\n", eState, meFloppyState));
2530
2531
2532 /* Paranoia */
2533 if ( eState == DriveState_NotMounted
2534 && meFloppyState == DriveState_NotMounted)
2535 {
2536 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2537 return S_OK;
2538 }
2539
2540 /* Get the path string and other relevant properties */
2541 Bstr Path;
2542 switch (eState)
2543 {
2544 case DriveState_ImageMounted:
2545 {
2546 ComPtr <IFloppyImage> ImagePtr;
2547 rc = mFloppyDrive->GetImage (ImagePtr.asOutParam());
2548 if (SUCCEEDED (rc))
2549 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2550 break;
2551 }
2552
2553 case DriveState_HostDriveCaptured:
2554 {
2555 ComPtr <IHostFloppyDrive> DrivePtr;
2556 rc = mFloppyDrive->GetHostDrive (DrivePtr.asOutParam());
2557 if (SUCCEEDED (rc))
2558 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2559 break;
2560 }
2561
2562 case DriveState_NotMounted:
2563 break;
2564
2565 default:
2566 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2567 rc = E_FAIL;
2568 break;
2569 }
2570
2571 AssertComRC (rc);
2572 if (FAILED (rc))
2573 {
2574 LogFlowThisFunc (("Returns %#x\n", rc));
2575 return rc;
2576 }
2577
2578 return doDriveChange ("i82078", 0, 0, eState, &meFloppyState,
2579 Utf8Str (Path).raw(), false);
2580}
2581
2582
2583/**
2584 * Process a floppy or dvd change.
2585 *
2586 * @returns COM status code.
2587 *
2588 * @param pszDevice The PDM device name.
2589 * @param uInstance The PDM device instance.
2590 * @param uLun The PDM LUN number of the drive.
2591 * @param eState The new state.
2592 * @param peState Pointer to the variable keeping the actual state of the drive.
2593 * This will be both read and updated to eState or other appropriate state.
2594 * @param pszPath The path to the media / drive which is now being mounted / captured.
2595 * If NULL no media or drive is attached and the lun will be configured with
2596 * the default block driver with no media. This will also be the state if
2597 * mounting / capturing the specified media / drive fails.
2598 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2599 *
2600 * @note Locks this object for reading.
2601 */
2602HRESULT Console::doDriveChange (const char *pszDevice, unsigned uInstance, unsigned uLun, DriveState_T eState,
2603 DriveState_T *peState, const char *pszPath, bool fPassthrough)
2604{
2605 LogFlowThisFunc (("pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2606 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2607 pszDevice, pszDevice, uInstance, uLun, eState,
2608 peState, *peState, pszPath, pszPath, fPassthrough));
2609
2610 AutoCaller autoCaller (this);
2611 AssertComRCReturnRC (autoCaller.rc());
2612
2613 AutoReaderLock alock (this);
2614
2615 /* protect mpVM */
2616 AutoVMCaller autoVMCaller (this);
2617 CheckComRCReturnRC (autoVMCaller.rc());
2618
2619 /*
2620 * Call worker in EMT, that's faster and safer than doing everything
2621 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2622 * here to make requests from under the lock in order to serialize them.
2623 */
2624 PVMREQ pReq;
2625 int vrc = VMR3ReqCall (mpVM, &pReq, 0 /* no wait! */,
2626 (PFNRT) Console::changeDrive, 8,
2627 this, pszDevice, uInstance, uLun, eState, peState,
2628 pszPath, fPassthrough);
2629 /// @todo (r=dmik) bird, it would be nice to have a special VMR3Req method
2630 // for that purpose, that doesn't return useless VERR_TIMEOUT
2631 if (vrc == VERR_TIMEOUT)
2632 vrc = VINF_SUCCESS;
2633
2634 /* leave the lock before waiting for a result (EMT will call us back!) */
2635 alock.leave();
2636
2637 if (VBOX_SUCCESS (vrc))
2638 {
2639 vrc = VMR3ReqWait (pReq, RT_INDEFINITE_WAIT);
2640 AssertRC (vrc);
2641 if (VBOX_SUCCESS (vrc))
2642 vrc = pReq->iStatus;
2643 }
2644 VMR3ReqFree (pReq);
2645
2646 if (VBOX_SUCCESS (vrc))
2647 {
2648 LogFlowThisFunc (("Returns S_OK\n"));
2649 return S_OK;
2650 }
2651
2652 if (pszPath)
2653 return setError (E_FAIL,
2654 tr ("Could not mount the media/drive '%s' (%Vrc)"), pszPath, vrc);
2655
2656 return setError (E_FAIL,
2657 tr ("Could not unmount the currently mounted media/drive (%Vrc)"), vrc);
2658}
2659
2660
2661/**
2662 * Performs the Floppy/DVD change in EMT.
2663 *
2664 * @returns VBox status code.
2665 *
2666 * @param pThis Pointer to the Console object.
2667 * @param pszDevice The PDM device name.
2668 * @param uInstance The PDM device instance.
2669 * @param uLun The PDM LUN number of the drive.
2670 * @param eState The new state.
2671 * @param peState Pointer to the variable keeping the actual state of the drive.
2672 * This will be both read and updated to eState or other appropriate state.
2673 * @param pszPath The path to the media / drive which is now being mounted / captured.
2674 * If NULL no media or drive is attached and the lun will be configured with
2675 * the default block driver with no media. This will also be the state if
2676 * mounting / capturing the specified media / drive fails.
2677 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2678 *
2679 * @thread EMT
2680 * @note Locks the Console object for writing
2681 */
2682DECLCALLBACK(int) Console::changeDrive (Console *pThis, const char *pszDevice, unsigned uInstance, unsigned uLun,
2683 DriveState_T eState, DriveState_T *peState,
2684 const char *pszPath, bool fPassthrough)
2685{
2686 LogFlowFunc (("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2687 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2688 pThis, pszDevice, pszDevice, uInstance, uLun, eState,
2689 peState, *peState, pszPath, pszPath, fPassthrough));
2690
2691 AssertReturn (pThis, VERR_INVALID_PARAMETER);
2692
2693 AssertMsg ( (!strcmp (pszDevice, "i82078") && uLun == 0 && uInstance == 0)
2694 || (!strcmp (pszDevice, "piix3ide") && uLun == 2 && uInstance == 0),
2695 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
2696
2697 AutoCaller autoCaller (pThis);
2698 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
2699
2700 /*
2701 * Locking the object before doing VMR3* calls is quite safe here,
2702 * since we're on EMT. Write lock is necessary because we're indirectly
2703 * modify the meDVDState/meFloppyState members (pointed to by peState).
2704 */
2705 AutoLock alock (pThis);
2706
2707 /* protect mpVM */
2708 AutoVMCaller autoVMCaller (pThis);
2709 CheckComRCReturnRC (autoVMCaller.rc());
2710
2711 PVM pVM = pThis->mpVM;
2712
2713 /*
2714 * Suspend the VM first.
2715 *
2716 * The VM must not be running since it might have pending I/O to
2717 * the drive which is being changed.
2718 */
2719 bool fResume;
2720 VMSTATE enmVMState = VMR3GetState (pVM);
2721 switch (enmVMState)
2722 {
2723 case VMSTATE_RESETTING:
2724 case VMSTATE_RUNNING:
2725 {
2726 LogFlowFunc (("Suspending the VM...\n"));
2727 /* disable the callback to prevent Console-level state change */
2728 pThis->mVMStateChangeCallbackDisabled = true;
2729 int rc = VMR3Suspend (pVM);
2730 pThis->mVMStateChangeCallbackDisabled = false;
2731 AssertRCReturn (rc, rc);
2732 fResume = true;
2733 break;
2734 }
2735
2736 case VMSTATE_SUSPENDED:
2737 case VMSTATE_CREATED:
2738 case VMSTATE_OFF:
2739 fResume = false;
2740 break;
2741
2742 default:
2743 AssertMsgFailedReturn (("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
2744 }
2745
2746 int rc = VINF_SUCCESS;
2747 int rcRet = VINF_SUCCESS;
2748
2749 do
2750 {
2751 /*
2752 * Unmount existing media / detach host drive.
2753 */
2754 PPDMIMOUNT pIMount = NULL;
2755 switch (*peState)
2756 {
2757
2758 case DriveState_ImageMounted:
2759 {
2760 /*
2761 * Resolve the interface.
2762 */
2763 PPDMIBASE pBase;
2764 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2765 if (VBOX_FAILURE (rc))
2766 {
2767 if (rc == VERR_PDM_LUN_NOT_FOUND)
2768 rc = VINF_SUCCESS;
2769 AssertRC (rc);
2770 break;
2771 }
2772
2773 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2774 AssertBreak (pIMount, rc = VERR_INVALID_POINTER);
2775
2776 /*
2777 * Unmount the media.
2778 */
2779 rc = pIMount->pfnUnmount (pIMount);
2780 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2781 rc = VINF_SUCCESS;
2782 break;
2783 }
2784
2785 case DriveState_HostDriveCaptured:
2786 {
2787 rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2788 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2789 rc = VINF_SUCCESS;
2790 AssertRC (rc);
2791 break;
2792 }
2793
2794 case DriveState_NotMounted:
2795 break;
2796
2797 default:
2798 AssertMsgFailed (("Invalid *peState: %d\n", peState));
2799 break;
2800 }
2801
2802 if (VBOX_FAILURE (rc))
2803 {
2804 rcRet = rc;
2805 break;
2806 }
2807
2808 /*
2809 * Nothing is currently mounted.
2810 */
2811 *peState = DriveState_NotMounted;
2812
2813
2814 /*
2815 * Process the HostDriveCaptured state first, as the fallback path
2816 * means mounting the normal block driver without media.
2817 */
2818 if (eState == DriveState_HostDriveCaptured)
2819 {
2820 /*
2821 * Detach existing driver chain (block).
2822 */
2823 int rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2824 if (VBOX_FAILURE (rc))
2825 {
2826 if (rc == VERR_PDM_LUN_NOT_FOUND)
2827 rc = VINF_SUCCESS;
2828 AssertReleaseRC (rc);
2829 break; /* we're toast */
2830 }
2831 pIMount = NULL;
2832
2833 /*
2834 * Construct a new driver configuration.
2835 */
2836 PCFGMNODE pInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2837 AssertRelease (pInst);
2838 /* nuke anything which might have been left behind. */
2839 CFGMR3RemoveNode (CFGMR3GetChildF (pInst, "LUN#%d", uLun));
2840
2841 /* create a new block driver config */
2842 PCFGMNODE pLunL0;
2843 PCFGMNODE pCfg;
2844 if ( VBOX_SUCCESS (rc = CFGMR3InsertNodeF (pInst, &pLunL0, "LUN#%u", uLun))
2845 && VBOX_SUCCESS (rc = CFGMR3InsertString (pLunL0, "Driver", !strcmp (pszDevice, "i82078") ? "HostFloppy" : "HostDVD"))
2846 && VBOX_SUCCESS (rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg))
2847 && VBOX_SUCCESS (rc = CFGMR3InsertString (pCfg, "Path", pszPath))
2848 && VBOX_SUCCESS (rc = !strcmp (pszDevice, "i82078") ? VINF_SUCCESS : CFGMR3InsertInteger(pCfg, "Passthrough", fPassthrough)))
2849 {
2850 /*
2851 * Attempt to attach the driver.
2852 */
2853 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, NULL);
2854 AssertRC (rc);
2855 }
2856 if (VBOX_FAILURE (rc))
2857 rcRet = rc;
2858 }
2859
2860 /*
2861 * Process the ImageMounted, NotMounted and failed HostDriveCapture cases.
2862 */
2863 rc = VINF_SUCCESS;
2864 switch (eState)
2865 {
2866#define RC_CHECK() do { if (VBOX_FAILURE (rc)) { AssertReleaseRC (rc); break; } } while (0)
2867
2868 case DriveState_HostDriveCaptured:
2869 if (VBOX_SUCCESS (rcRet))
2870 break;
2871 /* fallback: umounted block driver. */
2872 pszPath = NULL;
2873 eState = DriveState_NotMounted;
2874 /* fallthru */
2875 case DriveState_ImageMounted:
2876 case DriveState_NotMounted:
2877 {
2878 /*
2879 * Resolve the drive interface / create the driver.
2880 */
2881 if (!pIMount)
2882 {
2883 PPDMIBASE pBase;
2884 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2885 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2886 {
2887 /*
2888 * We have to create it, so we'll do the full config setup and everything.
2889 */
2890 PCFGMNODE pIdeInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2891 AssertRelease (pIdeInst);
2892
2893 /* nuke anything which might have been left behind. */
2894 CFGMR3RemoveNode (CFGMR3GetChildF (pIdeInst, "LUN#%d", uLun));
2895
2896 /* create a new block driver config */
2897 PCFGMNODE pLunL0;
2898 rc = CFGMR3InsertNodeF (pIdeInst, &pLunL0, "LUN#%d", uLun); RC_CHECK();
2899 rc = CFGMR3InsertString (pLunL0, "Driver", "Block"); RC_CHECK();
2900 PCFGMNODE pCfg;
2901 rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg); RC_CHECK();
2902 rc = CFGMR3InsertString (pCfg, "Type", !strcmp (pszDevice, "i82078") ? "Floppy 1.44" : "DVD");
2903 RC_CHECK();
2904 rc = CFGMR3InsertInteger (pCfg, "Mountable", 1); RC_CHECK();
2905
2906 /*
2907 * Attach the driver.
2908 */
2909 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, &pBase);
2910 RC_CHECK();
2911 }
2912 else if (VBOX_FAILURE(rc))
2913 {
2914 AssertRC (rc);
2915 return rc;
2916 }
2917
2918 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2919 if (!pIMount)
2920 {
2921 AssertFailed();
2922 return rc;
2923 }
2924 }
2925
2926 /*
2927 * If we've got an image, let's mount it.
2928 */
2929 if (pszPath && *pszPath)
2930 {
2931 rc = pIMount->pfnMount (pIMount, pszPath, strcmp (pszDevice, "i82078") ? "MediaISO" : "RawImage");
2932 if (VBOX_FAILURE (rc))
2933 eState = DriveState_NotMounted;
2934 }
2935 break;
2936 }
2937
2938 default:
2939 AssertMsgFailed (("Invalid eState: %d\n", eState));
2940 break;
2941
2942#undef RC_CHECK
2943 }
2944
2945 if (VBOX_FAILURE (rc) && VBOX_SUCCESS (rcRet))
2946 rcRet = rc;
2947
2948 *peState = eState;
2949 }
2950 while (0);
2951
2952 /*
2953 * Resume the VM if necessary.
2954 */
2955 if (fResume)
2956 {
2957 LogFlowFunc (("Resuming the VM...\n"));
2958 /* disable the callback to prevent Console-level state change */
2959 pThis->mVMStateChangeCallbackDisabled = true;
2960 rc = VMR3Resume (pVM);
2961 pThis->mVMStateChangeCallbackDisabled = false;
2962 AssertRC (rc);
2963 if (VBOX_FAILURE (rc))
2964 {
2965 /* too bad, we failed. try to sync the console state with the VMM state */
2966 vmstateChangeCallback (pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
2967 }
2968 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
2969 // error (if any) will be hidden from the caller. For proper reporting
2970 // of such multiple errors to the caller we need to enhance the
2971 // IVurtualBoxError interface. For now, give the first error the higher
2972 // priority.
2973 if (VBOX_SUCCESS (rcRet))
2974 rcRet = rc;
2975 }
2976
2977 LogFlowFunc (("Returning %Vrc\n", rcRet));
2978 return rcRet;
2979}
2980
2981
2982/**
2983 * Called by IInternalSessionControl::OnNetworkAdapterChange().
2984 *
2985 * @note Locks this object for writing.
2986 */
2987HRESULT Console::onNetworkAdapterChange(INetworkAdapter *networkAdapter)
2988{
2989 LogFlowThisFunc (("\n"));
2990
2991 AutoCaller autoCaller (this);
2992 AssertComRCReturnRC (autoCaller.rc());
2993
2994 AutoLock alock (this);
2995
2996 /* Don't do anything if the VM isn't running */
2997 if (!mpVM)
2998 return S_OK;
2999
3000 /* protect mpVM */
3001 AutoVMCaller autoVMCaller (this);
3002 CheckComRCReturnRC (autoVMCaller.rc());
3003
3004 /* Get the properties we need from the adapter */
3005 BOOL fCableConnected;
3006 HRESULT rc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected);
3007 AssertComRC(rc);
3008 if (SUCCEEDED(rc))
3009 {
3010 ULONG ulInstance;
3011 rc = networkAdapter->COMGETTER(Slot)(&ulInstance);
3012 AssertComRC(rc);
3013 if (SUCCEEDED(rc))
3014 {
3015 /*
3016 * Find the pcnet instance, get the config interface and update the link state.
3017 */
3018 PPDMIBASE pBase;
3019 int rcVBox = PDMR3QueryDeviceLun(mpVM, "pcnet", (unsigned)ulInstance, 0, &pBase);
3020 ComAssertRC(rcVBox);
3021 if (VBOX_SUCCESS(rcVBox))
3022 {
3023 Assert(pBase);
3024 PPDMINETWORKCONFIG pINetCfg = (PPDMINETWORKCONFIG)pBase->pfnQueryInterface(pBase, PDMINTERFACE_NETWORK_CONFIG);
3025 if (pINetCfg)
3026 {
3027 Log(("Console::onNetworkAdapterChange: setting link state to %d\n", fCableConnected));
3028 rcVBox = pINetCfg->pfnSetLinkState(pINetCfg, fCableConnected ? PDMNETWORKLINKSTATE_UP : PDMNETWORKLINKSTATE_DOWN);
3029 ComAssertRC(rcVBox);
3030 }
3031 }
3032 }
3033 }
3034
3035 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3036 return rc;
3037}
3038
3039/**
3040 * Called by IInternalSessionControl::OnVRDPServerChange().
3041 *
3042 * @note Locks this object for writing.
3043 */
3044HRESULT Console::onVRDPServerChange()
3045{
3046 AutoCaller autoCaller (this);
3047 AssertComRCReturnRC (autoCaller.rc());
3048
3049 AutoLock alock (this);
3050
3051 HRESULT rc = S_OK;
3052
3053 if (mVRDPServer && mMachineState == MachineState_Running)
3054 {
3055 BOOL vrdpEnabled = FALSE;
3056
3057 rc = mVRDPServer->COMGETTER(Enabled) (&vrdpEnabled);
3058 ComAssertComRCRetRC (rc);
3059
3060 if (vrdpEnabled)
3061 {
3062 // If there was no VRDP server started the 'stop' will do nothing.
3063 // However if a server was started and this notification was called,
3064 // we have to restart the server.
3065 mConsoleVRDPServer->Stop ();
3066
3067 if (VBOX_FAILURE(mConsoleVRDPServer->Launch ()))
3068 {
3069 rc = E_FAIL;
3070 }
3071 else
3072 {
3073 mConsoleVRDPServer->SetCallback ();
3074 }
3075 }
3076 else
3077 {
3078 mConsoleVRDPServer->Stop ();
3079 }
3080 }
3081
3082 return rc;
3083}
3084
3085/**
3086 * Called by IInternalSessionControl::OnUSBControllerChange().
3087 *
3088 * @note Locks this object for writing.
3089 */
3090HRESULT Console::onUSBControllerChange()
3091{
3092 LogFlowThisFunc (("\n"));
3093
3094 AutoCaller autoCaller (this);
3095 AssertComRCReturnRC (autoCaller.rc());
3096
3097 AutoLock alock (this);
3098
3099 /* Ignore if no VM is running yet. */
3100 if (!mpVM)
3101 return S_OK;
3102
3103/// @todo (dmik)
3104// check for the Enabled state and disable virtual USB controller??
3105// Anyway, if we want to query the machine's USB Controller we need to cache
3106// it to to mUSBController in #init() (as it is done with mDVDDrive).
3107//
3108// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
3109//
3110// /* protect mpVM */
3111// AutoVMCaller autoVMCaller (this);
3112// CheckComRCReturnRC (autoVMCaller.rc());
3113
3114 return S_OK;
3115}
3116
3117/**
3118 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
3119 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
3120 * returns TRUE for a given remote USB device.
3121 *
3122 * @return S_OK if the device was attached to the VM.
3123 * @return failure if not attached.
3124 *
3125 * @param aDevice
3126 * The device in question.
3127 *
3128 * @note Locks this object for writing.
3129 */
3130HRESULT Console::onUSBDeviceAttach (IUSBDevice *aDevice)
3131{
3132 LogFlowThisFunc (("aDevice=%p\n", aDevice));
3133
3134 AutoCaller autoCaller (this);
3135 ComAssertComRCRetRC (autoCaller.rc());
3136
3137 AutoLock alock (this);
3138
3139 /* VM might have been stopped when this message arrives */
3140 if (mMachineState < MachineState_Running)
3141 {
3142 LogFlowThisFunc (("Attach request ignored (mMachineState=%d).\n",
3143 mMachineState));
3144 return E_FAIL;
3145 }
3146
3147 /* protect mpVM */
3148 AutoVMCaller autoVMCaller (this);
3149 CheckComRCReturnRC (autoVMCaller.rc());
3150
3151 /* Don't proceed unless we've found the usb controller. */
3152 PPDMIBASE pBase = NULL;
3153 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3154 if (VBOX_FAILURE (vrc))
3155 {
3156 LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
3157 return E_FAIL;
3158 }
3159
3160 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
3161 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
3162 ComAssertRet (pRhConfig, E_FAIL);
3163
3164 return attachUSBDevice (aDevice, false /* aManual */, pRhConfig);
3165}
3166
3167/**
3168 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
3169 * processRemoteUSBDevices().
3170 *
3171 * @note Locks this object for writing.
3172 */
3173HRESULT Console::onUSBDeviceDetach (INPTR GUIDPARAM aId)
3174{
3175 Guid Uuid (aId);
3176 LogFlowThisFunc (("aId={%Vuuid}\n", Uuid.raw()));
3177
3178 AutoCaller autoCaller (this);
3179 AssertComRCReturnRC (autoCaller.rc());
3180
3181 AutoLock alock (this);
3182
3183 /* Find the device. */
3184 ComObjPtr <OUSBDevice> device;
3185 USBDeviceList::iterator it = mUSBDevices.begin();
3186 while (it != mUSBDevices.end())
3187 {
3188 LogFlowThisFunc (("it={%Vuuid}\n", (*it)->id().raw()));
3189 if ((*it)->id() == Uuid)
3190 {
3191 device = *it;
3192 break;
3193 }
3194 ++ it;
3195 }
3196
3197 /* VM might have been stopped when this message arrives */
3198 if (device.isNull())
3199 {
3200 LogFlowThisFunc (("Device not found.\n"));
3201 if (mMachineState < MachineState_Running)
3202 {
3203 LogFlowThisFunc (("Detach request ignored (mMachineState=%d).\n",
3204 mMachineState));
3205 return E_FAIL;
3206 }
3207 /* the device must be in the list */
3208 AssertFailedReturn (E_FAIL);
3209 }
3210
3211 /* protect mpVM */
3212 AutoVMCaller autoVMCaller (this);
3213 CheckComRCReturnRC (autoVMCaller.rc());
3214
3215 PPDMIBASE pBase = NULL;
3216 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3217
3218 /* if the device is attached, then there must be a USB controller */
3219 AssertRCReturn (vrc, E_FAIL);
3220
3221 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
3222 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
3223 AssertReturn (pRhConfig, E_FAIL);
3224
3225 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n", Uuid.raw()));
3226
3227 /* leave the lock before a VMR3* call (EMT will call us back)! */
3228 alock.leave();
3229
3230 PVMREQ pReq;
3231 vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
3232 (PFNRT) usbDetachCallback, 5,
3233 this, &it, false /* aManual */, pRhConfig, Uuid.raw());
3234 if (VBOX_SUCCESS (vrc))
3235 vrc = pReq->iStatus;
3236 VMR3ReqFree (pReq);
3237
3238 AssertRC (vrc);
3239
3240 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
3241}
3242
3243/**
3244 * Gets called by Session::UpdateMachineState()
3245 * (IInternalSessionControl::updateMachineState()).
3246 *
3247 * Must be called only in certain cases (see the implementation).
3248 *
3249 * @note Locks this object for writing.
3250 */
3251HRESULT Console::updateMachineState (MachineState_T aMachineState)
3252{
3253 AutoCaller autoCaller (this);
3254 AssertComRCReturnRC (autoCaller.rc());
3255
3256 AutoLock alock (this);
3257
3258 AssertReturn (mMachineState == MachineState_Saving ||
3259 mMachineState == MachineState_Discarding,
3260 E_FAIL);
3261
3262 return setMachineStateLocally (aMachineState);
3263}
3264
3265/**
3266 * @note Locks this object for reading.
3267 */
3268void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3269 uint32_t xHot, uint32_t yHot,
3270 uint32_t width, uint32_t height,
3271 void *pShape)
3272{
3273 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3274 "height=%d, shape=%p\n",
3275 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3276
3277 AutoReaderLock alock (this);
3278
3279 CallbackList::iterator it = mCallbacks.begin();
3280 while (it != mCallbacks.end())
3281 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3282 width, height, (BYTE *) pShape);
3283}
3284
3285/**
3286 * @note Locks this object for reading.
3287 */
3288void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3289{
3290 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3291 supportsAbsolute, needsHostCursor));
3292
3293 AutoCaller autoCaller (this);
3294 AssertComRCReturnVoid (autoCaller.rc());
3295
3296 AutoReaderLock alock (this);
3297
3298 CallbackList::iterator it = mCallbacks.begin();
3299 while (it != mCallbacks.end())
3300 {
3301 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3302 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3303 }
3304}
3305
3306/**
3307 * @note Locks this object for reading.
3308 */
3309void Console::onStateChange (MachineState_T machineState)
3310{
3311 AutoCaller autoCaller (this);
3312 AssertComRCReturnVoid (autoCaller.rc());
3313
3314 AutoReaderLock alock (this);
3315
3316 CallbackList::iterator it = mCallbacks.begin();
3317 while (it != mCallbacks.end())
3318 (*it++)->OnStateChange (machineState);
3319}
3320
3321/**
3322 * @note Locks this object for reading.
3323 */
3324void Console::onAdditionsStateChange()
3325{
3326 AutoCaller autoCaller (this);
3327 AssertComRCReturnVoid (autoCaller.rc());
3328
3329 AutoReaderLock alock (this);
3330
3331 CallbackList::iterator it = mCallbacks.begin();
3332 while (it != mCallbacks.end())
3333 (*it++)->OnAdditionsStateChange();
3334}
3335
3336/**
3337 * @note Locks this object for reading.
3338 */
3339void Console::onAdditionsOutdated()
3340{
3341 AutoCaller autoCaller (this);
3342 AssertComRCReturnVoid (autoCaller.rc());
3343
3344 AutoReaderLock alock (this);
3345
3346 /** @todo Use the On-Screen Display feature to report the fact.
3347 * The user should be told to install additions that are
3348 * provided with the current VBox build:
3349 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3350 */
3351}
3352
3353/**
3354 * @note Locks this object for reading.
3355 */
3356void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3357{
3358 AutoCaller autoCaller (this);
3359 AssertComRCReturnVoid (autoCaller.rc());
3360
3361 AutoReaderLock alock (this);
3362
3363 CallbackList::iterator it = mCallbacks.begin();
3364 while (it != mCallbacks.end())
3365 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3366}
3367
3368/**
3369 * @note Locks this object for reading.
3370 */
3371void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3372{
3373 AutoCaller autoCaller (this);
3374 AssertComRCReturnVoid (autoCaller.rc());
3375
3376 AutoReaderLock alock (this);
3377
3378 CallbackList::iterator it = mCallbacks.begin();
3379 while (it != mCallbacks.end())
3380 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3381}
3382
3383// private mehtods
3384////////////////////////////////////////////////////////////////////////////////
3385
3386/**
3387 * Increases the usage counter of the mpVM pointer. Guarantees that
3388 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
3389 * is called.
3390 *
3391 * If this method returns a failure, the caller is not allowed to use mpVM
3392 * and may return the failed result code to the upper level. This method sets
3393 * the extended error info on failure if \a aQuiet is false.
3394 *
3395 * Setting \a aQuiet to true is useful for methods that don't want to return
3396 * the failed result code to the caller when this method fails (e.g. need to
3397 * silently check for the mpVM avaliability).
3398 *
3399 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
3400 * returned instead of asserting. Having it false is intended as a sanity check
3401 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
3402 *
3403 * @param aQuiet true to suppress setting error info
3404 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
3405 * (otherwise this method will assert if mpVM is NULL)
3406 *
3407 * @note Locks this object for writing.
3408 */
3409HRESULT Console::addVMCaller (bool aQuiet /* = false */,
3410 bool aAllowNullVM /* = false */)
3411{
3412 AutoCaller autoCaller (this);
3413 AssertComRCReturnRC (autoCaller.rc());
3414
3415 AutoLock alock (this);
3416
3417 if (mVMDestroying)
3418 {
3419 /* powerDown() is waiting for all callers to finish */
3420 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3421 tr ("Virtual machine is being powered down"));
3422 }
3423
3424 if (mpVM == NULL)
3425 {
3426 Assert (aAllowNullVM == true);
3427
3428 /* The machine is not powered up */
3429 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3430 tr ("Virtual machine is not powered up"));
3431 }
3432
3433 ++ mVMCallers;
3434
3435 return S_OK;
3436}
3437
3438/**
3439 * Decreases the usage counter of the mpVM pointer. Must always complete
3440 * the addVMCaller() call after the mpVM pointer is no more necessary.
3441 *
3442 * @note Locks this object for writing.
3443 */
3444void Console::releaseVMCaller()
3445{
3446 AutoCaller autoCaller (this);
3447 AssertComRCReturnVoid (autoCaller.rc());
3448
3449 AutoLock alock (this);
3450
3451 AssertReturnVoid (mpVM != NULL);
3452
3453 Assert (mVMCallers > 0);
3454 -- mVMCallers;
3455
3456 if (mVMCallers == 0 && mVMDestroying)
3457 {
3458 /* inform powerDown() there are no more callers */
3459 RTSemEventSignal (mVMZeroCallersSem);
3460 }
3461}
3462
3463/**
3464 * Internal power off worker routine.
3465 *
3466 * This method may be called only at certain places with the folliwing meaning
3467 * as shown below:
3468 *
3469 * - if the machine state is either Running or Paused, a normal
3470 * Console-initiated powerdown takes place (e.g. PowerDown());
3471 * - if the machine state is Saving, saveStateThread() has successfully
3472 * done its job;
3473 * - if the machine state is Starting or Restoring, powerUpThread() has
3474 * failed to start/load the VM;
3475 * - if the machine state is Stopping, the VM has powered itself off
3476 * (i.e. not as a result of the powerDown() call).
3477 *
3478 * Calling it in situations other than the above will cause unexpected
3479 * behavior.
3480 *
3481 * Note that this method should be the only one that destroys mpVM and sets
3482 * it to NULL.
3483 *
3484 * @note Locks this object for writing.
3485 *
3486 * @note Never call this method from a thread that called addVMCaller() or
3487 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
3488 * release(). Otherwise it will deadlock.
3489 */
3490HRESULT Console::powerDown()
3491{
3492 LogFlowThisFuncEnter();
3493
3494 AutoCaller autoCaller (this);
3495 AssertComRCReturnRC (autoCaller.rc());
3496
3497 AutoLock alock (this);
3498
3499 /* sanity */
3500 AssertReturn (mVMDestroying == false, E_FAIL);
3501
3502 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
3503 "(mMachineState=%d, InUninit=%d)\n",
3504 mMachineState, autoCaller.state() == InUninit));
3505
3506 /* First, wait for all mpVM callers to finish their work if necessary */
3507 if (mVMCallers > 0)
3508 {
3509 /* go to the destroying state to prevent from adding new callers */
3510 mVMDestroying = true;
3511
3512 /* lazy creation */
3513 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
3514 RTSemEventCreate (&mVMZeroCallersSem);
3515
3516 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
3517 mVMCallers));
3518
3519 alock.leave();
3520
3521 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
3522
3523 alock.enter();
3524 }
3525
3526 AssertReturn (mpVM, E_FAIL);
3527
3528 AssertMsg (mMachineState == MachineState_Running ||
3529 mMachineState == MachineState_Paused ||
3530 mMachineState == MachineState_Saving ||
3531 mMachineState == MachineState_Starting ||
3532 mMachineState == MachineState_Restoring ||
3533 mMachineState == MachineState_Stopping,
3534 ("Invalid machine state: %d\n", mMachineState));
3535
3536 HRESULT rc = S_OK;
3537 int vrc = VINF_SUCCESS;
3538
3539 /*
3540 * Power off the VM if not already done that. In case of Stopping, the VM
3541 * has powered itself off and notified Console in vmstateChangeCallback().
3542 * In case of Starting or Restoring, powerUpThread() is calling us on
3543 * failure, so the VM is already off at that point.
3544 */
3545 if (mMachineState != MachineState_Stopping &&
3546 mMachineState != MachineState_Starting &&
3547 mMachineState != MachineState_Restoring)
3548 {
3549 /*
3550 * don't go from Saving to Stopping, vmstateChangeCallback needs it
3551 * to set the state to Saved on VMSTATE_TERMINATED.
3552 */
3553 if (mMachineState != MachineState_Saving)
3554 setMachineState (MachineState_Stopping);
3555
3556 LogFlowThisFunc (("Powering off the VM...\n"));
3557
3558 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
3559 alock.leave();
3560
3561 vrc = VMR3PowerOff (mpVM);
3562 /*
3563 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
3564 * VM-(guest-)initiated power off happened in parallel a ms before
3565 * this call. So far, we let this error pop up on the user's side.
3566 */
3567
3568 alock.enter();
3569 }
3570
3571 LogFlowThisFunc (("Ready for VM destruction\n"));
3572
3573 /*
3574 * If we are called from Console::uninit(), then try to destroy the VM
3575 * even on failure (this will most likely fail too, but what to do?..)
3576 */
3577 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
3578 {
3579 /*
3580 * Stop the VRDP server and release all USB device.
3581 * (When called from uninit mConsoleVRDPServer is already destroyed.)
3582 */
3583 if (mConsoleVRDPServer)
3584 {
3585 LogFlowThisFunc (("Stopping VRDP server...\n"));
3586
3587 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
3588 alock.leave();
3589
3590 mConsoleVRDPServer->Stop();
3591
3592 alock.enter();
3593 }
3594
3595 releaseAllUSBDevices();
3596
3597 /*
3598 * Now we've got to destroy the VM as well. (mpVM is not valid
3599 * beyond this point). We leave the lock before calling VMR3Destroy()
3600 * because it will result into calling destructors of drivers
3601 * associated with Console children which may in turn try to lock
3602 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
3603 * here because mVMDestroying is set which should prevent any activity.
3604 */
3605
3606 /*
3607 * Set mpVM to NULL early just in case if some old code is not using
3608 * addVMCaller()/releaseVMCaller().
3609 */
3610 PVM pVM = mpVM;
3611 mpVM = NULL;
3612
3613 LogFlowThisFunc (("Destroying the VM...\n"));
3614
3615 alock.leave();
3616
3617 vrc = VMR3Destroy (pVM);
3618
3619 /* take the lock again */
3620 alock.enter();
3621
3622 if (VBOX_SUCCESS (vrc))
3623 {
3624 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
3625 mMachineState));
3626 /*
3627 * Note: the Console-level machine state change happens on the
3628 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
3629 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
3630 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
3631 * occured yet. This is okay, because mMachineState is already
3632 * Stopping in this case, so any other attempt to call PowerDown()
3633 * will be rejected.
3634 */
3635 }
3636 else
3637 {
3638 /* bad bad bad, but what to do? */
3639 mpVM = pVM;
3640 rc = setError (E_FAIL,
3641 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
3642 }
3643 }
3644 else
3645 {
3646 rc = setError (E_FAIL,
3647 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
3648 }
3649
3650 /*
3651 * Finished with destruction. Note that if something impossible happened
3652 * and we've failed to destroy the VM, mVMDestroying will remain false and
3653 * mMachineState will be something like Stopping, so most Console methods
3654 * will return an error to the caller.
3655 */
3656 if (mpVM == NULL)
3657 mVMDestroying = false;
3658
3659 LogFlowThisFuncLeave();
3660 return rc;
3661}
3662
3663/**
3664 * @note Locks this object for writing.
3665 */
3666HRESULT Console::setMachineState (MachineState_T aMachineState,
3667 bool aUpdateServer /* = true */)
3668{
3669 AutoCaller autoCaller (this);
3670 AssertComRCReturnRC (autoCaller.rc());
3671
3672 AutoLock alock (this);
3673
3674 HRESULT rc = S_OK;
3675
3676 if (mMachineState != aMachineState)
3677 {
3678 LogFlowThisFunc (("machineState=%d\n", aMachineState));
3679 mMachineState = aMachineState;
3680
3681 /// @todo (dmik)
3682 // possibly, we need to redo onStateChange() using the dedicated
3683 // Event thread, like it is done in VirtualBox. This will make it
3684 // much safer (no deadlocks possible if someone tries to use the
3685 // console from the callback), however, listeners will lose the
3686 // ability to synchronously react to state changes (is it really
3687 // necessary??)
3688 LogFlowThisFunc (("Doing onStateChange()...\n"));
3689 onStateChange (aMachineState);
3690 LogFlowThisFunc (("Done onStateChange()\n"));
3691
3692 if (aUpdateServer)
3693 {
3694 /*
3695 * Server notification MUST be done from under the lock; otherwise
3696 * the machine state here and on the server might go out of sync, that
3697 * can lead to various unexpected results (like the machine state being
3698 * >= MachineState_Running on the server, while the session state is
3699 * already SessionState_SessionClosed at the same time there).
3700 *
3701 * Cross-lock conditions should be carefully watched out: calling
3702 * UpdateState we will require Machine and SessionMachine locks
3703 * (remember that here we're holding the Console lock here, and
3704 * also all locks that have been entered by the thread before calling
3705 * this method).
3706 */
3707 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
3708 rc = mControl->UpdateState (aMachineState);
3709 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
3710 }
3711 }
3712
3713 return rc;
3714}
3715
3716/**
3717 * Searches for a shared folder with the given logical name
3718 * in the collection of shared folders.
3719 *
3720 * @param aName logical name of the shared folder
3721 * @param aSharedFolder where to return the found object
3722 * @param aSetError whether to set the error info if the folder is
3723 * not found
3724 * @return
3725 * S_OK when found or E_INVALIDARG when not found
3726 *
3727 * @note The caller must lock this object for writing.
3728 */
3729HRESULT Console::findSharedFolder (const BSTR aName,
3730 ComObjPtr <SharedFolder> &aSharedFolder,
3731 bool aSetError /* = false */)
3732{
3733 /* sanity check */
3734 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
3735
3736 bool found = false;
3737 for (SharedFolderList::const_iterator it = mSharedFolders.begin();
3738 !found && it != mSharedFolders.end();
3739 ++ it)
3740 {
3741 AutoLock alock (*it);
3742 found = (*it)->name() == aName;
3743 if (found)
3744 aSharedFolder = *it;
3745 }
3746
3747 HRESULT rc = found ? S_OK : E_INVALIDARG;
3748
3749 if (aSetError && !found)
3750 setError (rc, tr ("Could not find a shared folder named '%ls'."), aName);
3751
3752 return rc;
3753}
3754
3755/**
3756 * VM state callback function. Called by the VMM
3757 * using its state machine states.
3758 *
3759 * Primarily used to handle VM initiated power off, suspend and state saving,
3760 * but also for doing termination completed work (VMSTATE_TERMINATE).
3761 *
3762 * In general this function is called in the context of the EMT.
3763 *
3764 * @param aVM The VM handle.
3765 * @param aState The new state.
3766 * @param aOldState The old state.
3767 * @param aUser The user argument (pointer to the Console object).
3768 *
3769 * @note Locks the Console object for writing.
3770 */
3771DECLCALLBACK(void)
3772Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
3773 void *aUser)
3774{
3775 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
3776 aOldState, aState, aVM));
3777
3778 Console *that = static_cast <Console *> (aUser);
3779 AssertReturnVoid (that);
3780
3781 AutoCaller autoCaller (that);
3782 /*
3783 * Note that we must let this method proceed even if Console::uninit() has
3784 * been already called. In such case this VMSTATE change is a result of:
3785 * 1) powerDown() called from uninit() itself, or
3786 * 2) VM-(guest-)initiated power off.
3787 */
3788 AssertReturnVoid (autoCaller.isOk() ||
3789 autoCaller.state() == InUninit);
3790
3791 switch (aState)
3792 {
3793 /*
3794 * The VM has terminated
3795 */
3796 case VMSTATE_OFF:
3797 {
3798 AutoLock alock (that);
3799
3800 if (that->mVMStateChangeCallbackDisabled)
3801 break;
3802
3803 /*
3804 * Do we still think that it is running? It may happen if this is
3805 * a VM-(guest-)initiated shutdown/poweroff.
3806 */
3807 if (that->mMachineState != MachineState_Stopping &&
3808 that->mMachineState != MachineState_Saving &&
3809 that->mMachineState != MachineState_Restoring)
3810 {
3811 LogFlowFunc (("VM has powered itself off but Console still "
3812 "thinks it is running. Notifying.\n"));
3813
3814 /* prevent powerDown() from calling VMR3PowerOff() again */
3815 that->setMachineState (MachineState_Stopping);
3816
3817 /*
3818 * Setup task object and thread to carry out the operation
3819 * asynchronously (if we call powerDown() right here but there
3820 * is one or more mpVM callers (added with addVMCaller()) we'll
3821 * deadlock.
3822 */
3823 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
3824 /*
3825 * If creating a task is falied, this can currently mean one
3826 * of two: either Console::uninit() has been called just a ms
3827 * before (so a powerDown() call is already on the way), or
3828 * powerDown() itself is being already executed. Just do
3829 * nothing .
3830 */
3831 if (!task->isOk())
3832 {
3833 LogFlowFunc (("Console is already being uninitialized.\n"));
3834 break;
3835 }
3836
3837 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
3838 (void *) task.get(), 0,
3839 RTTHREADTYPE_MAIN_WORKER, 0,
3840 "VMPowerDowm");
3841
3842 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
3843 if (VBOX_FAILURE (vrc))
3844 break;
3845
3846 /* task is now owned by powerDownThread(), so release it */
3847 task.release();
3848 }
3849 break;
3850 }
3851
3852 /*
3853 * The VM has been completely destroyed.
3854 *
3855 * Note: This state change can happen at two points:
3856 * 1) At the end of VMR3Destroy() if it was not called from EMT.
3857 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
3858 * called by EMT.
3859 */
3860 case VMSTATE_TERMINATED:
3861 {
3862 AutoLock alock (that);
3863
3864 if (that->mVMStateChangeCallbackDisabled)
3865 break;
3866
3867 /*
3868 * Terminate host interface networking. If aVM is NULL, we've been
3869 * manually called from powerUpThread() either before calling
3870 * VMR3Create() or after VMR3Create() failed, so no need to touch
3871 * networking.
3872 */
3873 if (aVM)
3874 that->powerDownHostInterfaces();
3875
3876 /*
3877 * From now on the machine is officially powered down or
3878 * remains in the Saved state.
3879 */
3880 switch (that->mMachineState)
3881 {
3882 default:
3883 AssertFailed();
3884 /* fall through */
3885 case MachineState_Stopping:
3886 /* successfully powered down */
3887 that->setMachineState (MachineState_PoweredOff);
3888 break;
3889 case MachineState_Saving:
3890 /*
3891 * successfully saved (note that the machine is already
3892 * in the Saved state on the server due to EndSavingState()
3893 * called from saveStateThread(), so only change the local
3894 * state)
3895 */
3896 that->setMachineStateLocally (MachineState_Saved);
3897 break;
3898 case MachineState_Starting:
3899 /*
3900 * failed to start, but be patient: set back to PoweredOff
3901 * (for similarity with the below)
3902 */
3903 that->setMachineState (MachineState_PoweredOff);
3904 break;
3905 case MachineState_Restoring:
3906 /*
3907 * failed to load the saved state file, but be patient:
3908 * set back to Saved (to preserve the saved state file)
3909 */
3910 that->setMachineState (MachineState_Saved);
3911 break;
3912 }
3913
3914 break;
3915 }
3916
3917 case VMSTATE_SUSPENDED:
3918 {
3919 if (aOldState == VMSTATE_RUNNING)
3920 {
3921 AutoLock alock (that);
3922
3923 if (that->mVMStateChangeCallbackDisabled)
3924 break;
3925
3926 /* Change the machine state from Running to Paused */
3927 Assert (that->mMachineState == MachineState_Running);
3928 that->setMachineState (MachineState_Paused);
3929 }
3930 }
3931
3932 case VMSTATE_RUNNING:
3933 {
3934 if (aOldState == VMSTATE_CREATED ||
3935 aOldState == VMSTATE_SUSPENDED)
3936 {
3937 AutoLock alock (that);
3938
3939 if (that->mVMStateChangeCallbackDisabled)
3940 break;
3941
3942 /*
3943 * Change the machine state from Starting, Restoring or Paused
3944 * to Running
3945 */
3946 Assert ((that->mMachineState == MachineState_Starting &&
3947 aOldState == VMSTATE_CREATED) ||
3948 ((that->mMachineState == MachineState_Restoring ||
3949 that->mMachineState == MachineState_Paused) &&
3950 aOldState == VMSTATE_SUSPENDED));
3951
3952 that->setMachineState (MachineState_Running);
3953 }
3954 }
3955
3956 default: /* shut up gcc */
3957 break;
3958 }
3959}
3960
3961/**
3962 * Sends a request to VMM to attach the given host device.
3963 * After this method succeeds, the attached device will appear in the
3964 * mUSBDevices collection.
3965 *
3966 * If \a aManual is true and a failure occures, the given device
3967 * will be returned back to the USB proxy manager.
3968 *
3969 * @param aHostDevice device to attach
3970 * @param aManual true if device is being manually attached
3971 *
3972 * @note Locks this object for writing.
3973 * @note Synchronously calls EMT.
3974 */
3975HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, bool aManual,
3976 PVUSBIRHCONFIG aConfig)
3977{
3978 AssertReturn (aHostDevice && aConfig, E_FAIL);
3979
3980 AutoLock alock (this);
3981
3982 HRESULT hrc;
3983
3984 /*
3985 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
3986 * method in EMT (using usbAttachCallback()).
3987 */
3988 Bstr BstrAddress;
3989 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
3990 ComAssertComRCRetRC (hrc);
3991
3992 Utf8Str Address (BstrAddress);
3993
3994 Guid Uuid;
3995 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
3996 ComAssertComRCRetRC (hrc);
3997
3998 BOOL fRemote = FALSE;
3999 void *pvRemote = NULL;
4000
4001 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
4002 ComAssertComRCRetRC (hrc);
4003
4004#ifndef VRDP_MC
4005 if (fRemote)
4006 {
4007 pvRemote = mConsoleVRDPServer->GetUSBBackendPointer ();
4008 ComAssertRet (pvRemote, E_FAIL);
4009 }
4010#endif /* !VRDP_MC */
4011
4012 /* protect mpVM */
4013 AutoVMCaller autoVMCaller (this);
4014 CheckComRCReturnRC (autoVMCaller.rc());
4015
4016 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
4017 Address.raw(), Uuid.ptr()));
4018
4019 /* leave the lock before a VMR3* call (EMT will call us back)! */
4020 alock.leave();
4021
4022 PVMREQ pReq = NULL;
4023 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4024 (PFNRT) usbAttachCallback, 7,
4025 this, aHostDevice,
4026 aConfig, Uuid.ptr(), fRemote, Address.raw(), pvRemote);
4027 if (VBOX_SUCCESS (vrc))
4028 vrc = pReq->iStatus;
4029 VMR3ReqFree (pReq);
4030
4031 /* restore the lock */
4032 alock.enter();
4033
4034 /* hrc is S_OK here */
4035
4036 if (VBOX_FAILURE (vrc))
4037 {
4038 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
4039 Address.raw(), Uuid.ptr(), vrc));
4040
4041 if (aManual)
4042 {
4043 /*
4044 * Neither SessionMachine::ReleaseUSBDevice() nor Host::releaseUSBDevice()
4045 * should call the Console back, so keep the lock to provide atomicity
4046 * (to protect Host reapplying USB filters)
4047 */
4048 hrc = mControl->ReleaseUSBDevice (Uuid);
4049 AssertComRC (hrc);
4050 }
4051
4052 switch (vrc)
4053 {
4054 case VERR_VUSB_NO_PORTS:
4055 hrc = setError (E_FAIL,
4056 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
4057 break;
4058 case VERR_VUSB_USBFS_PERMISSION:
4059 hrc = setError (E_FAIL,
4060 tr ("Not permitted to open the USB device, check usbfs options"));
4061 break;
4062 default:
4063 hrc = setError (E_FAIL,
4064 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
4065 break;
4066 }
4067 }
4068
4069 return hrc;
4070}
4071
4072/**
4073 * USB device attack callback used by AttachUSBDevice().
4074 * Note that AttachUSBDevice() doesn't return until this callback is executed,
4075 * so we don't use AutoCaller and don't care about reference counters of
4076 * interface pointers passed in.
4077 *
4078 * @thread EMT
4079 * @note Locks the console object for writing.
4080 */
4081//static
4082DECLCALLBACK(int)
4083Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice,
4084 PVUSBIRHCONFIG aConfig, PCRTUUID aUuid, bool aRemote,
4085 const char *aAddress, void *aRemoteBackend)
4086{
4087 LogFlowFuncEnter();
4088 LogFlowFunc (("that={%p}\n", that));
4089
4090 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4091
4092#ifdef VRDP_MC
4093 if (aRemote)
4094 {
4095 /* @todo aRemoteBackend input parameter is not needed. */
4096 Assert (aRemoteBackend == NULL);
4097
4098 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
4099
4100 Guid guid (*aUuid);
4101
4102 aRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
4103
4104 if (aRemoteBackend == NULL)
4105 {
4106 /* The clientId is invalid then. */
4107 return VERR_INVALID_PARAMETER;
4108 }
4109 }
4110#endif /* VRDP_MC */
4111
4112 int vrc = aConfig->pfnCreateProxyDevice (aConfig, aUuid, aRemote, aAddress,
4113 aRemoteBackend);
4114
4115 if (VBOX_SUCCESS (vrc))
4116 {
4117 /* Create a OUSBDevice and add it to the device list */
4118 ComObjPtr <OUSBDevice> device;
4119 device.createObject();
4120 HRESULT hrc = device->init (aHostDevice);
4121 AssertComRC (hrc);
4122
4123 AutoLock alock (that);
4124 that->mUSBDevices.push_back (device);
4125 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
4126 }
4127
4128 LogFlowFunc (("vrc=%Vrc\n", vrc));
4129 LogFlowFuncLeave();
4130 return vrc;
4131}
4132
4133/**
4134 * USB device attack callback used by AttachUSBDevice().
4135 * Note that AttachUSBDevice() doesn't return until this callback is executed,
4136 * so we don't use AutoCaller and don't care about reference counters of
4137 * interface pointers passed in.
4138 *
4139 * @thread EMT
4140 * @note Locks the console object for writing.
4141 */
4142//static
4143DECLCALLBACK(int)
4144Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt,
4145 bool aManual, PVUSBIRHCONFIG aConfig, PCRTUUID aUuid)
4146{
4147 LogFlowFuncEnter();
4148 LogFlowFunc (("that={%p}\n", that));
4149
4150 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4151
4152#ifdef VRDP_MC
4153 /*
4154 * If that was a remote device, release the backend pointer.
4155 * The pointer was requested in usbAttachCallback.
4156 */
4157 BOOL fRemote = FALSE;
4158
4159 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
4160 ComAssertComRC (hrc2);
4161
4162 if (fRemote)
4163 {
4164 Guid guid (*aUuid);
4165 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
4166 }
4167#endif /* VRDP_MC */
4168
4169 int vrc = aConfig->pfnDestroyProxyDevice (aConfig, aUuid);
4170
4171 if (VBOX_SUCCESS (vrc))
4172 {
4173 AutoLock alock (that);
4174
4175 /* Remove the device from the collection */
4176 that->mUSBDevices.erase (*aIt);
4177 LogFlowFunc (("Detached device {%Vuuid}\n", (**aIt)->id().raw()));
4178
4179 /// @todo (dmik) REMOTE_USB
4180 // if the device is remote, notify a remote client that we have
4181 // detached the device
4182
4183 /* If it's a manual detach, give it back to the USB Proxy */
4184 if (aManual)
4185 {
4186 /*
4187 * Neither SessionMachine::ReleaseUSBDevice() nor Host::releaseUSBDevice()
4188 * should call the Console back, so keep the lock to provide atomicity
4189 * (to protect Host reapplying USB filters)
4190 */
4191 LogFlowFunc (("Giving it back it to USB proxy...\n"));
4192 HRESULT hrc = that->mControl->ReleaseUSBDevice (Guid (*aUuid));
4193 AssertComRC (hrc);
4194 vrc = SUCCEEDED (hrc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
4195 }
4196 }
4197
4198 LogFlowFunc (("vrc=%Vrc\n", vrc));
4199 LogFlowFuncLeave();
4200 return vrc;
4201}
4202
4203/**
4204 * Construct the VM configuration tree (CFGM).
4205 *
4206 * This is a callback for VMR3Create() call. It is called from CFGMR3Init()
4207 * in the emulation thread (EMT). Any per thread COM/XPCOM initialization
4208 * is done here.
4209 *
4210 * @param pVM VM handle.
4211 * @param pvTask Pointer to the VMPowerUpTask object.
4212 * @return VBox status code.
4213 *
4214 * @note Locks the Console object for writing.
4215 */
4216DECLCALLBACK(int) Console::configConstructor(PVM pVM, void *pvTask)
4217{
4218 LogFlowFuncEnter();
4219
4220 /* Note: the task pointer is owned by powerUpThread() */
4221 VMPowerUpTask *task = static_cast <VMPowerUpTask *> (pvTask);
4222 AssertReturn (task, VERR_GENERAL_FAILURE);
4223
4224#if defined(__WIN__)
4225 {
4226 /* initialize COM */
4227 HRESULT hrc = CoInitializeEx(NULL,
4228 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
4229 COINIT_SPEED_OVER_MEMORY);
4230 LogFlow (("Console::configConstructor(): CoInitializeEx()=%08X\n", hrc));
4231 AssertComRCReturn (hrc, VERR_GENERAL_FAILURE);
4232 }
4233#endif
4234
4235 ComObjPtr <Console> pConsole = task->mConsole;
4236
4237 AutoCaller autoCaller (pConsole);
4238 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
4239
4240 /* lock the console because we widely use internal fields and methods */
4241 AutoLock alock (pConsole);
4242
4243 ComPtr <IMachine> pMachine = pConsole->machine();
4244
4245 int rc;
4246 HRESULT hrc;
4247 char *psz = NULL;
4248 BSTR str = NULL;
4249 ULONG cRamMBs;
4250 unsigned i;
4251
4252#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
4253#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
4254#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
4255#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); return VERR_GENERAL_FAILURE; } } while (0)
4256
4257 /* Get necessary objects */
4258
4259 ComPtr<IVirtualBox> virtualBox;
4260 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
4261
4262 ComPtr<IHost> host;
4263 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
4264
4265 ComPtr <ISystemProperties> systemProperties;
4266 hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam()); H();
4267
4268 ComPtr<IBIOSSettings> biosSettings;
4269 hrc = pMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam()); H();
4270
4271
4272 /*
4273 * Get root node first.
4274 * This is the only node in the tree.
4275 */
4276 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4277 Assert(pRoot);
4278
4279 /*
4280 * Set the root level values.
4281 */
4282 hrc = pMachine->COMGETTER(Name)(&str); H();
4283 STR_CONV();
4284 rc = CFGMR3InsertString(pRoot, "Name", psz); RC_CHECK();
4285 STR_FREE();
4286 hrc = pMachine->COMGETTER(MemorySize)(&cRamMBs); H();
4287 rc = CFGMR3InsertInteger(pRoot, "RamSize", cRamMBs * _1M); RC_CHECK();
4288 rc = CFGMR3InsertInteger(pRoot, "TimerMillies", 10); RC_CHECK();
4289 rc = CFGMR3InsertInteger(pRoot, "RawR3Enabled", 1); /* boolean */ RC_CHECK();
4290 rc = CFGMR3InsertInteger(pRoot, "RawR0Enabled", 1); /* boolean */ RC_CHECK();
4291 /** @todo Config: RawR0, PATMEnabled and CASMEnabled needs attention later. */
4292 rc = CFGMR3InsertInteger(pRoot, "PATMEnabled", 1); /* boolean */ RC_CHECK();
4293 rc = CFGMR3InsertInteger(pRoot, "CSAMEnabled", 1); /* boolean */ RC_CHECK();
4294
4295 /* hardware virtualization extensions */
4296 TriStateBool_T hwVirtExEnabled;
4297 BOOL fHWVirtExEnabled;
4298 hrc = pMachine->COMGETTER(HWVirtExEnabled)(&hwVirtExEnabled); H();
4299 if (hwVirtExEnabled == TriStateBool_Default)
4300 {
4301 /* check the default value */
4302 hrc = systemProperties->COMGETTER(HWVirtExEnabled)(&fHWVirtExEnabled); H();
4303 }
4304 else
4305 fHWVirtExEnabled = (hwVirtExEnabled == TriStateBool_True);
4306 if (fHWVirtExEnabled)
4307 {
4308 PCFGMNODE pHWVirtExt;
4309 rc = CFGMR3InsertNode(pRoot, "HWVirtExt", &pHWVirtExt); RC_CHECK();
4310 rc = CFGMR3InsertInteger(pHWVirtExt, "Enabled", 1); RC_CHECK();
4311 }
4312
4313 BOOL fIOAPIC;
4314 hrc = biosSettings->COMGETTER(IOAPICEnabled)(&fIOAPIC); H();
4315
4316 /*
4317 * PDM config.
4318 * Load drivers in VBoxC.[so|dll]
4319 */
4320 PCFGMNODE pPDM;
4321 PCFGMNODE pDrivers;
4322 PCFGMNODE pMod;
4323 rc = CFGMR3InsertNode(pRoot, "PDM", &pPDM); RC_CHECK();
4324 rc = CFGMR3InsertNode(pPDM, "Drivers", &pDrivers); RC_CHECK();
4325 rc = CFGMR3InsertNode(pDrivers, "VBoxC", &pMod); RC_CHECK();
4326#ifdef VBOX_WITH_XPCOM
4327 // VBoxC is located in the components subdirectory
4328 char szPathProgram[RTPATH_MAX + sizeof("/components/VBoxC")];
4329 rc = RTPathProgram(szPathProgram, RTPATH_MAX); AssertRC(rc);
4330 strcat(szPathProgram, "/components/VBoxC");
4331 rc = CFGMR3InsertString(pMod, "Path", szPathProgram); RC_CHECK();
4332#else
4333 rc = CFGMR3InsertString(pMod, "Path", "VBoxC"); RC_CHECK();
4334#endif
4335
4336 /*
4337 * Devices
4338 */
4339 PCFGMNODE pDevices = NULL; /* /Devices */
4340 PCFGMNODE pDev = NULL; /* /Devices/Dev/ */
4341 PCFGMNODE pInst = NULL; /* /Devices/Dev/0/ */
4342 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
4343 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
4344 PCFGMNODE pLunL1 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
4345 rc = CFGMR3InsertNode(pRoot, "Devices", &pDevices); RC_CHECK();
4346
4347 /*
4348 * PC Arch.
4349 */
4350 rc = CFGMR3InsertNode(pDevices, "pcarch", &pDev); RC_CHECK();
4351 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4352 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4353 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4354
4355 /*
4356 * PC Bios.
4357 */
4358 rc = CFGMR3InsertNode(pDevices, "pcbios", &pDev); RC_CHECK();
4359 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4360 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4361 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4362 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
4363 rc = CFGMR3InsertString(pCfg, "HardDiskDevice", "piix3ide"); RC_CHECK();
4364 rc = CFGMR3InsertString(pCfg, "FloppyDevice", "i82078"); RC_CHECK();
4365
4366 DeviceType_T bootDevice;
4367 if (SchemaDefs::MaxBootPosition > 9)
4368 {
4369 AssertMsgFailed (("Too many boot devices %d\n",
4370 SchemaDefs::MaxBootPosition));
4371 return VERR_INVALID_PARAMETER;
4372 }
4373
4374 for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; pos ++)
4375 {
4376 hrc = pMachine->GetBootOrder(pos, &bootDevice); H();
4377
4378 char szParamName[] = "BootDeviceX";
4379 szParamName[sizeof (szParamName) - 2] = ((char (pos - 1)) + '0');
4380
4381 const char *pszBootDevice;
4382 switch (bootDevice)
4383 {
4384 case DeviceType_NoDevice:
4385 pszBootDevice = "NONE";
4386 break;
4387 case DeviceType_HardDiskDevice:
4388 pszBootDevice = "IDE";
4389 break;
4390 case DeviceType_DVDDevice:
4391 pszBootDevice = "DVD";
4392 break;
4393 case DeviceType_FloppyDevice:
4394 pszBootDevice = "FLOPPY";
4395 break;
4396 case DeviceType_NetworkDevice:
4397 pszBootDevice = "LAN";
4398 break;
4399 default:
4400 AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
4401 return VERR_INVALID_PARAMETER;
4402 }
4403 rc = CFGMR3InsertString(pCfg, szParamName, pszBootDevice); RC_CHECK();
4404 }
4405
4406 /*
4407 * BIOS logo
4408 */
4409 BOOL fFadeIn;
4410 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
4411 rc = CFGMR3InsertInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0); RC_CHECK();
4412 BOOL fFadeOut;
4413 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
4414 rc = CFGMR3InsertInteger(pCfg, "FadeOut", fFadeOut ? 1: 0); RC_CHECK();
4415 ULONG logoDisplayTime;
4416 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
4417 rc = CFGMR3InsertInteger(pCfg, "LogoTime", logoDisplayTime); RC_CHECK();
4418 Bstr logoImagePath;
4419 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
4420 rc = CFGMR3InsertString(pCfg, "LogoFile", logoImagePath ? Utf8Str(logoImagePath) : ""); RC_CHECK();
4421
4422 /*
4423 * Boot menu
4424 */
4425 BIOSBootMenuMode_T bootMenuMode;
4426 int value;
4427 biosSettings->COMGETTER(BootMenuMode)(&bootMenuMode);
4428 switch (bootMenuMode)
4429 {
4430 case BIOSBootMenuMode_Disabled:
4431 value = 0;
4432 break;
4433 case BIOSBootMenuMode_MenuOnly:
4434 value = 1;
4435 break;
4436 default:
4437 value = 2;
4438 }
4439 rc = CFGMR3InsertInteger(pCfg, "ShowBootMenu", value); RC_CHECK();
4440
4441 /*
4442 * ACPI
4443 */
4444 BOOL fACPI;
4445 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
4446 if (fACPI)
4447 {
4448 rc = CFGMR3InsertNode(pDevices, "acpi", &pDev); RC_CHECK();
4449 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4450 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4451 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4452 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
4453 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4454 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 7); RC_CHECK();
4455 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
4456
4457 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4458 rc = CFGMR3InsertString(pLunL0, "Driver", "ACPIHost"); RC_CHECK();
4459 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4460 }
4461
4462 /*
4463 * DMA
4464 */
4465 rc = CFGMR3InsertNode(pDevices, "8237A", &pDev); RC_CHECK();
4466 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4467 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4468
4469 /*
4470 * PCI bus.
4471 */
4472 rc = CFGMR3InsertNode(pDevices, "pci", &pDev); /* piix3 */ RC_CHECK();
4473 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4474 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4475 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4476 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4477
4478 /*
4479 * PS/2 keyboard & mouse.
4480 */
4481 rc = CFGMR3InsertNode(pDevices, "pckbd", &pDev); RC_CHECK();
4482 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4483 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4484 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4485
4486 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4487 rc = CFGMR3InsertString(pLunL0, "Driver", "KeyboardQueue"); RC_CHECK();
4488 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4489 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 64); RC_CHECK();
4490
4491 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4492 rc = CFGMR3InsertString(pLunL1, "Driver", "MainKeyboard"); RC_CHECK();
4493 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4494 Keyboard *pKeyboard = pConsole->mKeyboard;
4495 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pKeyboard); RC_CHECK();
4496
4497 rc = CFGMR3InsertNode(pInst, "LUN#1", &pLunL0); RC_CHECK();
4498 rc = CFGMR3InsertString(pLunL0, "Driver", "MouseQueue"); RC_CHECK();
4499 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4500 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 128); RC_CHECK();
4501
4502 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4503 rc = CFGMR3InsertString(pLunL1, "Driver", "MainMouse"); RC_CHECK();
4504 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4505 Mouse *pMouse = pConsole->mMouse;
4506 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pMouse); RC_CHECK();
4507
4508 /*
4509 * i82078 Floppy drive controller
4510 */
4511 ComPtr<IFloppyDrive> floppyDrive;
4512 hrc = pMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam()); H();
4513 BOOL fFloppyEnabled;
4514 hrc = floppyDrive->COMGETTER(Enabled)(&fFloppyEnabled); H();
4515 if (fFloppyEnabled)
4516 {
4517 rc = CFGMR3InsertNode(pDevices, "i82078", &pDev); RC_CHECK();
4518 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4519 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); RC_CHECK();
4520 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4521 rc = CFGMR3InsertInteger(pCfg, "IRQ", 6); RC_CHECK();
4522 rc = CFGMR3InsertInteger(pCfg, "DMA", 2); RC_CHECK();
4523 rc = CFGMR3InsertInteger(pCfg, "MemMapped", 0 ); RC_CHECK();
4524 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x3f0); RC_CHECK();
4525
4526 /* Attach the status driver */
4527 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
4528 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
4529 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4530 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapFDLeds[0]); RC_CHECK();
4531 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
4532 rc = CFGMR3InsertInteger(pCfg, "Last", 0); RC_CHECK();
4533
4534 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4535
4536 ComPtr<IFloppyImage> floppyImage;
4537 hrc = floppyDrive->GetImage(floppyImage.asOutParam()); H();
4538 if (floppyImage)
4539 {
4540 pConsole->meFloppyState = DriveState_ImageMounted;
4541 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4542 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4543 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
4544 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4545
4546 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4547 rc = CFGMR3InsertString(pLunL1, "Driver", "RawImage"); RC_CHECK();
4548 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4549 hrc = floppyImage->COMGETTER(FilePath)(&str); H();
4550 STR_CONV();
4551 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4552 STR_FREE();
4553 }
4554 else
4555 {
4556 ComPtr<IHostFloppyDrive> hostFloppyDrive;
4557 hrc = floppyDrive->GetHostDrive(hostFloppyDrive.asOutParam()); H();
4558 if (hostFloppyDrive)
4559 {
4560 pConsole->meFloppyState = DriveState_HostDriveCaptured;
4561 rc = CFGMR3InsertString(pLunL0, "Driver", "HostFloppy"); RC_CHECK();
4562 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4563 hrc = hostFloppyDrive->COMGETTER(Name)(&str); H();
4564 STR_CONV();
4565 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4566 STR_FREE();
4567 }
4568 else
4569 {
4570 pConsole->meFloppyState = DriveState_NotMounted;
4571 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4572 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4573 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
4574 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4575 }
4576 }
4577 }
4578
4579 /*
4580 * i8254 Programmable Interval Timer And Dummy Speaker
4581 */
4582 rc = CFGMR3InsertNode(pDevices, "i8254", &pDev); RC_CHECK();
4583 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4584 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4585#ifdef DEBUG
4586 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4587#endif
4588
4589 /*
4590 * i8259 Programmable Interrupt Controller.
4591 */
4592 rc = CFGMR3InsertNode(pDevices, "i8259", &pDev); RC_CHECK();
4593 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4594 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4595 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4596
4597 /*
4598 * Advanced Programmable Interrupt Controller.
4599 */
4600 rc = CFGMR3InsertNode(pDevices, "apic", &pDev); RC_CHECK();
4601 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4602 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4603 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4604
4605 if (fIOAPIC)
4606 {
4607 /*
4608 * I/O Advanced Programmable Interrupt Controller.
4609 */
4610 rc = CFGMR3InsertNode(pDevices, "ioapic", &pDev); RC_CHECK();
4611 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4612 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4613 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4614 }
4615
4616 /*
4617 * RTC MC146818.
4618 */
4619 rc = CFGMR3InsertNode(pDevices, "mc146818", &pDev); RC_CHECK();
4620 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4621 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4622
4623#if 0
4624 /*
4625 * Serial ports
4626 */
4627 rc = CFGMR3InsertNode(pDevices, "serial", &pDev); RC_CHECK();
4628 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4629 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4630 rc = CFGMR3InsertInteger(pCfg, "IRQ", 4); RC_CHECK();
4631 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x3f8); RC_CHECK();
4632
4633 rc = CFGMR3InsertNode(pDev, "1", &pInst); RC_CHECK();
4634 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4635 rc = CFGMR3InsertInteger(pCfg, "IRQ", 3); RC_CHECK();
4636 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x2f8); RC_CHECK();
4637#endif
4638
4639 /*
4640 * VGA.
4641 */
4642 rc = CFGMR3InsertNode(pDevices, "vga", &pDev); RC_CHECK();
4643 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4644 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4645 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 2); RC_CHECK();
4646 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
4647 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4648 hrc = pMachine->COMGETTER(VRAMSize)(&cRamMBs); H();
4649 rc = CFGMR3InsertInteger(pCfg, "VRamSize", cRamMBs * _1M); RC_CHECK();
4650
4651 /* Custom VESA mode list */
4652 unsigned cModes = 0;
4653 for (unsigned iMode = 1; iMode <= 16; iMode++)
4654 {
4655 char szExtraDataKey[sizeof("CustomVideoModeXX")];
4656 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%d", iMode);
4657 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey), &str); H();
4658 if (!str || !*str)
4659 break;
4660 STR_CONV();
4661 rc = CFGMR3InsertString(pCfg, szExtraDataKey, psz);
4662 STR_FREE();
4663 cModes++;
4664 }
4665 rc = CFGMR3InsertInteger(pCfg, "CustomVideoModes", cModes);
4666
4667 /* VESA height reduction */
4668 ULONG ulHeightReduction;
4669 IFramebuffer *pFramebuffer = pConsole->getDisplay()->getFramebuffer();
4670 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
4671 rc = CFGMR3InsertInteger(pCfg, "HeightReduction", ulHeightReduction); RC_CHECK();
4672
4673 /* Attach the display. */
4674 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4675 rc = CFGMR3InsertString(pLunL0, "Driver", "MainDisplay"); RC_CHECK();
4676 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4677 Display *pDisplay = pConsole->mDisplay;
4678 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pDisplay); RC_CHECK();
4679
4680 /*
4681 * IDE (update this when the main interface changes)
4682 */
4683 rc = CFGMR3InsertNode(pDevices, "piix3ide", &pDev); /* piix3 */ RC_CHECK();
4684 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4685 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4686 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 1); RC_CHECK();
4687 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 1); RC_CHECK();
4688 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4689
4690 /* Attach the status driver */
4691 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
4692 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
4693 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4694 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapIDELeds[0]);RC_CHECK();
4695 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
4696 rc = CFGMR3InsertInteger(pCfg, "Last", 3); RC_CHECK();
4697
4698 /* Attach the harddisks */
4699 ComPtr<IHardDiskAttachmentCollection> hdaColl;
4700 hrc = pMachine->COMGETTER(HardDiskAttachments)(hdaColl.asOutParam()); H();
4701 ComPtr<IHardDiskAttachmentEnumerator> hdaEnum;
4702 hrc = hdaColl->Enumerate(hdaEnum.asOutParam()); H();
4703
4704 BOOL fMore = FALSE;
4705 while ( SUCCEEDED(hrc = hdaEnum->HasMore(&fMore))
4706 && fMore)
4707 {
4708 ComPtr<IHardDiskAttachment> hda;
4709 hrc = hdaEnum->GetNext(hda.asOutParam()); H();
4710 ComPtr<IHardDisk> hardDisk;
4711 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
4712 DiskControllerType_T enmCtl;
4713 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
4714 LONG lDev;
4715 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
4716
4717 switch (enmCtl)
4718 {
4719 case DiskControllerType_IDE0Controller:
4720 i = 0;
4721 break;
4722 case DiskControllerType_IDE1Controller:
4723 i = 2;
4724 break;
4725 default:
4726 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
4727 return VERR_GENERAL_FAILURE;
4728 }
4729
4730 if (lDev < 0 || lDev >= 2)
4731 {
4732 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
4733 return VERR_GENERAL_FAILURE;
4734 }
4735
4736 i = i + lDev;
4737
4738 char szLUN[16];
4739 RTStrPrintf(szLUN, sizeof(szLUN), "LUN#%d", i);
4740 rc = CFGMR3InsertNode(pInst, szLUN, &pLunL0); RC_CHECK();
4741 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4742 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4743 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
4744 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
4745
4746 HardDiskStorageType_T hddType;
4747 hardDisk->COMGETTER(StorageType)(&hddType);
4748 if (hddType == HardDiskStorageType_VirtualDiskImage)
4749 {
4750 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4751 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
4752 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4753 /// @todo (dmik) we temporarily use the location property to
4754 // determine the image file name. This is subject to change
4755 // when iSCSI disks are here (we should either query a
4756 // storage-specific interface from IHardDisk, or "standardize"
4757 // the location property)
4758 hrc = hardDisk->COMGETTER(Location)(&str); H();
4759 STR_CONV();
4760 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4761 STR_FREE();
4762
4763 /* Create an inversed tree of parents. */
4764 ComPtr<IHardDisk> parentHardDisk = hardDisk;
4765 for (PCFGMNODE pParent = pCfg;;)
4766 {
4767 ComPtr<IHardDisk> curHardDisk;
4768 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
4769 if (!curHardDisk)
4770 break;
4771
4772 PCFGMNODE pCur;
4773 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
4774 /// @todo (dmik) we temporarily use the location property to
4775 // determine the image file name. This is subject to change
4776 // when iSCSI disks are here (we should either query a
4777 // storage-specific interface from IHardDisk, or "standardize"
4778 // the location property)
4779 hrc = curHardDisk->COMGETTER(Location)(&str); H();
4780 STR_CONV();
4781 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
4782 STR_FREE();
4783
4784 /* next */
4785 pParent = pCur;
4786 parentHardDisk = curHardDisk;
4787 }
4788 }
4789 else if (hddType == HardDiskStorageType_ISCSIHardDisk)
4790 {
4791 ComPtr<IISCSIHardDisk> iSCSIDisk = hardDisk;
4792
4793 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4794 rc = CFGMR3InsertString(pLunL1, "Driver", "iSCSI"); RC_CHECK();
4795 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4796
4797 /* Set up the iSCSI initiator driver configuration. */
4798 hrc = iSCSIDisk->COMGETTER(Target)(&str); H();
4799 STR_CONV();
4800 rc = CFGMR3InsertString(pCfg, "TargetName", psz); RC_CHECK();
4801 STR_FREE();
4802
4803 // @todo currently there is no Initiator name config.
4804 rc = CFGMR3InsertString(pCfg, "InitiatorName", "iqn.2006-02.de.innotek.initiator"); RC_CHECK();
4805
4806 ULONG64 lun;
4807 hrc = iSCSIDisk->COMGETTER(Lun)(&lun); H();
4808 rc = CFGMR3InsertInteger(pCfg, "LUN", lun); RC_CHECK();
4809
4810 hrc = iSCSIDisk->COMGETTER(Server)(&str); H();
4811 STR_CONV();
4812 USHORT port;
4813 hrc = iSCSIDisk->COMGETTER(Port)(&port); H();
4814 if (port != 0)
4815 {
4816 char *pszTN;
4817 RTStrAPrintf(&pszTN, "%s:%u", psz, port);
4818 rc = CFGMR3InsertString(pCfg, "TargetAddress", pszTN); RC_CHECK();
4819 RTStrFree(pszTN);
4820 }
4821 else
4822 {
4823 rc = CFGMR3InsertString(pCfg, "TargetAddress", psz); RC_CHECK();
4824 }
4825 STR_FREE();
4826
4827 hrc = iSCSIDisk->COMGETTER(UserName)(&str); H();
4828 if (str)
4829 {
4830 STR_CONV();
4831 rc = CFGMR3InsertString(pCfg, "InitiatorUsername", psz); RC_CHECK();
4832 STR_FREE();
4833 }
4834
4835 hrc = iSCSIDisk->COMGETTER(Password)(&str); H();
4836 if (str)
4837 {
4838 STR_CONV();
4839 rc = CFGMR3InsertString(pCfg, "InitiatorSecret", psz); RC_CHECK();
4840 STR_FREE();
4841 }
4842
4843 // @todo currently there is no target username config.
4844 //rc = CFGMR3InsertString(pCfg, "TargetUsername", ""); RC_CHECK();
4845
4846 // @todo currently there is no target password config.
4847 //rc = CFGMR3InsertString(pCfg, "TargetSecret", ""); RC_CHECK();
4848
4849 /* The iSCSI initiator needs an attached iSCSI transport driver. */
4850 PCFGMNODE pLunL2 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/AttachedDriver */
4851 rc = CFGMR3InsertNode(pLunL1, "AttachedDriver", &pLunL2); RC_CHECK();
4852 rc = CFGMR3InsertString(pLunL2, "Driver", "iSCSITCP"); RC_CHECK();
4853 /* Currently the transport driver has no config options. */
4854 }
4855 else
4856 AssertFailed();
4857 }
4858 H();
4859
4860 ComPtr<IDVDDrive> dvdDrive;
4861 hrc = pMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam()); H();
4862 if (dvdDrive)
4863 {
4864 // ASSUME: DVD drive is always attached to LUN#2 (i.e. secondary IDE master)
4865 rc = CFGMR3InsertNode(pInst, "LUN#2", &pLunL0); RC_CHECK();
4866 ComPtr<IHostDVDDrive> hostDvdDrive;
4867 hrc = dvdDrive->GetHostDrive(hostDvdDrive.asOutParam()); H();
4868 if (hostDvdDrive)
4869 {
4870 pConsole->meDVDState = DriveState_HostDriveCaptured;
4871 rc = CFGMR3InsertString(pLunL0, "Driver", "HostDVD"); RC_CHECK();
4872 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4873 hrc = hostDvdDrive->COMGETTER(Name)(&str); H();
4874 STR_CONV();
4875 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4876 STR_FREE();
4877 BOOL fPassthrough;
4878 hrc = dvdDrive->COMGETTER(Passthrough)(&fPassthrough); H();
4879 rc = CFGMR3InsertInteger(pCfg, "Passthrough", !!fPassthrough); RC_CHECK();
4880 }
4881 else
4882 {
4883 pConsole->meDVDState = DriveState_NotMounted;
4884 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4885 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4886 rc = CFGMR3InsertString(pCfg, "Type", "DVD"); RC_CHECK();
4887 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4888
4889 ComPtr<IDVDImage> dvdImage;
4890 hrc = dvdDrive->GetImage(dvdImage.asOutParam()); H();
4891 if (dvdImage)
4892 {
4893 pConsole->meDVDState = DriveState_ImageMounted;
4894 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4895 rc = CFGMR3InsertString(pLunL1, "Driver", "MediaISO"); RC_CHECK();
4896 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4897 hrc = dvdImage->COMGETTER(FilePath)(&str); H();
4898 STR_CONV();
4899 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4900 STR_FREE();
4901 }
4902 }
4903 }
4904
4905 /*
4906 * Network adapters
4907 */
4908 rc = CFGMR3InsertNode(pDevices, "pcnet", &pDev); RC_CHECK();
4909 //rc = CFGMR3InsertNode(pDevices, "ne2000", &pDev); RC_CHECK();
4910 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::NetworkAdapterCount; ulInstance++)
4911 {
4912 ComPtr<INetworkAdapter> networkAdapter;
4913 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
4914 BOOL fEnabled = FALSE;
4915 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabled); H();
4916 if (!fEnabled)
4917 continue;
4918
4919 char szInstance[4]; Assert(ulInstance <= 999);
4920 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
4921 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
4922 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4923 /* the first network card gets the PCI ID 3, the followings starting from 8 */
4924 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", !ulInstance ? 3 : ulInstance - 1 + 8); RC_CHECK();
4925 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
4926 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4927
4928 /*
4929 * The virtual hardware type.
4930 */
4931 NetworkAdapterType_T adapterType;
4932 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
4933 switch (adapterType)
4934 {
4935 case NetworkAdapterType_NetworkAdapterAm79C970A:
4936 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 0); RC_CHECK();
4937 break;
4938 case NetworkAdapterType_NetworkAdapterAm79C973:
4939 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 1); RC_CHECK();
4940 break;
4941 default:
4942 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
4943 adapterType, ulInstance));
4944 return VERR_GENERAL_FAILURE;
4945 }
4946
4947 /*
4948 * Get the MAC address and convert it to binary representation
4949 */
4950 Bstr macAddr;
4951 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
4952 Assert(macAddr);
4953 Utf8Str macAddrUtf8 = macAddr;
4954 char *macStr = (char*)macAddrUtf8.raw();
4955 Assert(strlen(macStr) == 12);
4956 PDMMAC Mac;
4957 memset(&Mac, 0, sizeof(Mac));
4958 char *pMac = (char*)&Mac;
4959 for (uint32_t i = 0; i < 6; i++)
4960 {
4961 char c1 = *macStr++ - '0';
4962 if (c1 > 9)
4963 c1 -= 7;
4964 char c2 = *macStr++ - '0';
4965 if (c2 > 9)
4966 c2 -= 7;
4967 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
4968 }
4969 rc = CFGMR3InsertBytes(pCfg, "MAC", &Mac, sizeof(Mac)); RC_CHECK();
4970
4971 /*
4972 * Check if the cable is supposed to be unplugged
4973 */
4974 BOOL fCableConnected;
4975 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
4976 rc = CFGMR3InsertInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0); RC_CHECK();
4977
4978 /*
4979 * Attach the status driver.
4980 */
4981 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
4982 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
4983 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4984 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapNetworkLeds[ulInstance]); RC_CHECK();
4985
4986 /*
4987 * Enable the packet sniffer if requested.
4988 */
4989 BOOL fSniffer;
4990 hrc = networkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
4991 if (fSniffer)
4992 {
4993 /* insert the sniffer filter driver. */
4994 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4995 rc = CFGMR3InsertString(pLunL0, "Driver", "NetSniffer"); RC_CHECK();
4996 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4997 hrc = networkAdapter->COMGETTER(TraceFile)(&str); H();
4998 if (str) /* check convention for indicating default file. */
4999 {
5000 STR_CONV();
5001 rc = CFGMR3InsertString(pCfg, "File", psz); RC_CHECK();
5002 STR_FREE();
5003 }
5004 }
5005
5006 NetworkAttachmentType_T networkAttachment;
5007 hrc = networkAdapter->COMGETTER(AttachmentType)(&networkAttachment); H();
5008 switch (networkAttachment)
5009 {
5010 case NetworkAttachmentType_NoNetworkAttachment:
5011 break;
5012
5013 case NetworkAttachmentType_NATNetworkAttachment:
5014 {
5015 if (fSniffer)
5016 {
5017 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5018 }
5019 else
5020 {
5021 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5022 }
5023 rc = CFGMR3InsertString(pLunL0, "Driver", "NAT"); RC_CHECK();
5024 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5025 /* (Port forwarding goes here.) */
5026 break;
5027 }
5028
5029 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
5030 {
5031 /*
5032 * Perform the attachment if required (don't return on error!)
5033 */
5034 hrc = pConsole->attachToHostInterface(networkAdapter);
5035 if (SUCCEEDED(hrc))
5036 {
5037#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5038 Assert (pConsole->maTapFD[ulInstance] >= 0);
5039 if (pConsole->maTapFD[ulInstance] >= 0)
5040 {
5041 if (fSniffer)
5042 {
5043 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5044 }
5045 else
5046 {
5047 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5048 }
5049 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5050 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5051 rc = CFGMR3InsertInteger(pCfg, "FileHandle", pConsole->maTapFD[ulInstance]); RC_CHECK();
5052 }
5053#elif defined(__WIN__)
5054 if (fSniffer)
5055 {
5056 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5057 }
5058 else
5059 {
5060 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5061 }
5062 Bstr hostInterfaceName;
5063 hrc = networkAdapter->COMGETTER(HostInterface)(hostInterfaceName.asOutParam()); H();
5064 ComPtr<IHostNetworkInterfaceCollection> coll;
5065 hrc = host->COMGETTER(NetworkInterfaces)(coll.asOutParam()); H();
5066 ComPtr<IHostNetworkInterface> hostInterface;
5067 rc = coll->FindByName(hostInterfaceName, hostInterface.asOutParam());
5068 if (!SUCCEEDED(rc))
5069 {
5070 AssertMsgFailed(("Cannot get GUID for host interface '%ls'\n", hostInterfaceName));
5071 hrc = networkAdapter->Detach(); H();
5072 }
5073 else
5074 {
5075 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5076 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5077 rc = CFGMR3InsertString(pCfg, "HostInterfaceName", Utf8Str(hostInterfaceName)); RC_CHECK();
5078 Guid hostIFGuid;
5079 hrc = hostInterface->COMGETTER(Id)(hostIFGuid.asOutParam()); H();
5080 char szDriverGUID[256] = {0};
5081 /* add curly brackets */
5082 szDriverGUID[0] = '{';
5083 strcpy(szDriverGUID + 1, hostIFGuid.toString().raw());
5084 strcat(szDriverGUID, "}");
5085 rc = CFGMR3InsertBytes(pCfg, "GUID", szDriverGUID, sizeof(szDriverGUID)); RC_CHECK();
5086 }
5087#else
5088# error "Port me"
5089#endif
5090 }
5091 else
5092 {
5093 switch (hrc)
5094 {
5095#ifdef __LINUX__
5096 case VERR_ACCESS_DENIED:
5097 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5098 "Failed to open '/dev/net/tun' for read/write access. Please check the "
5099 "permissions of that node. Either do 'chmod 0666 /dev/net/tun' or "
5100 "change the group of that node and get member of that group. Make "
5101 "sure that these changes are permanently in particular if you are "
5102 "using udev"));
5103#endif /* __LINUX__ */
5104 default:
5105 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
5106 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5107 "Failed to initialize Host Interface Networking"));
5108 }
5109 }
5110 break;
5111 }
5112
5113 case NetworkAttachmentType_InternalNetworkAttachment:
5114 {
5115 hrc = networkAdapter->COMGETTER(InternalNetwork)(&str); H();
5116 STR_CONV();
5117 if (psz && *psz)
5118 {
5119 if (fSniffer)
5120 {
5121 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5122 }
5123 else
5124 {
5125 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5126 }
5127 rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet"); RC_CHECK();
5128 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5129 rc = CFGMR3InsertString(pCfg, "Network", psz); RC_CHECK();
5130 }
5131 STR_FREE();
5132 break;
5133 }
5134
5135 default:
5136 AssertMsgFailed(("should not get here!\n"));
5137 break;
5138 }
5139 }
5140
5141 /*
5142 * VMM Device
5143 */
5144 rc = CFGMR3InsertNode(pDevices, "VMMDev", &pDev); RC_CHECK();
5145 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5146 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5147 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5148 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 4); RC_CHECK();
5149 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5150
5151 /* the VMM device's Main driver */
5152 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5153 rc = CFGMR3InsertString(pLunL0, "Driver", "MainVMMDev"); RC_CHECK();
5154 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5155 VMMDev *pVMMDev = pConsole->mVMMDev;
5156 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pVMMDev); RC_CHECK();
5157
5158 /*
5159 * Audio Sniffer Device
5160 */
5161 rc = CFGMR3InsertNode(pDevices, "AudioSniffer", &pDev); RC_CHECK();
5162 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5163 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5164
5165 /* the Audio Sniffer device's Main driver */
5166 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5167 rc = CFGMR3InsertString(pLunL0, "Driver", "MainAudioSniffer"); RC_CHECK();
5168 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5169 AudioSniffer *pAudioSniffer = pConsole->mAudioSniffer;
5170 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pAudioSniffer); RC_CHECK();
5171
5172 /*
5173 * AC'97 ICH audio
5174 */
5175 ComPtr<IAudioAdapter> audioAdapter;
5176 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
5177 BOOL enabled = FALSE;
5178 if (audioAdapter)
5179 {
5180 hrc = audioAdapter->COMGETTER(Enabled)(&enabled); H();
5181 }
5182 if (enabled)
5183 {
5184 rc = CFGMR3InsertNode(pDevices, "ichac97", &pDev); /* ichac97 */
5185 rc = CFGMR3InsertNode(pDev, "0", &pInst);
5186 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5187 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 5); RC_CHECK();
5188 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5189 rc = CFGMR3InsertNode(pInst, "Config", &pCfg);
5190
5191 /* the Audio driver */
5192 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5193 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
5194 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5195 AudioDriverType_T audioDriver;
5196 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
5197 switch (audioDriver)
5198 {
5199 case AudioDriverType_NullAudioDriver:
5200 {
5201 rc = CFGMR3InsertString(pCfg, "AudioDriver", "null"); RC_CHECK();
5202 break;
5203 }
5204#ifdef __WIN__
5205 case AudioDriverType_WINMMAudioDriver:
5206 {
5207 rc = CFGMR3InsertString(pCfg, "AudioDriver", "winmm"); RC_CHECK();
5208 break;
5209 }
5210 case AudioDriverType_DSOUNDAudioDriver:
5211 {
5212 rc = CFGMR3InsertString(pCfg, "AudioDriver", "dsound"); RC_CHECK();
5213 break;
5214 }
5215#endif /* !__LINUX__ */
5216#ifdef __LINUX__
5217 case AudioDriverType_OSSAudioDriver:
5218 {
5219 rc = CFGMR3InsertString(pCfg, "AudioDriver", "oss"); RC_CHECK();
5220 break;
5221 }
5222#ifdef VBOX_WITH_ALSA
5223 case AudioDriverType_ALSAAudioDriver:
5224 {
5225 rc = CFGMR3InsertString(pCfg, "AudioDriver", "alsa"); RC_CHECK();
5226 break;
5227 }
5228#endif
5229#endif /* __LINUX__ */
5230 }
5231 }
5232
5233 /*
5234 * The USB Controller.
5235 */
5236 ComPtr<IUSBController> USBCtlPtr;
5237 hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
5238 if (USBCtlPtr)
5239 {
5240 BOOL fEnabled;
5241 hrc = USBCtlPtr->COMGETTER(Enabled)(&fEnabled); H();
5242 if (fEnabled)
5243 {
5244 rc = CFGMR3InsertNode(pDevices, "usb-ohci", &pDev); RC_CHECK();
5245 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5246 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5247 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5248 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 6); RC_CHECK();
5249 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5250
5251 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5252 rc = CFGMR3InsertString(pLunL0, "Driver", "VUSBRootHub"); RC_CHECK();
5253 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5254 }
5255 }
5256
5257 /*
5258 * Clipboard
5259 */
5260 {
5261 ClipboardMode_T mode = ClipboardMode_ClipDisabled;
5262 hrc = pMachine->COMGETTER(ClipboardMode) (&mode); H();
5263
5264 if (mode != ClipboardMode_ClipDisabled)
5265 {
5266 /* Load the service */
5267 rc = pConsole->mVMMDev->hgcmLoadService ("VBoxSharedClipboard", "VBoxSharedClipboard");
5268
5269 if (VBOX_FAILURE (rc))
5270 {
5271 LogRel(("VBoxSharedClipboard is not available. rc = %Vrc\n", rc));
5272 /* That is not a fatal failure. */
5273 rc = VINF_SUCCESS;
5274 }
5275 else
5276 {
5277 /* Setup the service. */
5278 VBOXHGCMSVCPARM parm;
5279
5280 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
5281
5282 switch (mode)
5283 {
5284 default:
5285 case ClipboardMode_ClipDisabled:
5286 {
5287 LogRel(("VBoxSharedClipboard mode: Off\n"));
5288 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
5289 break;
5290 }
5291 case ClipboardMode_ClipGuestToHost:
5292 {
5293 LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
5294 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
5295 break;
5296 }
5297 case ClipboardMode_ClipHostToGuest:
5298 {
5299 LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
5300 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
5301 break;
5302 }
5303 case ClipboardMode_ClipBidirectional:
5304 {
5305 LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
5306 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
5307 break;
5308 }
5309 }
5310
5311 pConsole->mVMMDev->hgcmHostCall ("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
5312
5313 Log(("Set VBoxSharedClipboard mode\n"));
5314 }
5315 }
5316 }
5317
5318 /*
5319 * CFGM overlay handling.
5320 *
5321 * Here we check the extra data entries for CFGM values
5322 * and create the nodes and insert the values on the fly. Existing
5323 * values will be removed and reinserted. If a value is a valid number,
5324 * it will be inserted as a number, otherwise as a string.
5325 *
5326 * We first perform a run on global extra data, then on the machine
5327 * extra data to support global settings with local overrides.
5328 *
5329 */
5330 Bstr strExtraDataKey;
5331 bool fGlobalExtraData = true;
5332 for (;;)
5333 {
5334 Bstr strNextExtraDataKey;
5335 Bstr strExtraDataValue;
5336
5337 /* get the next key */
5338 if (fGlobalExtraData)
5339 hrc = virtualBox->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5340 strExtraDataValue.asOutParam());
5341 else
5342 hrc = pMachine->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5343 strExtraDataValue.asOutParam());
5344
5345 /* stop if for some reason there's nothing more to request */
5346 if (FAILED(hrc) || !strNextExtraDataKey)
5347 {
5348 /* if we're out of global keys, continue with machine, otherwise we're done */
5349 if (fGlobalExtraData)
5350 {
5351 fGlobalExtraData = false;
5352 strExtraDataKey.setNull();
5353 continue;
5354 }
5355 break;
5356 }
5357
5358 strExtraDataKey = strNextExtraDataKey;
5359 Utf8Str strExtraDataKeyUtf8 = Utf8Str(strExtraDataKey);
5360
5361 /* we only care about keys starting with "VBoxInternal/" */
5362 if (strncmp(strExtraDataKeyUtf8.raw(), "VBoxInternal/", 13) != 0)
5363 continue;
5364 char *pszExtraDataKey = (char*)strExtraDataKeyUtf8.raw() + 13;
5365
5366 /* the key will be in the format "Node1/Node2/Value" or simply "Value". */
5367 PCFGMNODE pNode;
5368 char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
5369 if (pszCFGMValueName)
5370 {
5371 /* terminate the node and advance to the value */
5372 *pszCFGMValueName = '\0';
5373 pszCFGMValueName++;
5374
5375 /* does the node already exist? */
5376 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
5377 if (pNode)
5378 {
5379 /* the value might already exist, remove it to be safe */
5380 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5381 }
5382 else
5383 {
5384 /* create the node */
5385 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
5386 AssertMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
5387 if (VBOX_FAILURE(rc) || !pNode)
5388 continue;
5389 }
5390 }
5391 else
5392 {
5393 pNode = pRoot;
5394 pszCFGMValueName = pszExtraDataKey;
5395 pszExtraDataKey--;
5396
5397 /* the value might already exist, remove it to be safe */
5398 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5399 }
5400
5401 /* now let's have a look at the value */
5402 Utf8Str strCFGMValueUtf8 = Utf8Str(strExtraDataValue);
5403 const char *pszCFGMValue = strCFGMValueUtf8.raw();
5404 /* empty value means remove value which we've already done */
5405 if (pszCFGMValue && *pszCFGMValue)
5406 {
5407 /* if it's a valid number, we'll insert it as such, otherwise string */
5408 uint64_t u64Value;
5409 if (RTStrToUInt64Ex(pszCFGMValue, NULL, 0, &u64Value) == VINF_SUCCESS)
5410 {
5411 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
5412 }
5413 else
5414 {
5415 rc = CFGMR3InsertString(pNode, pszCFGMValueName, pszCFGMValue);
5416 }
5417 AssertMsgRC(rc, ("failed to insert CFGM value '%s' to key '%s'\n", pszCFGMValue, pszExtraDataKey));
5418 }
5419 }
5420
5421#undef H
5422#undef RC_CHECK
5423#undef STR_FREE
5424#undef STR_CONV
5425
5426 /* Register VM state change handler */
5427 int rc2 = VMR3AtStateRegister (pVM, Console::vmstateChangeCallback, pConsole);
5428 AssertRC (rc2);
5429 if (VBOX_SUCCESS (rc))
5430 rc = rc2;
5431
5432 /* Register VM runtime error handler */
5433 rc2 = VMR3AtRuntimeErrorRegister (pVM, Console::setVMRuntimeErrorCallback, pConsole);
5434 AssertRC (rc2);
5435 if (VBOX_SUCCESS (rc))
5436 rc = rc2;
5437
5438 /* Save the VM pointer in the machine object */
5439 pConsole->mpVM = pVM;
5440
5441 LogFlowFunc (("vrc = %Vrc\n", rc));
5442 LogFlowFuncLeave();
5443
5444 return rc;
5445}
5446
5447/**
5448 * Helper function to handle host interface device creation and attachment.
5449 *
5450 * @param networkAdapter the network adapter which attachment should be reset
5451 * @return COM status code
5452 *
5453 * @note The caller must lock this object for writing.
5454 */
5455HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5456{
5457 /* sanity check */
5458 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5459
5460#ifdef DEBUG
5461 /* paranoia */
5462 NetworkAttachmentType_T attachment;
5463 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5464 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5465#endif /* DEBUG */
5466
5467 HRESULT rc = S_OK;
5468
5469#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5470 ULONG slot = 0;
5471 rc = networkAdapter->COMGETTER(Slot)(&slot);
5472 AssertComRC(rc);
5473
5474 /*
5475 * Try get the FD.
5476 */
5477 LONG ltapFD;
5478 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5479 if (SUCCEEDED(rc))
5480 maTapFD[slot] = (RTFILE)ltapFD;
5481 else
5482 maTapFD[slot] = NIL_RTFILE;
5483
5484 /*
5485 * Are we supposed to use an existing TAP interface?
5486 */
5487 if (maTapFD[slot] != NIL_RTFILE)
5488 {
5489 /* nothing to do */
5490 Assert(ltapFD >= 0);
5491 Assert((LONG)maTapFD[slot] == ltapFD);
5492 rc = S_OK;
5493 }
5494 else
5495#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5496 {
5497 /*
5498 * Allocate a host interface device
5499 */
5500#ifdef __WIN__
5501 /* nothing to do */
5502 int rcVBox = VINF_SUCCESS;
5503#elif defined(__LINUX__)
5504 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5505 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5506 if (VBOX_SUCCESS(rcVBox))
5507 {
5508 /*
5509 * Set/obtain the tap interface.
5510 */
5511 struct ifreq IfReq;
5512 memset(&IfReq, 0, sizeof(IfReq));
5513 Bstr tapDeviceName;
5514 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5515 if (FAILED(rc) || tapDeviceName.isEmpty())
5516 strcpy(IfReq.ifr_name, "tap%d");
5517 else
5518 {
5519 Utf8Str str(tapDeviceName);
5520 if (str.length() <= sizeof(IfReq.ifr_name))
5521 strcpy(IfReq.ifr_name, str.raw());
5522 else
5523 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5524 }
5525 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5526 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5527 if (!rcVBox)
5528 {
5529 /*
5530 * Make it pollable.
5531 */
5532 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5533 {
5534 tapDeviceName = IfReq.ifr_name;
5535 if (tapDeviceName)
5536 {
5537 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5538
5539 /*
5540 * Here is the right place to communicate the TAP file descriptor and
5541 * the host interface name to the server if/when it becomes really
5542 * necessary.
5543 */
5544 maTAPDeviceName[slot] = tapDeviceName;
5545 rcVBox = VINF_SUCCESS;
5546 rc = S_OK;
5547 }
5548 else
5549 rcVBox = VERR_NO_MEMORY;
5550 }
5551 else
5552 {
5553 AssertMsgFailed(("Configuration error: Failed to configure /dev/net/tun non blocking. errno=%d\n", errno));
5554 rcVBox = VERR_HOSTIF_BLOCKING;
5555 rc = setError(E_FAIL, "Failed to set /dev/net/tun to non blocking. errno=%d\n", errno);
5556 }
5557 }
5558 else
5559 {
5560 AssertMsgFailed(("Configuration error: Failed to configure /dev/net/tun. errno=%d\n", errno));
5561 rcVBox = VERR_HOSTIF_IOCTL;
5562 rc = setError(E_FAIL, "Failed to configure /dev/net/tun. errno = %d\n", errno);
5563 }
5564 }
5565 else
5566 {
5567 AssertMsgFailed(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5568 switch (rcVBox)
5569 {
5570 case VERR_ACCESS_DENIED:
5571 /* will be handled by our caller */
5572 LogRel(("HERE\n"));
5573 rc = rcVBox;
5574 break;
5575 default:
5576 rc = setError(E_FAIL, "Failed to open /dev/net/tun rc = %Vrc\n", rcVBox);
5577 break;
5578 }
5579 }
5580#elif defined(__DARWIN__)
5581 /** @todo Implement tap networking for Darwin. */
5582 int rcVBox = VERR_NOT_IMPLEMENTED;
5583#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
5584# error "PORTME: Implement OS specific TAP interface open/creation."
5585#else
5586# error "Unknown host OS"
5587#endif
5588 /* in case of failure, cleanup. */
5589 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5590 {
5591 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5592 }
5593 }
5594#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5595 if (SUCCEEDED(rc))
5596 {
5597 /*
5598 * Call the initialization program.
5599 *
5600 * The initialization program is passed the device name as the first param.
5601 * The second parameter is the decimal value of the file handle of the device
5602 * which it inherits.
5603 */
5604 Bstr tapSetupApplication;
5605 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5606 if (tapSetupApplication)
5607 {
5608 /*
5609 * Create the argument list.
5610 */
5611 const char *apszArgs[4];
5612 /* 0. The program name. */
5613 Utf8Str tapSetupApp(tapSetupApplication);
5614 apszArgs[0] = tapSetupApp.raw();
5615
5616 /* 1. The file descriptor. */
5617 char szFD[32];
5618 RTStrPrintf(szFD, sizeof(szFD), "%RTfile", maTapFD[slot]);
5619 apszArgs[1] = szFD;
5620
5621 /* 2. The device name (optional). */
5622 apszArgs[2] = maTAPDeviceName[slot].isEmpty() ? NULL : maTAPDeviceName[slot].raw();
5623
5624 /* 3. The end. */
5625 apszArgs[3] = NULL;
5626
5627 /*
5628 * Create the process and wait for it to complete.
5629 */
5630 RTPROCESS Process;
5631 int rcVBox = RTProcCreate(apszArgs[0], &apszArgs[0], NULL, 0, &Process);
5632 if (VBOX_SUCCESS(rcVBox))
5633 {
5634 /* wait for the process to exit */
5635 RTPROCSTATUS ProcStatus;
5636 rcVBox = RTProcWait(Process, RTPROCWAIT_FLAGS_BLOCK, &ProcStatus);
5637 AssertRC(rcVBox);
5638 if (VBOX_SUCCESS(rcVBox))
5639 {
5640 if ( ProcStatus.enmReason == RTPROCEXITREASON_NORMAL
5641 && ProcStatus.iStatus == 0)
5642 rcVBox = VINF_SUCCESS;
5643 else
5644 rcVBox = VMSetError(mpVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_("Failed to initialize Host Interface Networking"));
5645 }
5646 }
5647 else
5648 {
5649 AssertMsgFailed(("Configuration error: Failed to start init program \"%s\", rc=%Vra\n", tapSetupApp.raw(), rcVBox));
5650 rc = setError(E_FAIL, "Failed to start init program \"%s\", rc = %Vra\n", tapSetupApp.raw(), rcVBox);
5651 }
5652
5653 /* in case of failure, cleanup. */
5654 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5655 {
5656 rc = setError(E_FAIL, tr ("General failure configuring Host Interface Networking"));
5657 }
5658 }
5659 }
5660#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5661 return rc;
5662}
5663
5664/**
5665 * Helper function to handle detachment from a host interface
5666 *
5667 * @param networkAdapter the network adapter which attachment should be reset
5668 * @return COM status code
5669 *
5670 * @note The caller must lock this object for writing.
5671 */
5672HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5673{
5674 /* sanity check */
5675 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5676
5677 HRESULT rc = S_OK;
5678#ifdef DEBUG
5679 /* paranoia */
5680 NetworkAttachmentType_T attachment;
5681 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5682 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5683#endif /* DEBUG */
5684
5685#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5686
5687 ULONG slot = 0;
5688 rc = networkAdapter->COMGETTER(Slot)(&slot);
5689 AssertComRC(rc);
5690
5691 /* is there an open TAP device? */
5692 if (maTapFD[slot] != NIL_RTFILE)
5693 {
5694 /*
5695 * Execute term command and close the file handle.
5696 */
5697 Bstr tapTerminateApplication;
5698 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5699 if (tapTerminateApplication)
5700 {
5701 /*
5702 * Create the argument list
5703 */
5704 const char *apszArgs[4];
5705 /* 0. The program name. */
5706 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5707 apszArgs[0] = tapTermAppUtf8.raw();
5708
5709 /* 1. The file descriptor. */
5710 char szFD[32];
5711 RTStrPrintf(szFD, sizeof(szFD), "%RTfile", maTapFD[slot]);
5712 apszArgs[1] = szFD;
5713
5714 /* 2. Device name (optional). */
5715 apszArgs[2] = maTAPDeviceName[slot].isEmpty() ? NULL : maTAPDeviceName[slot].raw();
5716
5717 /* 3. The end. */
5718 apszArgs[3] = NULL;
5719
5720 /*
5721 * Create the process and wait for it to complete.
5722 */
5723 RTPROCESS Process;
5724 int rcVBox = RTProcCreate(apszArgs[0], &apszArgs[0], NULL, 0, &Process);
5725 if (VBOX_SUCCESS(rcVBox))
5726 {
5727 /* wait for the process to exit */
5728 RTPROCSTATUS ProcStatus;
5729 rcVBox = RTProcWait(Process, RTPROCWAIT_FLAGS_BLOCK, &ProcStatus);
5730 AssertRC(rcVBox);
5731 /* ignore return code? */
5732 }
5733 else
5734 AssertMsgFailed(("Configuration error: Failed to start terminate program \"%s\", rc=%Vra\n", apszArgs[0], rcVBox)); /** @todo last error candidate. */
5735 if (VBOX_FAILURE(rcVBox))
5736 rc = E_FAIL;
5737 }
5738
5739 /*
5740 * Now we can close the file handle.
5741 */
5742 int rcVBox = RTFileClose(maTapFD[slot]);
5743 AssertRC(rcVBox);
5744 /* the TAP device name and handle are no longer valid */
5745 maTapFD[slot] = NIL_RTFILE;
5746 maTAPDeviceName[slot] = "";
5747 }
5748#endif
5749 return rc;
5750}
5751
5752
5753/**
5754 * Called at power down to terminate host interface networking.
5755 *
5756 * @note The caller must lock this object for writing.
5757 */
5758HRESULT Console::powerDownHostInterfaces()
5759{
5760 LogFlowThisFunc (("\n"));
5761
5762 /* sanity check */
5763 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5764
5765 /*
5766 * host interface termination handling
5767 */
5768 HRESULT rc;
5769 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
5770 {
5771 ComPtr<INetworkAdapter> networkAdapter;
5772 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
5773 CheckComRCBreakRC (rc);
5774
5775 BOOL enabled = FALSE;
5776 networkAdapter->COMGETTER(Enabled) (&enabled);
5777 if (!enabled)
5778 continue;
5779
5780 NetworkAttachmentType_T attachment;
5781 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5782 if (attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment)
5783 {
5784 HRESULT rc2 = detachFromHostInterface(networkAdapter);
5785 if (FAILED(rc2) && SUCCEEDED(rc))
5786 rc = rc2;
5787 }
5788 }
5789
5790 return rc;
5791}
5792
5793
5794/**
5795 * Process callback handler for VMR3Load and VMR3Save.
5796 *
5797 * @param pVM The VM handle.
5798 * @param uPercent Completetion precentage (0-100).
5799 * @param pvUser Pointer to the VMProgressTask structure.
5800 * @return VINF_SUCCESS.
5801 */
5802/*static*/ DECLCALLBACK (int)
5803Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
5804{
5805 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5806 AssertReturn (task, VERR_INVALID_PARAMETER);
5807
5808 /* update the progress object */
5809 if (task->mProgress)
5810 task->mProgress->notifyProgress (uPercent);
5811
5812 return VINF_SUCCESS;
5813}
5814
5815/**
5816 * VM error callback function. Called by the various VM components.
5817 *
5818 * @param pVM The VM handle. Can be NULL if an error occurred before
5819 * successfully creating a VM.
5820 * @param pvUser Pointer to the VMProgressTask structure.
5821 * @param rc VBox status code.
5822 * @param pszFormat The error message.
5823 * @thread EMT.
5824 */
5825/* static */ DECLCALLBACK (void)
5826Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
5827 const char *pszFormat, va_list args)
5828{
5829 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5830 AssertReturnVoid (task);
5831
5832 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
5833 HRESULT hrc = setError (E_FAIL, tr ("%N.\n"
5834 "VBox status code: %d (%Vrc)"),
5835 tr (pszFormat), &args,
5836 rc, rc);
5837 task->mProgress->notifyComplete (hrc);
5838}
5839
5840/**
5841 * VM runtime error callback function.
5842 * See VMSetRuntimeError for the detailed description of parameters.
5843 *
5844 * @param pVM The VM handle.
5845 * @param pvUser The user argument.
5846 * @param fFatal Whether it is a fatal error or not.
5847 * @param pszErrorID Error ID string.
5848 * @param pszFormat Error message format string.
5849 * @param args Error message arguments.
5850 * @thread EMT.
5851 */
5852/* static */ DECLCALLBACK(void)
5853Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
5854 const char *pszErrorID,
5855 const char *pszFormat, va_list args)
5856{
5857 LogFlowFuncEnter();
5858
5859 Console *that = static_cast <Console *> (pvUser);
5860 AssertReturnVoid (that);
5861
5862 Utf8Str message = Utf8StrFmt (pszFormat, args);
5863
5864 LogRel (("Console: VM runtime error: fatal=%RTbool, "
5865 "errorID=%s message=\"%s\"\n",
5866 fFatal, pszErrorID, message.raw()));
5867
5868 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
5869
5870 LogFlowFuncLeave();
5871}
5872
5873/**
5874 * Captures and attaches USB devices to a newly created VM.
5875 *
5876 * @param pVM The VM handle.
5877 *
5878 * @note The caller must lock this object for writing.
5879 */
5880HRESULT Console::captureUSBDevices (PVM pVM)
5881{
5882 LogFlowThisFunc (("\n"));
5883
5884 /* sanity check */
5885 ComAssertRet (isLockedOnCurrentThread(), E_FAIL);
5886
5887 /*
5888 * If the machine has an USB controller, capture devices and attach
5889 * them to it.
5890 */
5891 PPDMIBASE pBase;
5892 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
5893 if (VBOX_SUCCESS (vrc))
5894 {
5895 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
5896 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
5897 ComAssertRet (pRhConfig, E_FAIL);
5898
5899 /*
5900 * Get the list of USB devices that should be captured and attached to
5901 * the newly created machine.
5902 */
5903 ComPtr <IUSBDeviceCollection> coll;
5904 HRESULT hrc = mControl->AutoCaptureUSBDevices (coll.asOutParam());
5905 ComAssertComRCRetRC (hrc);
5906
5907 /*
5908 * Enumerate the devices and attach them.
5909 * Failing to attach an device is currently ignored and the device
5910 * released.
5911 */
5912 ComPtr <IUSBDeviceEnumerator> en;
5913 hrc = coll->Enumerate (en.asOutParam());
5914 ComAssertComRCRetRC (hrc);
5915
5916 BOOL hasMore = FALSE;
5917 while (SUCCEEDED (en->HasMore (&hasMore)) && hasMore)
5918 {
5919 ComPtr <IUSBDevice> hostDevice;
5920 hrc = en->GetNext (hostDevice.asOutParam());
5921 ComAssertComRCRetRC (hrc);
5922 ComAssertRet (!hostDevice.isNull(), E_FAIL);
5923
5924 hrc = attachUSBDevice (hostDevice, true /* aManual */, pRhConfig);
5925
5926 /// @todo (r=dmik) warning reporting subsystem
5927 }
5928 }
5929 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
5930 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
5931 vrc = VINF_SUCCESS;
5932 else
5933 AssertRC (vrc);
5934
5935 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
5936}
5937
5938
5939/**
5940 * Releases all USB device which is attached to the VM for the
5941 * purpose of clean up and such like.
5942 *
5943 * @note The caller must lock this object for writing.
5944 */
5945void Console::releaseAllUSBDevices (void)
5946{
5947 LogFlowThisFunc (("\n"));
5948
5949 /* sanity check */
5950 AssertReturnVoid (isLockedOnCurrentThread());
5951
5952 mControl->ReleaseAllUSBDevices();
5953 mUSBDevices.clear();
5954}
5955
5956/**
5957 * @note Locks this object for writing.
5958 */
5959#ifdef VRDP_MC
5960void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
5961#else
5962void Console::processRemoteUSBDevices (VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
5963#endif /* VRDP_MC */
5964{
5965 LogFlowThisFuncEnter();
5966#ifdef VRDP_MC
5967 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
5968#else
5969 LogFlowThisFunc (("pDevList=%p, cbDevList = %d\n", pDevList, cbDevList));
5970#endif /* VRDP_MC */
5971
5972 AutoCaller autoCaller (this);
5973 if (!autoCaller.isOk())
5974 {
5975 /* Console has been already uninitialized, deny request */
5976 AssertMsgFailed (("Temporary assertion to prove that it happens, "
5977 "please report to dmik\n"));
5978 LogFlowThisFunc (("Console is already uninitialized\n"));
5979 LogFlowThisFuncLeave();
5980 return;
5981 }
5982
5983 AutoLock alock (this);
5984
5985 /*
5986 * Mark all existing remote USB devices as dirty.
5987 */
5988 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
5989 while (it != mRemoteUSBDevices.end())
5990 {
5991 (*it)->dirty (true);
5992 ++ it;
5993 }
5994
5995 /*
5996 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
5997 */
5998 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
5999 VRDPUSBDEVICEDESC *e = pDevList;
6000
6001 /* The cbDevList condition must be checked first, because the function can
6002 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6003 */
6004 while (cbDevList >= 2 && e->oNext)
6005 {
6006 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6007 e->idVendor, e->idProduct,
6008 e->oProduct? (char *)e + e->oProduct: ""));
6009
6010 bool fNewDevice = true;
6011
6012 it = mRemoteUSBDevices.begin();
6013 while (it != mRemoteUSBDevices.end())
6014 {
6015#ifdef VRDP_MC
6016 if ((*it)->devId () == e->id
6017 && (*it)->clientId () == u32ClientId)
6018#else
6019 if ((*it)->devId () == e->id)
6020#endif /* VRDP_MC */
6021 {
6022 /* The device is already in the list. */
6023 (*it)->dirty (false);
6024 fNewDevice = false;
6025 break;
6026 }
6027
6028 ++ it;
6029 }
6030
6031 if (fNewDevice)
6032 {
6033 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6034 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6035 ));
6036
6037 /* Create the device object and add the new device to list. */
6038 ComObjPtr <RemoteUSBDevice> device;
6039 device.createObject();
6040#ifdef VRDP_MC
6041 device->init (u32ClientId, e);
6042#else
6043 device->init (e);
6044#endif /* VRDP_MC */
6045
6046 mRemoteUSBDevices.push_back (device);
6047
6048 /* Check if the device is ok for current USB filters. */
6049 BOOL fMatched = FALSE;
6050
6051 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched);
6052
6053 AssertComRC (hrc);
6054
6055 LogFlowThisFunc (("USB filters return %d\n", fMatched));
6056
6057 if (fMatched)
6058 {
6059 hrc = onUSBDeviceAttach(device);
6060
6061 /// @todo (r=dmik) warning reporting subsystem
6062
6063 if (hrc == S_OK)
6064 {
6065 LogFlowThisFunc (("Device attached\n"));
6066 device->captured (true);
6067 }
6068 }
6069 }
6070
6071 if (cbDevList < e->oNext)
6072 {
6073 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6074 cbDevList, e->oNext));
6075 break;
6076 }
6077
6078 cbDevList -= e->oNext;
6079
6080 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6081 }
6082
6083 /*
6084 * Remove dirty devices, that is those which are not reported by the server anymore.
6085 */
6086 for (;;)
6087 {
6088 ComObjPtr <RemoteUSBDevice> device;
6089
6090 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6091 while (it != mRemoteUSBDevices.end())
6092 {
6093 if ((*it)->dirty ())
6094 {
6095 device = *it;
6096 break;
6097 }
6098
6099 ++ it;
6100 }
6101
6102 if (!device)
6103 {
6104 break;
6105 }
6106
6107 USHORT vendorId = 0;
6108 device->COMGETTER(VendorId) (&vendorId);
6109
6110 USHORT productId = 0;
6111 device->COMGETTER(ProductId) (&productId);
6112
6113 Bstr product;
6114 device->COMGETTER(Product) (product.asOutParam());
6115
6116 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6117 vendorId, productId, product.raw ()
6118 ));
6119
6120 /* Detach the device from VM. */
6121 if (device->captured ())
6122 {
6123 Guid uuid;
6124 device->COMGETTER (Id) (uuid.asOutParam());
6125 onUSBDeviceDetach (uuid);
6126 }
6127
6128 /* And remove it from the list. */
6129 mRemoteUSBDevices.erase (it);
6130 }
6131
6132 LogFlowThisFuncLeave();
6133}
6134
6135
6136
6137/**
6138 * Thread function which starts the VM (also from saved state) and
6139 * track progress.
6140 *
6141 * @param Thread The thread id.
6142 * @param pvUser Pointer to a VMPowerUpTask structure.
6143 * @return VINF_SUCCESS (ignored).
6144 *
6145 * @note Locks the Console object for writing.
6146 */
6147/*static*/
6148DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6149{
6150 LogFlowFuncEnter();
6151
6152 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6153 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6154
6155 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6156 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6157
6158#if defined(__WIN__)
6159 {
6160 /* initialize COM */
6161 HRESULT hrc = CoInitializeEx (NULL,
6162 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6163 COINIT_SPEED_OVER_MEMORY);
6164 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6165 }
6166#endif
6167
6168 HRESULT hrc = S_OK;
6169 int vrc = VINF_SUCCESS;
6170
6171 ComObjPtr <Console> console = task->mConsole;
6172
6173 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6174
6175 AutoLock alock (console);
6176
6177 /* sanity */
6178 Assert (console->mpVM == NULL);
6179
6180 do
6181 {
6182 /*
6183 * Initialize the release logging facility. In case something
6184 * goes wrong, there will be no release logging. Maybe in the future
6185 * we can add some logic to use different file names in this case.
6186 * Note that the logic must be in sync with Machine::DeleteSettings().
6187 */
6188
6189 Bstr logFolder;
6190 hrc = console->mControl->GetLogFolder (logFolder.asOutParam());
6191 CheckComRCBreakRC (hrc);
6192
6193 Utf8Str logDir = logFolder;
6194
6195 /* make sure the Logs folder exists */
6196 Assert (!logDir.isEmpty());
6197 if (!RTDirExists (logDir))
6198 RTDirCreateFullPath (logDir, 0777);
6199
6200 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
6201 logDir.raw(), RTPATH_DELIMITER);
6202
6203 /*
6204 * Age the old log files
6205 * Rename .2 to .3, .1 to .2 and the last log file to .1
6206 * Overwrite target files in case they exist;
6207 */
6208 for (int i = 2; i >= 0; i--)
6209 {
6210 Utf8Str oldName;
6211 if (i > 0)
6212 oldName = Utf8StrFmt ("%s.%d", logFile.raw(), i);
6213 else
6214 oldName = logFile;
6215 Utf8Str newName = Utf8StrFmt ("%s.%d", logFile.raw(), i + 1);
6216 RTFileRename(oldName.raw(), newName.raw(), RTFILEMOVE_FLAGS_REPLACE);
6217 }
6218
6219 PRTLOGGER loggerRelease;
6220 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
6221 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
6222#ifdef __WIN__
6223 fFlags |= RTLOGFLAGS_USECRLF;
6224#endif /* __WIN__ */
6225 vrc = RTLogCreate(&loggerRelease, fFlags, "all",
6226 "VBOX_RELEASE_LOG", ELEMENTS(s_apszGroups), s_apszGroups,
6227 RTLOGDEST_FILE, logFile.raw());
6228 if (VBOX_SUCCESS(vrc))
6229 {
6230 /* some introductory information */
6231 RTTIMESPEC timeSpec;
6232 char nowUct[64];
6233 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
6234 RTLogRelLogger(loggerRelease, 0, ~0U,
6235 "VirtualBox %d.%d.%d (%s %s) release log\n"
6236 "Log opened %s\n",
6237 VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD,
6238 __DATE__, __TIME__,
6239 nowUct);
6240
6241 /* register this logger as the release logger */
6242 RTLogRelSetDefaultInstance(loggerRelease);
6243 }
6244 else
6245 {
6246 hrc = setError (E_FAIL,
6247 tr ("Failed to open release log file '%s' (%Vrc)"),
6248 logFile.raw(), vrc);
6249 break;
6250 }
6251
6252#ifdef VBOX_VRDP
6253 if (VBOX_SUCCESS (vrc))
6254 {
6255 /* Create the VRDP server. In case of headless operation, this will
6256 * also create the framebuffer, required at VM creation.
6257 */
6258 ConsoleVRDPServer *server = console->consoleVRDPServer();
6259 Assert (server);
6260 /// @todo (dmik)
6261 // does VRDP server call Console from the other thread?
6262 // Not sure, so leave the lock just in case
6263 alock.leave();
6264 vrc = server->Launch();
6265 alock.enter();
6266 if (VBOX_FAILURE (vrc))
6267 {
6268 Utf8Str errMsg;
6269 switch (vrc)
6270 {
6271 case VERR_NET_ADDRESS_IN_USE:
6272 {
6273 ULONG port = 0;
6274 console->mVRDPServer->COMGETTER(Port) (&port);
6275 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6276 port);
6277 break;
6278 }
6279 default:
6280 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6281 vrc);
6282 }
6283 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6284 vrc, errMsg.raw()));
6285 hrc = setError (E_FAIL, errMsg);
6286 break;
6287 }
6288 }
6289#endif /* VBOX_VRDP */
6290
6291 /*
6292 * Create the VM
6293 */
6294 PVM pVM;
6295 /*
6296 * leave the lock since EMT will call Console. It's safe because
6297 * mMachineState is either Starting or Restoring state here.
6298 */
6299 alock.leave();
6300
6301 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6302 task->mConfigConstructor, task.get(),
6303 &pVM);
6304
6305 alock.enter();
6306
6307#ifdef VBOX_VRDP
6308 {
6309 /* Enable client connections to the server. */
6310 ConsoleVRDPServer *server = console->consoleVRDPServer();
6311 server->SetCallback ();
6312 }
6313#endif /* VBOX_VRDP */
6314
6315 if (VBOX_SUCCESS (vrc))
6316 {
6317 do
6318 {
6319 /*
6320 * Register our load/save state file handlers
6321 */
6322 vrc = SSMR3RegisterExternal (pVM,
6323 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6324 0 /* cbGuess */,
6325 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6326 static_cast <Console *> (console));
6327 AssertRC (vrc);
6328 if (VBOX_FAILURE (vrc))
6329 break;
6330
6331 /*
6332 * Synchronize debugger settings
6333 */
6334 MachineDebugger *machineDebugger = console->getMachineDebugger();
6335 if (machineDebugger)
6336 {
6337 machineDebugger->flushQueuedSettings();
6338 }
6339
6340 if (console->getVMMDev()->getShFlClientId())
6341 {
6342 /// @todo (dmik)
6343 // does the code below call Console from the other thread?
6344 // Not sure, so leave the lock just in case
6345 alock.leave();
6346
6347 /*
6348 * Shared Folders
6349 */
6350 for (std::map <Bstr, ComPtr <ISharedFolder> >::const_iterator
6351 it = task->mSharedFolders.begin();
6352 it != task->mSharedFolders.end();
6353 ++ it)
6354 {
6355 Bstr name = (*it).first;
6356 ComPtr <ISharedFolder> folder = (*it).second;
6357
6358 Bstr hostPath;
6359 hrc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
6360 CheckComRCBreakRC (hrc);
6361
6362 LogFlowFunc (("Adding shared folder '%ls' -> '%ls'\n",
6363 name.raw(), hostPath.raw()));
6364 ComAssertBreak (!name.isEmpty() && !hostPath.isEmpty(),
6365 hrc = E_FAIL);
6366
6367 /** @todo should move this into the shared folder class */
6368 VBOXHGCMSVCPARM parms[2];
6369 SHFLSTRING *pFolderName, *pMapName;
6370 int cbString;
6371
6372 cbString = (hostPath.length() + 1) * sizeof(RTUCS2);
6373 pFolderName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6374 Assert(pFolderName);
6375 memcpy(pFolderName->String.ucs2, hostPath.raw(), cbString);
6376
6377 pFolderName->u16Size = cbString;
6378 pFolderName->u16Length = cbString - sizeof(RTUCS2);
6379
6380 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
6381 parms[0].u.pointer.addr = pFolderName;
6382 parms[0].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6383
6384 cbString = (name.length() + 1) * sizeof(RTUCS2);
6385 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6386 Assert(pMapName);
6387 memcpy(pMapName->String.ucs2, name.raw(), cbString);
6388
6389 pMapName->u16Size = cbString;
6390 pMapName->u16Length = cbString - sizeof(RTUCS2);
6391
6392 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
6393 parms[1].u.pointer.addr = pMapName;
6394 parms[1].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6395
6396 vrc = console->getVMMDev()->hgcmHostCall("VBoxSharedFolders",
6397 SHFL_FN_ADD_MAPPING, 2, &parms[0]);
6398
6399 RTMemFree(pFolderName);
6400 RTMemFree(pMapName);
6401
6402 if (VBOX_FAILURE (vrc))
6403 {
6404 hrc = setError (E_FAIL,
6405 tr ("Unable to add mapping '%ls' to '%ls' (%Vrc)"),
6406 hostPath.raw(), name.raw(), vrc);
6407 break;
6408 }
6409 }
6410
6411 /* enter the lock again */
6412 alock.enter();
6413
6414 CheckComRCBreakRC (hrc);
6415 }
6416
6417 /*
6418 * Capture USB devices.
6419 */
6420 hrc = console->captureUSBDevices (pVM);
6421 CheckComRCBreakRC (hrc);
6422
6423 /* leave the lock before a lengthy operation */
6424 alock.leave();
6425
6426 /* Load saved state? */
6427 if (!!task->mSavedStateFile)
6428 {
6429 LogFlowFunc (("Restoring saved state from '%s'...\n",
6430 task->mSavedStateFile.raw()));
6431
6432 vrc = VMR3Load (pVM, task->mSavedStateFile,
6433 Console::stateProgressCallback,
6434 static_cast <VMProgressTask *> (task.get()));
6435
6436 /* Start/Resume the VM execution */
6437 if (VBOX_SUCCESS (vrc))
6438 {
6439 vrc = VMR3Resume (pVM);
6440 AssertRC (vrc);
6441 }
6442
6443 /* Power off in case we failed loading or resuming the VM */
6444 if (VBOX_FAILURE (vrc))
6445 {
6446 int vrc2 = VMR3PowerOff (pVM);
6447 AssertRC (vrc2);
6448 }
6449 }
6450 else
6451 {
6452 /* Power on the VM (i.e. start executing) */
6453 vrc = VMR3PowerOn(pVM);
6454 AssertRC (vrc);
6455 }
6456
6457 /* enter the lock again */
6458 alock.enter();
6459 }
6460 while (0);
6461
6462 /* On failure, destroy the VM */
6463 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6464 {
6465 /* preserve the current error info */
6466 ErrorInfo ei;
6467
6468 /*
6469 * powerDown() will call VMR3Destroy() and do all necessary
6470 * cleanup (VRDP, USB devices)
6471 */
6472 HRESULT hrc2 = console->powerDown();
6473 AssertComRC (hrc2);
6474
6475 setError (ei);
6476 }
6477 }
6478 else
6479 {
6480 /*
6481 * If VMR3Create() failed it has released the VM memory.
6482 */
6483 console->mpVM = NULL;
6484 }
6485
6486 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6487 {
6488 /*
6489 * If VMR3Create() or one of the other calls in this function fail,
6490 * an appropriate error message has been already set. However since
6491 * that happens via a callback, the status code in this function is
6492 * not updated.
6493 */
6494 if (!task->mProgress->completed())
6495 {
6496 /*
6497 * If the COM error info is not yet set but we've got a
6498 * failure, convert the VBox status code into a meaningful
6499 * error message. This becomes unused once all the sources of
6500 * errors set the appropriate error message themselves.
6501 * Note that we don't use VMSetError() below because pVM is
6502 * either invalid or NULL here.
6503 */
6504 AssertMsgFailed (("Missing error message during powerup for "
6505 "status code %Vrc\n", vrc));
6506 hrc = setError (E_FAIL,
6507 tr ("Failed to start VM execution (%Vrc)"), vrc);
6508 }
6509 else
6510 hrc = task->mProgress->resultCode();
6511
6512 Assert (FAILED (hrc));
6513 break;
6514 }
6515 }
6516 while (0);
6517
6518 if (console->mMachineState == MachineState_Starting ||
6519 console->mMachineState == MachineState_Restoring)
6520 {
6521 /*
6522 * We are still in the Starting/Restoring state. This means one of:
6523 * 1) we failed before VMR3Create() was called;
6524 * 2) VMR3Create() failed.
6525 * In both cases, there is no need to call powerDown(), but we still
6526 * need to go back to the PoweredOff/Saved state. Reuse
6527 * vmstateChangeCallback() for that purpose.
6528 */
6529
6530 /* preserve the current error info */
6531 ErrorInfo ei;
6532
6533 Assert (console->mpVM == NULL);
6534 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6535 console);
6536 setError (ei);
6537 }
6538
6539 /*
6540 * Evaluate the final result.
6541 * Note that the appropriate mMachineState value is already set by
6542 * vmstateChangeCallback() in all cases.
6543 */
6544
6545 /* leave the lock, don't need it any more */
6546 alock.leave();
6547
6548 if (SUCCEEDED (hrc))
6549 {
6550 /* Notify the progress object of the success */
6551 task->mProgress->notifyComplete (S_OK);
6552 }
6553 else
6554 {
6555 if (!task->mProgress->completed())
6556 {
6557 /* The progress object will fetch the current error info. This
6558 * gets the errors signalled by using setError(). The ones
6559 * signalled via VMSetError() immediately notify the progress
6560 * object that the operation is completed. */
6561 task->mProgress->notifyComplete (hrc);
6562 }
6563
6564 LogRel (("Power up failed (vrc=%Vrc, hrc=0x%08X)\n", vrc, hrc));
6565 }
6566
6567#if defined(__WIN__)
6568 /* uninitialize COM */
6569 CoUninitialize();
6570#endif
6571
6572 LogFlowFuncLeave();
6573
6574 return VINF_SUCCESS;
6575}
6576
6577
6578/**
6579 * Reconfigures a VDI.
6580 *
6581 * @param pVM The VM handle.
6582 * @param hda The harddisk attachment.
6583 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6584 * @return VBox status code.
6585 */
6586static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6587{
6588 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6589
6590 int rc;
6591 HRESULT hrc;
6592 char *psz = NULL;
6593 BSTR str = NULL;
6594 *phrc = S_OK;
6595#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
6596#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6597#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6598#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6599
6600 /*
6601 * Figure out which IDE device this is.
6602 */
6603 ComPtr<IHardDisk> hardDisk;
6604 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6605 DiskControllerType_T enmCtl;
6606 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
6607 LONG lDev;
6608 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
6609
6610 int i;
6611 switch (enmCtl)
6612 {
6613 case DiskControllerType_IDE0Controller:
6614 i = 0;
6615 break;
6616 case DiskControllerType_IDE1Controller:
6617 i = 2;
6618 break;
6619 default:
6620 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
6621 return VERR_GENERAL_FAILURE;
6622 }
6623
6624 if (lDev < 0 || lDev >= 2)
6625 {
6626 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6627 return VERR_GENERAL_FAILURE;
6628 }
6629
6630 i = i + lDev;
6631
6632 /*
6633 * Is there an existing LUN? If not create it.
6634 * We ASSUME that this will NEVER collide with the DVD.
6635 */
6636 PCFGMNODE pCfg;
6637 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", i);
6638 if (!pLunL1)
6639 {
6640 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6641 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6642
6643 PCFGMNODE pLunL0;
6644 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", i); RC_CHECK();
6645 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6646 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6647 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6648 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6649
6650 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6651 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6652 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6653 }
6654 else
6655 {
6656#ifdef VBOX_STRICT
6657 char *pszDriver;
6658 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6659 Assert(!strcmp(pszDriver, "VBoxHDD"));
6660 MMR3HeapFree(pszDriver);
6661#endif
6662
6663 /*
6664 * Check if things has changed.
6665 */
6666 pCfg = CFGMR3GetChild(pLunL1, "Config");
6667 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6668
6669 /* the image */
6670 /// @todo (dmik) we temporarily use the location property to
6671 // determine the image file name. This is subject to change
6672 // when iSCSI disks are here (we should either query a
6673 // storage-specific interface from IHardDisk, or "standardize"
6674 // the location property)
6675 hrc = hardDisk->COMGETTER(Location)(&str); H();
6676 STR_CONV();
6677 char *pszPath;
6678 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6679 if (!strcmp(psz, pszPath))
6680 {
6681 /* parent images. */
6682 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6683 for (PCFGMNODE pParent = pCfg;;)
6684 {
6685 MMR3HeapFree(pszPath);
6686 pszPath = NULL;
6687 STR_FREE();
6688
6689 /* get parent */
6690 ComPtr<IHardDisk> curHardDisk;
6691 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6692 PCFGMNODE pCur;
6693 pCur = CFGMR3GetChild(pParent, "Parent");
6694 if (!pCur && !curHardDisk)
6695 {
6696 /* no change */
6697 LogFlowFunc (("No change!\n"));
6698 return VINF_SUCCESS;
6699 }
6700 if (!pCur || !curHardDisk)
6701 break;
6702
6703 /* compare paths. */
6704 /// @todo (dmik) we temporarily use the location property to
6705 // determine the image file name. This is subject to change
6706 // when iSCSI disks are here (we should either query a
6707 // storage-specific interface from IHardDisk, or "standardize"
6708 // the location property)
6709 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6710 STR_CONV();
6711 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6712 if (strcmp(psz, pszPath))
6713 break;
6714
6715 /* next */
6716 pParent = pCur;
6717 parentHardDisk = curHardDisk;
6718 }
6719
6720 }
6721 else
6722 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", i, pszPath));
6723
6724 MMR3HeapFree(pszPath);
6725 STR_FREE();
6726
6727 /*
6728 * Detach the driver and replace the config node.
6729 */
6730 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, i); RC_CHECK();
6731 CFGMR3RemoveNode(pCfg);
6732 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6733 }
6734
6735 /*
6736 * Create the driver configuration.
6737 */
6738 /// @todo (dmik) we temporarily use the location property to
6739 // determine the image file name. This is subject to change
6740 // when iSCSI disks are here (we should either query a
6741 // storage-specific interface from IHardDisk, or "standardize"
6742 // the location property)
6743 hrc = hardDisk->COMGETTER(Location)(&str); H();
6744 STR_CONV();
6745 LogFlowFunc (("LUN#%d: leaf image '%s'\n", i, psz));
6746 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6747 STR_FREE();
6748 /* Create an inversed tree of parents. */
6749 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6750 for (PCFGMNODE pParent = pCfg;;)
6751 {
6752 ComPtr<IHardDisk> curHardDisk;
6753 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6754 if (!curHardDisk)
6755 break;
6756
6757 PCFGMNODE pCur;
6758 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6759 /// @todo (dmik) we temporarily use the location property to
6760 // determine the image file name. This is subject to change
6761 // when iSCSI disks are here (we should either query a
6762 // storage-specific interface from IHardDisk, or "standardize"
6763 // the location property)
6764 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6765 STR_CONV();
6766 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6767 STR_FREE();
6768
6769 /* next */
6770 pParent = pCur;
6771 parentHardDisk = curHardDisk;
6772 }
6773
6774 /*
6775 * Attach the new driver.
6776 */
6777 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, i, NULL); RC_CHECK();
6778
6779 LogFlowFunc (("Returns success\n"));
6780 return rc;
6781}
6782
6783
6784/**
6785 * Thread for executing the saved state operation.
6786 *
6787 * @param Thread The thread handle.
6788 * @param pvUser Pointer to a VMSaveTask structure.
6789 * @return VINF_SUCCESS (ignored).
6790 *
6791 * @note Locks the Console object for writing.
6792 */
6793/*static*/
6794DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6795{
6796 LogFlowFuncEnter();
6797
6798 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6799 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6800
6801 Assert (!task->mSavedStateFile.isNull());
6802 Assert (!task->mProgress.isNull());
6803
6804 const ComObjPtr <Console> &that = task->mConsole;
6805
6806 /*
6807 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6808 * protect mpVM because VMSaveTask does that
6809 */
6810
6811 Utf8Str errMsg;
6812 HRESULT rc = S_OK;
6813
6814 if (task->mIsSnapshot)
6815 {
6816 Assert (!task->mServerProgress.isNull());
6817 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6818
6819 rc = task->mServerProgress->WaitForCompletion (-1);
6820 if (SUCCEEDED (rc))
6821 {
6822 HRESULT result = S_OK;
6823 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6824 if (SUCCEEDED (rc))
6825 rc = result;
6826 }
6827 }
6828
6829 if (SUCCEEDED (rc))
6830 {
6831 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6832
6833 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6834 Console::stateProgressCallback,
6835 static_cast <VMProgressTask *> (task.get()));
6836 if (VBOX_FAILURE (vrc))
6837 {
6838 errMsg = Utf8StrFmt (
6839 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6840 task->mSavedStateFile.raw(), vrc);
6841 rc = E_FAIL;
6842 }
6843 }
6844
6845 /* lock the console sonce we're going to access it */
6846 AutoLock thatLock (that);
6847
6848 if (SUCCEEDED (rc))
6849 {
6850 if (task->mIsSnapshot)
6851 do
6852 {
6853 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
6854
6855 ComPtr <IHardDiskAttachmentCollection> hdaColl;
6856 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
6857 if (FAILED (rc))
6858 break;
6859 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
6860 rc = hdaColl->Enumerate (hdaEn.asOutParam());
6861 if (FAILED (rc))
6862 break;
6863 BOOL more = FALSE;
6864 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
6865 {
6866 ComPtr <IHardDiskAttachment> hda;
6867 rc = hdaEn->GetNext (hda.asOutParam());
6868 if (FAILED (rc))
6869 break;
6870
6871 PVMREQ pReq;
6872 IHardDiskAttachment *pHda = hda;
6873 /*
6874 * don't leave the lock since reconfigureVDI isn't going to
6875 * access Console.
6876 */
6877 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
6878 (PFNRT)reconfigureVDI, 3, that->mpVM,
6879 pHda, &rc);
6880 if (VBOX_SUCCESS (rc))
6881 rc = pReq->iStatus;
6882 VMR3ReqFree (pReq);
6883 if (FAILED (rc))
6884 break;
6885 if (VBOX_FAILURE (vrc))
6886 {
6887 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
6888 rc = E_FAIL;
6889 break;
6890 }
6891 }
6892 }
6893 while (0);
6894 }
6895
6896 /* finalize the procedure regardless of the result */
6897 if (task->mIsSnapshot)
6898 {
6899 /*
6900 * finalize the requested snapshot object.
6901 * This will reset the machine state to the state it had right
6902 * before calling mControl->BeginTakingSnapshot().
6903 */
6904 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
6905 }
6906 else
6907 {
6908 /*
6909 * finalize the requested save state procedure.
6910 * In case of success, the server will set the machine state to Saved;
6911 * in case of failure it will reset the it to the state it had right
6912 * before calling mControl->BeginSavingState().
6913 */
6914 that->mControl->EndSavingState (SUCCEEDED (rc));
6915 }
6916
6917 /* synchronize the state with the server */
6918 if (task->mIsSnapshot || FAILED (rc))
6919 {
6920 if (task->mLastMachineState == MachineState_Running)
6921 {
6922 /* restore the paused state if appropriate */
6923 that->setMachineStateLocally (MachineState_Paused);
6924 /* restore the running state if appropriate */
6925 that->Resume();
6926 }
6927 else
6928 that->setMachineStateLocally (task->mLastMachineState);
6929 }
6930 else
6931 {
6932 /*
6933 * The machine has been successfully saved, so power it down
6934 * (vmstateChangeCallback() will set state to Saved on success).
6935 * Note: we release the task's VM caller, otherwise it will
6936 * deadlock.
6937 */
6938 task->releaseVMCaller();
6939
6940 rc = that->powerDown();
6941 }
6942
6943 /* notify the progress object about operation completion */
6944 if (SUCCEEDED (rc))
6945 task->mProgress->notifyComplete (S_OK);
6946 else
6947 {
6948 if (!errMsg.isNull())
6949 task->mProgress->notifyComplete (rc,
6950 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
6951 else
6952 task->mProgress->notifyComplete (rc);
6953 }
6954
6955 LogFlowFuncLeave();
6956 return VINF_SUCCESS;
6957}
6958
6959/**
6960 * Thread for powering down the Console.
6961 *
6962 * @param Thread The thread handle.
6963 * @param pvUser Pointer to the VMTask structure.
6964 * @return VINF_SUCCESS (ignored).
6965 *
6966 * @note Locks the Console object for writing.
6967 */
6968/*static*/
6969DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
6970{
6971 LogFlowFuncEnter();
6972
6973 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
6974 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6975
6976 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
6977
6978 const ComObjPtr <Console> &that = task->mConsole;
6979
6980 /*
6981 * Note: no need to use addCaller() to protect Console
6982 * because VMTask does that
6983 */
6984
6985 /* release VM caller to let powerDown() proceed */
6986 task->releaseVMCaller();
6987
6988 HRESULT rc = that->powerDown();
6989 AssertComRC (rc);
6990
6991 LogFlowFuncLeave();
6992 return VINF_SUCCESS;
6993}
6994
6995/**
6996 * The Main status driver instance data.
6997 */
6998typedef struct DRVMAINSTATUS
6999{
7000 /** The LED connectors. */
7001 PDMILEDCONNECTORS ILedConnectors;
7002 /** Pointer to the LED ports interface above us. */
7003 PPDMILEDPORTS pLedPorts;
7004 /** Pointer to the array of LED pointers. */
7005 PPDMLED *papLeds;
7006 /** The unit number corresponding to the first entry in the LED array. */
7007 RTUINT iFirstLUN;
7008 /** The unit number corresponding to the last entry in the LED array.
7009 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7010 RTUINT iLastLUN;
7011} DRVMAINSTATUS, *PDRVMAINSTATUS;
7012
7013
7014/**
7015 * Notification about a unit which have been changed.
7016 *
7017 * The driver must discard any pointers to data owned by
7018 * the unit and requery it.
7019 *
7020 * @param pInterface Pointer to the interface structure containing the called function pointer.
7021 * @param iLUN The unit number.
7022 */
7023DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7024{
7025 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7026 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7027 {
7028 PPDMLED pLed;
7029 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7030 if (VBOX_FAILURE(rc))
7031 pLed = NULL;
7032 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7033 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7034 }
7035}
7036
7037
7038/**
7039 * Queries an interface to the driver.
7040 *
7041 * @returns Pointer to interface.
7042 * @returns NULL if the interface was not supported by the driver.
7043 * @param pInterface Pointer to this interface structure.
7044 * @param enmInterface The requested interface identification.
7045 */
7046DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7047{
7048 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7049 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7050 switch (enmInterface)
7051 {
7052 case PDMINTERFACE_BASE:
7053 return &pDrvIns->IBase;
7054 case PDMINTERFACE_LED_CONNECTORS:
7055 return &pDrv->ILedConnectors;
7056 default:
7057 return NULL;
7058 }
7059}
7060
7061
7062/**
7063 * Destruct a status driver instance.
7064 *
7065 * @returns VBox status.
7066 * @param pDrvIns The driver instance data.
7067 */
7068DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7069{
7070 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7071 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7072 if (pData->papLeds)
7073 {
7074 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7075 while (iLed-- > 0)
7076 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7077 }
7078}
7079
7080
7081/**
7082 * Construct a status driver instance.
7083 *
7084 * @returns VBox status.
7085 * @param pDrvIns The driver instance data.
7086 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7087 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7088 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7089 * iInstance it's expected to be used a bit in this function.
7090 */
7091DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7092{
7093 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7094 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7095
7096 /*
7097 * Validate configuration.
7098 */
7099 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7100 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7101 PPDMIBASE pBaseIgnore;
7102 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7103 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7104 {
7105 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7106 return VERR_PDM_DRVINS_NO_ATTACH;
7107 }
7108
7109 /*
7110 * Data.
7111 */
7112 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7113 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7114
7115 /*
7116 * Read config.
7117 */
7118 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7119 if (VBOX_FAILURE(rc))
7120 {
7121 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7122 return rc;
7123 }
7124
7125 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7126 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7127 pData->iFirstLUN = 0;
7128 else if (VBOX_FAILURE(rc))
7129 {
7130 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7131 return rc;
7132 }
7133
7134 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7135 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7136 pData->iLastLUN = 0;
7137 else if (VBOX_FAILURE(rc))
7138 {
7139 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7140 return rc;
7141 }
7142 if (pData->iFirstLUN > pData->iLastLUN)
7143 {
7144 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7145 return VERR_GENERAL_FAILURE;
7146 }
7147
7148 /*
7149 * Get the ILedPorts interface of the above driver/device and
7150 * query the LEDs we want.
7151 */
7152 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7153 if (!pData->pLedPorts)
7154 {
7155 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7156 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7157 }
7158
7159 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7160 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7161
7162 return VINF_SUCCESS;
7163}
7164
7165
7166/**
7167 * Keyboard driver registration record.
7168 */
7169const PDMDRVREG Console::DrvStatusReg =
7170{
7171 /* u32Version */
7172 PDM_DRVREG_VERSION,
7173 /* szDriverName */
7174 "MainStatus",
7175 /* pszDescription */
7176 "Main status driver (Main as in the API).",
7177 /* fFlags */
7178 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7179 /* fClass. */
7180 PDM_DRVREG_CLASS_STATUS,
7181 /* cMaxInstances */
7182 ~0,
7183 /* cbInstance */
7184 sizeof(DRVMAINSTATUS),
7185 /* pfnConstruct */
7186 Console::drvStatus_Construct,
7187 /* pfnDestruct */
7188 Console::drvStatus_Destruct,
7189 /* pfnIOCtl */
7190 NULL,
7191 /* pfnPowerOn */
7192 NULL,
7193 /* pfnReset */
7194 NULL,
7195 /* pfnSuspend */
7196 NULL,
7197 /* pfnResume */
7198 NULL,
7199 /* pfnDetach */
7200 NULL
7201};
7202
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