VirtualBox

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

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

Main: Fixed the assertion unexpectedly popping up when creating a transient shared folder on a powered off VM.

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