VirtualBox

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

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

Main: Fixed a stupud bug.

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