VirtualBox

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

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

Main: Added USBDevice to the DeviceType enum to provide USB device activity (search for USB_DEVICE_ACTIVITY in ConsoleImpl.cpp). Thanks to MS COM C++ bingings polluting the global namespace with enum values, I had to rename the USBDevice class to OUSBDevice (and to add the COM_DECL_READONLY_ENUM_AND_COLLECTION_EX_BEGIN macro for even more flexible collection declarations).

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