VirtualBox

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

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

Another attempt to solve the VRDP initialization problem

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