VirtualBox

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

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

fix Vista crash if sound is enabled; made audio LogRel consistent; winmm was never used, show dsound instead

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 246.8 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 ComPtr<IVirtualDiskImage> vdiDisk = hardDisk;
4839 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
4840
4841 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4842 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
4843 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4844 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
4845 STR_CONV();
4846 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4847 STR_FREE();
4848
4849 /* Create an inversed tree of parents. */
4850 ComPtr<IHardDisk> parentHardDisk = hardDisk;
4851 for (PCFGMNODE pParent = pCfg;;)
4852 {
4853 ComPtr<IHardDisk> curHardDisk;
4854 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
4855 if (!curHardDisk)
4856 break;
4857
4858 vdiDisk = curHardDisk;
4859 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
4860
4861 PCFGMNODE pCur;
4862 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
4863 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
4864 STR_CONV();
4865 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
4866 STR_FREE();
4867
4868 /* next */
4869 pParent = pCur;
4870 parentHardDisk = curHardDisk;
4871 }
4872 }
4873 else if (hddType == HardDiskStorageType_ISCSIHardDisk)
4874 {
4875 ComPtr<IISCSIHardDisk> iSCSIDisk = hardDisk;
4876 AssertBreak (!iSCSIDisk.isNull(), hrc = E_FAIL);
4877
4878 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4879 rc = CFGMR3InsertString(pLunL1, "Driver", "iSCSI"); RC_CHECK();
4880 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4881
4882 /* Set up the iSCSI initiator driver configuration. */
4883 hrc = iSCSIDisk->COMGETTER(Target)(&str); H();
4884 STR_CONV();
4885 rc = CFGMR3InsertString(pCfg, "TargetName", psz); RC_CHECK();
4886 STR_FREE();
4887
4888 // @todo currently there is no Initiator name config.
4889 rc = CFGMR3InsertString(pCfg, "InitiatorName", "iqn.2006-02.de.innotek.initiator"); RC_CHECK();
4890
4891 ULONG64 lun;
4892 hrc = iSCSIDisk->COMGETTER(Lun)(&lun); H();
4893 rc = CFGMR3InsertInteger(pCfg, "LUN", lun); RC_CHECK();
4894
4895 hrc = iSCSIDisk->COMGETTER(Server)(&str); H();
4896 STR_CONV();
4897 USHORT port;
4898 hrc = iSCSIDisk->COMGETTER(Port)(&port); H();
4899 if (port != 0)
4900 {
4901 char *pszTN;
4902 RTStrAPrintf(&pszTN, "%s:%u", psz, port);
4903 rc = CFGMR3InsertString(pCfg, "TargetAddress", pszTN); RC_CHECK();
4904 RTStrFree(pszTN);
4905 }
4906 else
4907 {
4908 rc = CFGMR3InsertString(pCfg, "TargetAddress", psz); RC_CHECK();
4909 }
4910 STR_FREE();
4911
4912 hrc = iSCSIDisk->COMGETTER(UserName)(&str); H();
4913 if (str)
4914 {
4915 STR_CONV();
4916 rc = CFGMR3InsertString(pCfg, "InitiatorUsername", psz); RC_CHECK();
4917 STR_FREE();
4918 }
4919
4920 hrc = iSCSIDisk->COMGETTER(Password)(&str); H();
4921 if (str)
4922 {
4923 STR_CONV();
4924 rc = CFGMR3InsertString(pCfg, "InitiatorSecret", psz); RC_CHECK();
4925 STR_FREE();
4926 }
4927
4928 // @todo currently there is no target username config.
4929 //rc = CFGMR3InsertString(pCfg, "TargetUsername", ""); RC_CHECK();
4930
4931 // @todo currently there is no target password config.
4932 //rc = CFGMR3InsertString(pCfg, "TargetSecret", ""); RC_CHECK();
4933
4934 /* The iSCSI initiator needs an attached iSCSI transport driver. */
4935 PCFGMNODE pLunL2 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/AttachedDriver */
4936 rc = CFGMR3InsertNode(pLunL1, "AttachedDriver", &pLunL2); RC_CHECK();
4937 rc = CFGMR3InsertString(pLunL2, "Driver", "iSCSITCP"); RC_CHECK();
4938 /* Currently the transport driver has no config options. */
4939 }
4940 else if (hddType == HardDiskStorageType_VMDKImage)
4941 {
4942 ComPtr<IVMDKImage> vmdkDisk = hardDisk;
4943 AssertBreak (!vmdkDisk.isNull(), hrc = E_FAIL);
4944
4945 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4946 rc = CFGMR3InsertString(pLunL1, "Driver", "VmdkHDD"); RC_CHECK();
4947 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4948 hrc = vmdkDisk->COMGETTER(FilePath)(&str); H();
4949 STR_CONV();
4950 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4951 STR_FREE();
4952 }
4953 else
4954 AssertFailed();
4955 }
4956 H();
4957
4958 ComPtr<IDVDDrive> dvdDrive;
4959 hrc = pMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam()); H();
4960 if (dvdDrive)
4961 {
4962 // ASSUME: DVD drive is always attached to LUN#2 (i.e. secondary IDE master)
4963 rc = CFGMR3InsertNode(pInst, "LUN#2", &pLunL0); RC_CHECK();
4964 ComPtr<IHostDVDDrive> hostDvdDrive;
4965 hrc = dvdDrive->GetHostDrive(hostDvdDrive.asOutParam()); H();
4966 if (hostDvdDrive)
4967 {
4968 pConsole->meDVDState = DriveState_HostDriveCaptured;
4969 rc = CFGMR3InsertString(pLunL0, "Driver", "HostDVD"); RC_CHECK();
4970 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4971 hrc = hostDvdDrive->COMGETTER(Name)(&str); H();
4972 STR_CONV();
4973 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4974 STR_FREE();
4975 BOOL fPassthrough;
4976 hrc = dvdDrive->COMGETTER(Passthrough)(&fPassthrough); H();
4977 rc = CFGMR3InsertInteger(pCfg, "Passthrough", !!fPassthrough); RC_CHECK();
4978 }
4979 else
4980 {
4981 pConsole->meDVDState = DriveState_NotMounted;
4982 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4983 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4984 rc = CFGMR3InsertString(pCfg, "Type", "DVD"); RC_CHECK();
4985 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4986
4987 ComPtr<IDVDImage> dvdImage;
4988 hrc = dvdDrive->GetImage(dvdImage.asOutParam()); H();
4989 if (dvdImage)
4990 {
4991 pConsole->meDVDState = DriveState_ImageMounted;
4992 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4993 rc = CFGMR3InsertString(pLunL1, "Driver", "MediaISO"); RC_CHECK();
4994 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4995 hrc = dvdImage->COMGETTER(FilePath)(&str); H();
4996 STR_CONV();
4997 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4998 STR_FREE();
4999 }
5000 }
5001 }
5002
5003 /*
5004 * Network adapters
5005 */
5006 rc = CFGMR3InsertNode(pDevices, "pcnet", &pDev); RC_CHECK();
5007 //rc = CFGMR3InsertNode(pDevices, "ne2000", &pDev); RC_CHECK();
5008 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::NetworkAdapterCount; ulInstance++)
5009 {
5010 ComPtr<INetworkAdapter> networkAdapter;
5011 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
5012 BOOL fEnabled = FALSE;
5013 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabled); H();
5014 if (!fEnabled)
5015 continue;
5016
5017 char szInstance[4]; Assert(ulInstance <= 999);
5018 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5019 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5020 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5021 /* the first network card gets the PCI ID 3, the followings starting from 8 */
5022 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", !ulInstance ? 3 : ulInstance - 1 + 8); RC_CHECK();
5023 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5024 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5025
5026 /*
5027 * The virtual hardware type.
5028 */
5029 NetworkAdapterType_T adapterType;
5030 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
5031 switch (adapterType)
5032 {
5033 case NetworkAdapterType_NetworkAdapterAm79C970A:
5034 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 0); RC_CHECK();
5035 break;
5036 case NetworkAdapterType_NetworkAdapterAm79C973:
5037 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 1); RC_CHECK();
5038 break;
5039 default:
5040 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
5041 adapterType, ulInstance));
5042 return VERR_GENERAL_FAILURE;
5043 }
5044
5045 /*
5046 * Get the MAC address and convert it to binary representation
5047 */
5048 Bstr macAddr;
5049 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
5050 Assert(macAddr);
5051 Utf8Str macAddrUtf8 = macAddr;
5052 char *macStr = (char*)macAddrUtf8.raw();
5053 Assert(strlen(macStr) == 12);
5054 PDMMAC Mac;
5055 memset(&Mac, 0, sizeof(Mac));
5056 char *pMac = (char*)&Mac;
5057 for (uint32_t i = 0; i < 6; i++)
5058 {
5059 char c1 = *macStr++ - '0';
5060 if (c1 > 9)
5061 c1 -= 7;
5062 char c2 = *macStr++ - '0';
5063 if (c2 > 9)
5064 c2 -= 7;
5065 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
5066 }
5067 rc = CFGMR3InsertBytes(pCfg, "MAC", &Mac, sizeof(Mac)); RC_CHECK();
5068
5069 /*
5070 * Check if the cable is supposed to be unplugged
5071 */
5072 BOOL fCableConnected;
5073 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
5074 rc = CFGMR3InsertInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0); RC_CHECK();
5075
5076 /*
5077 * Attach the status driver.
5078 */
5079 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5080 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5081 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5082 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapNetworkLeds[ulInstance]); RC_CHECK();
5083
5084 /*
5085 * Enable the packet sniffer if requested.
5086 */
5087 BOOL fSniffer;
5088 hrc = networkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
5089 if (fSniffer)
5090 {
5091 /* insert the sniffer filter driver. */
5092 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5093 rc = CFGMR3InsertString(pLunL0, "Driver", "NetSniffer"); RC_CHECK();
5094 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5095 hrc = networkAdapter->COMGETTER(TraceFile)(&str); H();
5096 if (str) /* check convention for indicating default file. */
5097 {
5098 STR_CONV();
5099 rc = CFGMR3InsertString(pCfg, "File", psz); RC_CHECK();
5100 STR_FREE();
5101 }
5102 }
5103
5104 NetworkAttachmentType_T networkAttachment;
5105 hrc = networkAdapter->COMGETTER(AttachmentType)(&networkAttachment); H();
5106 switch (networkAttachment)
5107 {
5108 case NetworkAttachmentType_NoNetworkAttachment:
5109 break;
5110
5111 case NetworkAttachmentType_NATNetworkAttachment:
5112 {
5113 if (fSniffer)
5114 {
5115 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5116 }
5117 else
5118 {
5119 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5120 }
5121 rc = CFGMR3InsertString(pLunL0, "Driver", "NAT"); RC_CHECK();
5122 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5123 /* (Port forwarding goes here.) */
5124 break;
5125 }
5126
5127 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
5128 {
5129 /*
5130 * Perform the attachment if required (don't return on error!)
5131 */
5132 hrc = pConsole->attachToHostInterface(networkAdapter);
5133 if (SUCCEEDED(hrc))
5134 {
5135#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5136 Assert (pConsole->maTapFD[ulInstance] >= 0);
5137 if (pConsole->maTapFD[ulInstance] >= 0)
5138 {
5139 if (fSniffer)
5140 {
5141 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5142 }
5143 else
5144 {
5145 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5146 }
5147 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5148 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5149 rc = CFGMR3InsertInteger(pCfg, "FileHandle", pConsole->maTapFD[ulInstance]); RC_CHECK();
5150 }
5151#elif defined(__WIN__)
5152 if (fSniffer)
5153 {
5154 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5155 }
5156 else
5157 {
5158 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5159 }
5160 Bstr hostInterfaceName;
5161 hrc = networkAdapter->COMGETTER(HostInterface)(hostInterfaceName.asOutParam()); H();
5162 ComPtr<IHostNetworkInterfaceCollection> coll;
5163 hrc = host->COMGETTER(NetworkInterfaces)(coll.asOutParam()); H();
5164 ComPtr<IHostNetworkInterface> hostInterface;
5165 rc = coll->FindByName(hostInterfaceName, hostInterface.asOutParam());
5166 if (!SUCCEEDED(rc))
5167 {
5168 AssertMsgFailed(("Cannot get GUID for host interface '%ls'\n", hostInterfaceName));
5169 hrc = networkAdapter->Detach(); H();
5170 }
5171 else
5172 {
5173 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5174 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5175 rc = CFGMR3InsertString(pCfg, "HostInterfaceName", Utf8Str(hostInterfaceName)); RC_CHECK();
5176 Guid hostIFGuid;
5177 hrc = hostInterface->COMGETTER(Id)(hostIFGuid.asOutParam()); H();
5178 char szDriverGUID[256] = {0};
5179 /* add curly brackets */
5180 szDriverGUID[0] = '{';
5181 strcpy(szDriverGUID + 1, hostIFGuid.toString().raw());
5182 strcat(szDriverGUID, "}");
5183 rc = CFGMR3InsertBytes(pCfg, "GUID", szDriverGUID, sizeof(szDriverGUID)); RC_CHECK();
5184 }
5185#else
5186# error "Port me"
5187#endif
5188 }
5189 else
5190 {
5191 switch (hrc)
5192 {
5193#ifdef __LINUX__
5194 case VERR_ACCESS_DENIED:
5195 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5196 "Failed to open '/dev/net/tun' for read/write access. Please check the "
5197 "permissions of that node. Either do 'chmod 0666 /dev/net/tun' or "
5198 "change the group of that node and get member of that group. Make "
5199 "sure that these changes are permanently in particular if you are "
5200 "using udev"));
5201#endif /* __LINUX__ */
5202 default:
5203 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
5204 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5205 "Failed to initialize Host Interface Networking"));
5206 }
5207 }
5208 break;
5209 }
5210
5211 case NetworkAttachmentType_InternalNetworkAttachment:
5212 {
5213 hrc = networkAdapter->COMGETTER(InternalNetwork)(&str); H();
5214 STR_CONV();
5215 if (psz && *psz)
5216 {
5217 if (fSniffer)
5218 {
5219 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5220 }
5221 else
5222 {
5223 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5224 }
5225 rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet"); RC_CHECK();
5226 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5227 rc = CFGMR3InsertString(pCfg, "Network", psz); RC_CHECK();
5228 }
5229 STR_FREE();
5230 break;
5231 }
5232
5233 default:
5234 AssertMsgFailed(("should not get here!\n"));
5235 break;
5236 }
5237 }
5238
5239 /*
5240 * VMM Device
5241 */
5242 rc = CFGMR3InsertNode(pDevices, "VMMDev", &pDev); RC_CHECK();
5243 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5244 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5245 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5246 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 4); RC_CHECK();
5247 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5248
5249 /* the VMM device's Main driver */
5250 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5251 rc = CFGMR3InsertString(pLunL0, "Driver", "MainVMMDev"); RC_CHECK();
5252 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5253 VMMDev *pVMMDev = pConsole->mVMMDev;
5254 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pVMMDev); RC_CHECK();
5255
5256 /*
5257 * Audio Sniffer Device
5258 */
5259 rc = CFGMR3InsertNode(pDevices, "AudioSniffer", &pDev); RC_CHECK();
5260 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5261 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5262
5263 /* the Audio Sniffer device's Main driver */
5264 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5265 rc = CFGMR3InsertString(pLunL0, "Driver", "MainAudioSniffer"); RC_CHECK();
5266 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5267 AudioSniffer *pAudioSniffer = pConsole->mAudioSniffer;
5268 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pAudioSniffer); RC_CHECK();
5269
5270 /*
5271 * AC'97 ICH audio
5272 */
5273 ComPtr<IAudioAdapter> audioAdapter;
5274 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
5275 BOOL enabled = FALSE;
5276 if (audioAdapter)
5277 {
5278 hrc = audioAdapter->COMGETTER(Enabled)(&enabled); H();
5279 }
5280 if (enabled)
5281 {
5282 rc = CFGMR3InsertNode(pDevices, "ichac97", &pDev); /* ichac97 */
5283 rc = CFGMR3InsertNode(pDev, "0", &pInst);
5284 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5285 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 5); RC_CHECK();
5286 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5287 rc = CFGMR3InsertNode(pInst, "Config", &pCfg);
5288
5289 /* the Audio driver */
5290 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5291 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
5292 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5293 AudioDriverType_T audioDriver;
5294 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
5295 switch (audioDriver)
5296 {
5297 case AudioDriverType_NullAudioDriver:
5298 {
5299 rc = CFGMR3InsertString(pCfg, "AudioDriver", "null"); RC_CHECK();
5300 break;
5301 }
5302#ifdef __WIN__
5303#ifdef VBOX_WITH_WINMM
5304 case AudioDriverType_WINMMAudioDriver:
5305 {
5306 rc = CFGMR3InsertString(pCfg, "AudioDriver", "winmm"); RC_CHECK();
5307 break;
5308 }
5309#endif
5310 case AudioDriverType_DSOUNDAudioDriver:
5311 {
5312 rc = CFGMR3InsertString(pCfg, "AudioDriver", "dsound"); RC_CHECK();
5313 break;
5314 }
5315#endif /* __WIN__ */
5316#ifdef __LINUX__
5317 case AudioDriverType_OSSAudioDriver:
5318 {
5319 rc = CFGMR3InsertString(pCfg, "AudioDriver", "oss"); RC_CHECK();
5320 break;
5321 }
5322#ifdef VBOX_WITH_ALSA
5323 case AudioDriverType_ALSAAudioDriver:
5324 {
5325 rc = CFGMR3InsertString(pCfg, "AudioDriver", "alsa"); RC_CHECK();
5326 break;
5327 }
5328#endif
5329#endif /* __LINUX__ */
5330 }
5331 }
5332
5333 /*
5334 * The USB Controller.
5335 */
5336 ComPtr<IUSBController> USBCtlPtr;
5337 hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
5338 if (USBCtlPtr)
5339 {
5340 BOOL fEnabled;
5341 hrc = USBCtlPtr->COMGETTER(Enabled)(&fEnabled); H();
5342 if (fEnabled)
5343 {
5344 rc = CFGMR3InsertNode(pDevices, "usb-ohci", &pDev); RC_CHECK();
5345 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5346 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5347 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5348 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 6); RC_CHECK();
5349 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5350
5351 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5352 rc = CFGMR3InsertString(pLunL0, "Driver", "VUSBRootHub"); RC_CHECK();
5353 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5354 }
5355 }
5356
5357 /*
5358 * Clipboard
5359 */
5360 {
5361 ClipboardMode_T mode = ClipboardMode_ClipDisabled;
5362 hrc = pMachine->COMGETTER(ClipboardMode) (&mode); H();
5363
5364 if (mode != ClipboardMode_ClipDisabled)
5365 {
5366 /* Load the service */
5367 rc = pConsole->mVMMDev->hgcmLoadService ("VBoxSharedClipboard", "VBoxSharedClipboard");
5368
5369 if (VBOX_FAILURE (rc))
5370 {
5371 LogRel(("VBoxSharedClipboard is not available. rc = %Vrc\n", rc));
5372 /* That is not a fatal failure. */
5373 rc = VINF_SUCCESS;
5374 }
5375 else
5376 {
5377 /* Setup the service. */
5378 VBOXHGCMSVCPARM parm;
5379
5380 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
5381
5382 switch (mode)
5383 {
5384 default:
5385 case ClipboardMode_ClipDisabled:
5386 {
5387 LogRel(("VBoxSharedClipboard mode: Off\n"));
5388 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
5389 break;
5390 }
5391 case ClipboardMode_ClipGuestToHost:
5392 {
5393 LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
5394 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
5395 break;
5396 }
5397 case ClipboardMode_ClipHostToGuest:
5398 {
5399 LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
5400 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
5401 break;
5402 }
5403 case ClipboardMode_ClipBidirectional:
5404 {
5405 LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
5406 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
5407 break;
5408 }
5409 }
5410
5411 pConsole->mVMMDev->hgcmHostCall ("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
5412
5413 Log(("Set VBoxSharedClipboard mode\n"));
5414 }
5415 }
5416 }
5417
5418 /*
5419 * CFGM overlay handling.
5420 *
5421 * Here we check the extra data entries for CFGM values
5422 * and create the nodes and insert the values on the fly. Existing
5423 * values will be removed and reinserted. If a value is a valid number,
5424 * it will be inserted as a number, otherwise as a string.
5425 *
5426 * We first perform a run on global extra data, then on the machine
5427 * extra data to support global settings with local overrides.
5428 *
5429 */
5430 Bstr strExtraDataKey;
5431 bool fGlobalExtraData = true;
5432 for (;;)
5433 {
5434 Bstr strNextExtraDataKey;
5435 Bstr strExtraDataValue;
5436
5437 /* get the next key */
5438 if (fGlobalExtraData)
5439 hrc = virtualBox->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5440 strExtraDataValue.asOutParam());
5441 else
5442 hrc = pMachine->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5443 strExtraDataValue.asOutParam());
5444
5445 /* stop if for some reason there's nothing more to request */
5446 if (FAILED(hrc) || !strNextExtraDataKey)
5447 {
5448 /* if we're out of global keys, continue with machine, otherwise we're done */
5449 if (fGlobalExtraData)
5450 {
5451 fGlobalExtraData = false;
5452 strExtraDataKey.setNull();
5453 continue;
5454 }
5455 break;
5456 }
5457
5458 strExtraDataKey = strNextExtraDataKey;
5459 Utf8Str strExtraDataKeyUtf8 = Utf8Str(strExtraDataKey);
5460
5461 /* we only care about keys starting with "VBoxInternal/" */
5462 if (strncmp(strExtraDataKeyUtf8.raw(), "VBoxInternal/", 13) != 0)
5463 continue;
5464 char *pszExtraDataKey = (char*)strExtraDataKeyUtf8.raw() + 13;
5465
5466 /* the key will be in the format "Node1/Node2/Value" or simply "Value". */
5467 PCFGMNODE pNode;
5468 char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
5469 if (pszCFGMValueName)
5470 {
5471 /* terminate the node and advance to the value */
5472 *pszCFGMValueName = '\0';
5473 pszCFGMValueName++;
5474
5475 /* does the node already exist? */
5476 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
5477 if (pNode)
5478 {
5479 /* the value might already exist, remove it to be safe */
5480 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5481 }
5482 else
5483 {
5484 /* create the node */
5485 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
5486 AssertMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
5487 if (VBOX_FAILURE(rc) || !pNode)
5488 continue;
5489 }
5490 }
5491 else
5492 {
5493 pNode = pRoot;
5494 pszCFGMValueName = pszExtraDataKey;
5495 pszExtraDataKey--;
5496
5497 /* the value might already exist, remove it to be safe */
5498 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5499 }
5500
5501 /* now let's have a look at the value */
5502 Utf8Str strCFGMValueUtf8 = Utf8Str(strExtraDataValue);
5503 const char *pszCFGMValue = strCFGMValueUtf8.raw();
5504 /* empty value means remove value which we've already done */
5505 if (pszCFGMValue && *pszCFGMValue)
5506 {
5507 /* if it's a valid number, we'll insert it as such, otherwise string */
5508 uint64_t u64Value;
5509 if (RTStrToUInt64Ex(pszCFGMValue, NULL, 0, &u64Value) == VINF_SUCCESS)
5510 {
5511 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
5512 }
5513 else
5514 {
5515 rc = CFGMR3InsertString(pNode, pszCFGMValueName, pszCFGMValue);
5516 }
5517 AssertMsgRC(rc, ("failed to insert CFGM value '%s' to key '%s'\n", pszCFGMValue, pszExtraDataKey));
5518 }
5519 }
5520
5521#undef H
5522#undef RC_CHECK
5523#undef STR_FREE
5524#undef STR_CONV
5525
5526 /* Register VM state change handler */
5527 int rc2 = VMR3AtStateRegister (pVM, Console::vmstateChangeCallback, pConsole);
5528 AssertRC (rc2);
5529 if (VBOX_SUCCESS (rc))
5530 rc = rc2;
5531
5532 /* Register VM runtime error handler */
5533 rc2 = VMR3AtRuntimeErrorRegister (pVM, Console::setVMRuntimeErrorCallback, pConsole);
5534 AssertRC (rc2);
5535 if (VBOX_SUCCESS (rc))
5536 rc = rc2;
5537
5538 /* Save the VM pointer in the machine object */
5539 pConsole->mpVM = pVM;
5540
5541 LogFlowFunc (("vrc = %Vrc\n", rc));
5542 LogFlowFuncLeave();
5543
5544 return rc;
5545}
5546
5547/**
5548 * Helper function to handle host interface device creation and attachment.
5549 *
5550 * @param networkAdapter the network adapter which attachment should be reset
5551 * @return COM status code
5552 *
5553 * @note The caller must lock this object for writing.
5554 */
5555HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5556{
5557 /* sanity check */
5558 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5559
5560#ifdef DEBUG
5561 /* paranoia */
5562 NetworkAttachmentType_T attachment;
5563 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5564 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5565#endif /* DEBUG */
5566
5567 HRESULT rc = S_OK;
5568
5569#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5570 ULONG slot = 0;
5571 rc = networkAdapter->COMGETTER(Slot)(&slot);
5572 AssertComRC(rc);
5573
5574 /*
5575 * Try get the FD.
5576 */
5577 LONG ltapFD;
5578 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5579 if (SUCCEEDED(rc))
5580 maTapFD[slot] = (RTFILE)ltapFD;
5581 else
5582 maTapFD[slot] = NIL_RTFILE;
5583
5584 /*
5585 * Are we supposed to use an existing TAP interface?
5586 */
5587 if (maTapFD[slot] != NIL_RTFILE)
5588 {
5589 /* nothing to do */
5590 Assert(ltapFD >= 0);
5591 Assert((LONG)maTapFD[slot] == ltapFD);
5592 rc = S_OK;
5593 }
5594 else
5595#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5596 {
5597 /*
5598 * Allocate a host interface device
5599 */
5600#ifdef __WIN__
5601 /* nothing to do */
5602 int rcVBox = VINF_SUCCESS;
5603#elif defined(__LINUX__)
5604 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5605 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5606 if (VBOX_SUCCESS(rcVBox))
5607 {
5608 /*
5609 * Set/obtain the tap interface.
5610 */
5611 struct ifreq IfReq;
5612 memset(&IfReq, 0, sizeof(IfReq));
5613 Bstr tapDeviceName;
5614 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5615 if (FAILED(rc) || tapDeviceName.isEmpty())
5616 strcpy(IfReq.ifr_name, "tap%d");
5617 else
5618 {
5619 Utf8Str str(tapDeviceName);
5620 if (str.length() <= sizeof(IfReq.ifr_name))
5621 strcpy(IfReq.ifr_name, str.raw());
5622 else
5623 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5624 }
5625 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5626 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5627 if (!rcVBox)
5628 {
5629 /*
5630 * Make it pollable.
5631 */
5632 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5633 {
5634 tapDeviceName = IfReq.ifr_name;
5635 if (tapDeviceName)
5636 {
5637 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5638
5639 /*
5640 * Here is the right place to communicate the TAP file descriptor and
5641 * the host interface name to the server if/when it becomes really
5642 * necessary.
5643 */
5644 maTAPDeviceName[slot] = tapDeviceName;
5645 rcVBox = VINF_SUCCESS;
5646 rc = S_OK;
5647 }
5648 else
5649 rcVBox = VERR_NO_MEMORY;
5650 }
5651 else
5652 {
5653 AssertMsgFailed(("Configuration error: Failed to configure /dev/net/tun non blocking. errno=%d\n", errno));
5654 rcVBox = VERR_HOSTIF_BLOCKING;
5655 rc = setError(E_FAIL, "Failed to set /dev/net/tun to non blocking. errno=%d\n", errno);
5656 }
5657 }
5658 else
5659 {
5660 AssertMsgFailed(("Configuration error: Failed to configure /dev/net/tun. errno=%d\n", errno));
5661 rcVBox = VERR_HOSTIF_IOCTL;
5662 rc = setError(E_FAIL, "Failed to configure /dev/net/tun. errno = %d\n", errno);
5663 }
5664 }
5665 else
5666 {
5667 AssertMsgFailed(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5668 switch (rcVBox)
5669 {
5670 case VERR_ACCESS_DENIED:
5671 /* will be handled by our caller */
5672 LogRel(("HERE\n"));
5673 rc = rcVBox;
5674 break;
5675 default:
5676 rc = setError(E_FAIL, "Failed to open /dev/net/tun rc = %Vrc\n", rcVBox);
5677 break;
5678 }
5679 }
5680#elif defined(__DARWIN__)
5681 /** @todo Implement tap networking for Darwin. */
5682 int rcVBox = VERR_NOT_IMPLEMENTED;
5683#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
5684# error "PORTME: Implement OS specific TAP interface open/creation."
5685#else
5686# error "Unknown host OS"
5687#endif
5688 /* in case of failure, cleanup. */
5689 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5690 {
5691 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5692 }
5693 }
5694#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5695 if (SUCCEEDED(rc))
5696 {
5697 /*
5698 * Call the initialization program.
5699 *
5700 * The initialization program is passed the device name as the first param.
5701 * The second parameter is the decimal value of the file handle of the device
5702 * which it inherits.
5703 */
5704 Bstr tapSetupApplication;
5705 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5706 if (tapSetupApplication)
5707 {
5708 /*
5709 * Create the argument list.
5710 */
5711 const char *apszArgs[4];
5712 /* 0. The program name. */
5713 Utf8Str tapSetupApp(tapSetupApplication);
5714 apszArgs[0] = tapSetupApp.raw();
5715
5716 /* 1. The file descriptor. */
5717 char szFD[32];
5718 RTStrPrintf(szFD, sizeof(szFD), "%RTfile", maTapFD[slot]);
5719 apszArgs[1] = szFD;
5720
5721 /* 2. The device name (optional). */
5722 apszArgs[2] = maTAPDeviceName[slot].isEmpty() ? NULL : maTAPDeviceName[slot].raw();
5723
5724 /* 3. The end. */
5725 apszArgs[3] = NULL;
5726
5727 /*
5728 * Create the process and wait for it to complete.
5729 */
5730 RTPROCESS Process;
5731 int rcVBox = RTProcCreate(apszArgs[0], &apszArgs[0], NULL, 0, &Process);
5732 if (VBOX_SUCCESS(rcVBox))
5733 {
5734 /* wait for the process to exit */
5735 RTPROCSTATUS ProcStatus;
5736 rcVBox = RTProcWait(Process, RTPROCWAIT_FLAGS_BLOCK, &ProcStatus);
5737 AssertRC(rcVBox);
5738 if (VBOX_SUCCESS(rcVBox))
5739 {
5740 if ( ProcStatus.enmReason == RTPROCEXITREASON_NORMAL
5741 && ProcStatus.iStatus == 0)
5742 rcVBox = VINF_SUCCESS;
5743 else
5744 rcVBox = VMSetError(mpVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_("Failed to initialize Host Interface Networking"));
5745 }
5746 }
5747 else
5748 {
5749 AssertMsgFailed(("Configuration error: Failed to start init program \"%s\", rc=%Vra\n", tapSetupApp.raw(), rcVBox));
5750 rc = setError(E_FAIL, "Failed to start init program \"%s\", rc = %Vra\n", tapSetupApp.raw(), rcVBox);
5751 }
5752
5753 /* in case of failure, cleanup. */
5754 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5755 {
5756 rc = setError(E_FAIL, tr ("General failure configuring Host Interface Networking"));
5757 }
5758 }
5759 }
5760#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5761 return rc;
5762}
5763
5764/**
5765 * Helper function to handle detachment from a host interface
5766 *
5767 * @param networkAdapter the network adapter which attachment should be reset
5768 * @return COM status code
5769 *
5770 * @note The caller must lock this object for writing.
5771 */
5772HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5773{
5774 /* sanity check */
5775 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5776
5777 HRESULT rc = S_OK;
5778#ifdef DEBUG
5779 /* paranoia */
5780 NetworkAttachmentType_T attachment;
5781 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5782 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5783#endif /* DEBUG */
5784
5785#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5786
5787 ULONG slot = 0;
5788 rc = networkAdapter->COMGETTER(Slot)(&slot);
5789 AssertComRC(rc);
5790
5791 /* is there an open TAP device? */
5792 if (maTapFD[slot] != NIL_RTFILE)
5793 {
5794 /*
5795 * Execute term command and close the file handle.
5796 */
5797 Bstr tapTerminateApplication;
5798 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5799 if (tapTerminateApplication)
5800 {
5801 /*
5802 * Create the argument list
5803 */
5804 const char *apszArgs[4];
5805 /* 0. The program name. */
5806 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5807 apszArgs[0] = tapTermAppUtf8.raw();
5808
5809 /* 1. The file descriptor. */
5810 char szFD[32];
5811 RTStrPrintf(szFD, sizeof(szFD), "%RTfile", maTapFD[slot]);
5812 apszArgs[1] = szFD;
5813
5814 /* 2. Device name (optional). */
5815 apszArgs[2] = maTAPDeviceName[slot].isEmpty() ? NULL : maTAPDeviceName[slot].raw();
5816
5817 /* 3. The end. */
5818 apszArgs[3] = NULL;
5819
5820 /*
5821 * Create the process and wait for it to complete.
5822 */
5823 RTPROCESS Process;
5824 int rcVBox = RTProcCreate(apszArgs[0], &apszArgs[0], NULL, 0, &Process);
5825 if (VBOX_SUCCESS(rcVBox))
5826 {
5827 /* wait for the process to exit */
5828 RTPROCSTATUS ProcStatus;
5829 rcVBox = RTProcWait(Process, RTPROCWAIT_FLAGS_BLOCK, &ProcStatus);
5830 AssertRC(rcVBox);
5831 /* ignore return code? */
5832 }
5833 else
5834 AssertMsgFailed(("Configuration error: Failed to start terminate program \"%s\", rc=%Vra\n", apszArgs[0], rcVBox)); /** @todo last error candidate. */
5835 if (VBOX_FAILURE(rcVBox))
5836 rc = E_FAIL;
5837 }
5838
5839 /*
5840 * Now we can close the file handle.
5841 */
5842 int rcVBox = RTFileClose(maTapFD[slot]);
5843 AssertRC(rcVBox);
5844 /* the TAP device name and handle are no longer valid */
5845 maTapFD[slot] = NIL_RTFILE;
5846 maTAPDeviceName[slot] = "";
5847 }
5848#endif
5849 return rc;
5850}
5851
5852
5853/**
5854 * Called at power down to terminate host interface networking.
5855 *
5856 * @note The caller must lock this object for writing.
5857 */
5858HRESULT Console::powerDownHostInterfaces()
5859{
5860 LogFlowThisFunc (("\n"));
5861
5862 /* sanity check */
5863 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5864
5865 /*
5866 * host interface termination handling
5867 */
5868 HRESULT rc;
5869 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
5870 {
5871 ComPtr<INetworkAdapter> networkAdapter;
5872 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
5873 CheckComRCBreakRC (rc);
5874
5875 BOOL enabled = FALSE;
5876 networkAdapter->COMGETTER(Enabled) (&enabled);
5877 if (!enabled)
5878 continue;
5879
5880 NetworkAttachmentType_T attachment;
5881 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5882 if (attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment)
5883 {
5884 HRESULT rc2 = detachFromHostInterface(networkAdapter);
5885 if (FAILED(rc2) && SUCCEEDED(rc))
5886 rc = rc2;
5887 }
5888 }
5889
5890 return rc;
5891}
5892
5893
5894/**
5895 * Process callback handler for VMR3Load and VMR3Save.
5896 *
5897 * @param pVM The VM handle.
5898 * @param uPercent Completetion precentage (0-100).
5899 * @param pvUser Pointer to the VMProgressTask structure.
5900 * @return VINF_SUCCESS.
5901 */
5902/*static*/ DECLCALLBACK (int)
5903Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
5904{
5905 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5906 AssertReturn (task, VERR_INVALID_PARAMETER);
5907
5908 /* update the progress object */
5909 if (task->mProgress)
5910 task->mProgress->notifyProgress (uPercent);
5911
5912 return VINF_SUCCESS;
5913}
5914
5915/**
5916 * VM error callback function. Called by the various VM components.
5917 *
5918 * @param pVM The VM handle. Can be NULL if an error occurred before
5919 * successfully creating a VM.
5920 * @param pvUser Pointer to the VMProgressTask structure.
5921 * @param rc VBox status code.
5922 * @param pszFormat The error message.
5923 * @thread EMT.
5924 */
5925/* static */ DECLCALLBACK (void)
5926Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
5927 const char *pszFormat, va_list args)
5928{
5929 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5930 AssertReturnVoid (task);
5931
5932 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
5933 HRESULT hrc = setError (E_FAIL, tr ("%N.\n"
5934 "VBox status code: %d (%Vrc)"),
5935 tr (pszFormat), &args,
5936 rc, rc);
5937 task->mProgress->notifyComplete (hrc);
5938}
5939
5940/**
5941 * VM runtime error callback function.
5942 * See VMSetRuntimeError for the detailed description of parameters.
5943 *
5944 * @param pVM The VM handle.
5945 * @param pvUser The user argument.
5946 * @param fFatal Whether it is a fatal error or not.
5947 * @param pszErrorID Error ID string.
5948 * @param pszFormat Error message format string.
5949 * @param args Error message arguments.
5950 * @thread EMT.
5951 */
5952/* static */ DECLCALLBACK(void)
5953Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
5954 const char *pszErrorID,
5955 const char *pszFormat, va_list args)
5956{
5957 LogFlowFuncEnter();
5958
5959 Console *that = static_cast <Console *> (pvUser);
5960 AssertReturnVoid (that);
5961
5962 Utf8Str message = Utf8StrFmt (pszFormat, args);
5963
5964 LogRel (("Console: VM runtime error: fatal=%RTbool, "
5965 "errorID=%s message=\"%s\"\n",
5966 fFatal, pszErrorID, message.raw()));
5967
5968 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
5969
5970 LogFlowFuncLeave();
5971}
5972
5973/**
5974 * Captures and attaches USB devices to a newly created VM.
5975 *
5976 * @param pVM The VM handle.
5977 *
5978 * @note The caller must lock this object for writing.
5979 */
5980HRESULT Console::captureUSBDevices (PVM pVM)
5981{
5982 LogFlowThisFunc (("\n"));
5983
5984 /* sanity check */
5985 ComAssertRet (isLockedOnCurrentThread(), E_FAIL);
5986
5987 /*
5988 * If the machine has an USB controller, capture devices and attach
5989 * them to it.
5990 */
5991 PPDMIBASE pBase;
5992 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
5993 if (VBOX_SUCCESS (vrc))
5994 {
5995 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
5996 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
5997 ComAssertRet (pRhConfig, E_FAIL);
5998
5999 /*
6000 * Get the list of USB devices that should be captured and attached to
6001 * the newly created machine.
6002 */
6003 ComPtr <IUSBDeviceCollection> coll;
6004 HRESULT hrc = mControl->AutoCaptureUSBDevices (coll.asOutParam());
6005 ComAssertComRCRetRC (hrc);
6006
6007 /*
6008 * Enumerate the devices and attach them.
6009 * Failing to attach an device is currently ignored and the device
6010 * released.
6011 */
6012 ComPtr <IUSBDeviceEnumerator> en;
6013 hrc = coll->Enumerate (en.asOutParam());
6014 ComAssertComRCRetRC (hrc);
6015
6016 BOOL hasMore = FALSE;
6017 while (SUCCEEDED (en->HasMore (&hasMore)) && hasMore)
6018 {
6019 ComPtr <IUSBDevice> hostDevice;
6020 hrc = en->GetNext (hostDevice.asOutParam());
6021 ComAssertComRCRetRC (hrc);
6022 ComAssertRet (!hostDevice.isNull(), E_FAIL);
6023
6024 hrc = attachUSBDevice (hostDevice, true /* aManual */, pRhConfig);
6025
6026 /// @todo (r=dmik) warning reporting subsystem
6027 }
6028 }
6029 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6030 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6031 vrc = VINF_SUCCESS;
6032 else
6033 AssertRC (vrc);
6034
6035 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
6036}
6037
6038
6039/**
6040 * Releases all USB device which is attached to the VM for the
6041 * purpose of clean up and such like.
6042 *
6043 * @note The caller must lock this object for writing.
6044 */
6045void Console::releaseAllUSBDevices (void)
6046{
6047 LogFlowThisFunc (("\n"));
6048
6049 /* sanity check */
6050 AssertReturnVoid (isLockedOnCurrentThread());
6051
6052 mControl->ReleaseAllUSBDevices();
6053 mUSBDevices.clear();
6054}
6055
6056/**
6057 * @note Locks this object for writing.
6058 */
6059#ifdef VRDP_MC
6060void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6061#else
6062void Console::processRemoteUSBDevices (VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6063#endif /* VRDP_MC */
6064{
6065 LogFlowThisFuncEnter();
6066#ifdef VRDP_MC
6067 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6068#else
6069 LogFlowThisFunc (("pDevList=%p, cbDevList = %d\n", pDevList, cbDevList));
6070#endif /* VRDP_MC */
6071
6072 AutoCaller autoCaller (this);
6073 if (!autoCaller.isOk())
6074 {
6075 /* Console has been already uninitialized, deny request */
6076 AssertMsgFailed (("Temporary assertion to prove that it happens, "
6077 "please report to dmik\n"));
6078 LogFlowThisFunc (("Console is already uninitialized\n"));
6079 LogFlowThisFuncLeave();
6080 return;
6081 }
6082
6083 AutoLock alock (this);
6084
6085 /*
6086 * Mark all existing remote USB devices as dirty.
6087 */
6088 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6089 while (it != mRemoteUSBDevices.end())
6090 {
6091 (*it)->dirty (true);
6092 ++ it;
6093 }
6094
6095 /*
6096 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6097 */
6098 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6099 VRDPUSBDEVICEDESC *e = pDevList;
6100
6101 /* The cbDevList condition must be checked first, because the function can
6102 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6103 */
6104 while (cbDevList >= 2 && e->oNext)
6105 {
6106 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6107 e->idVendor, e->idProduct,
6108 e->oProduct? (char *)e + e->oProduct: ""));
6109
6110 bool fNewDevice = true;
6111
6112 it = mRemoteUSBDevices.begin();
6113 while (it != mRemoteUSBDevices.end())
6114 {
6115#ifdef VRDP_MC
6116 if ((*it)->devId () == e->id
6117 && (*it)->clientId () == u32ClientId)
6118#else
6119 if ((*it)->devId () == e->id)
6120#endif /* VRDP_MC */
6121 {
6122 /* The device is already in the list. */
6123 (*it)->dirty (false);
6124 fNewDevice = false;
6125 break;
6126 }
6127
6128 ++ it;
6129 }
6130
6131 if (fNewDevice)
6132 {
6133 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6134 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6135 ));
6136
6137 /* Create the device object and add the new device to list. */
6138 ComObjPtr <RemoteUSBDevice> device;
6139 device.createObject();
6140#ifdef VRDP_MC
6141 device->init (u32ClientId, e);
6142#else
6143 device->init (e);
6144#endif /* VRDP_MC */
6145
6146 mRemoteUSBDevices.push_back (device);
6147
6148 /* Check if the device is ok for current USB filters. */
6149 BOOL fMatched = FALSE;
6150
6151 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched);
6152
6153 AssertComRC (hrc);
6154
6155 LogFlowThisFunc (("USB filters return %d\n", fMatched));
6156
6157 if (fMatched)
6158 {
6159 hrc = onUSBDeviceAttach(device);
6160
6161 /// @todo (r=dmik) warning reporting subsystem
6162
6163 if (hrc == S_OK)
6164 {
6165 LogFlowThisFunc (("Device attached\n"));
6166 device->captured (true);
6167 }
6168 }
6169 }
6170
6171 if (cbDevList < e->oNext)
6172 {
6173 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6174 cbDevList, e->oNext));
6175 break;
6176 }
6177
6178 cbDevList -= e->oNext;
6179
6180 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6181 }
6182
6183 /*
6184 * Remove dirty devices, that is those which are not reported by the server anymore.
6185 */
6186 for (;;)
6187 {
6188 ComObjPtr <RemoteUSBDevice> device;
6189
6190 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6191 while (it != mRemoteUSBDevices.end())
6192 {
6193 if ((*it)->dirty ())
6194 {
6195 device = *it;
6196 break;
6197 }
6198
6199 ++ it;
6200 }
6201
6202 if (!device)
6203 {
6204 break;
6205 }
6206
6207 USHORT vendorId = 0;
6208 device->COMGETTER(VendorId) (&vendorId);
6209
6210 USHORT productId = 0;
6211 device->COMGETTER(ProductId) (&productId);
6212
6213 Bstr product;
6214 device->COMGETTER(Product) (product.asOutParam());
6215
6216 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6217 vendorId, productId, product.raw ()
6218 ));
6219
6220 /* Detach the device from VM. */
6221 if (device->captured ())
6222 {
6223 Guid uuid;
6224 device->COMGETTER (Id) (uuid.asOutParam());
6225 onUSBDeviceDetach (uuid);
6226 }
6227
6228 /* And remove it from the list. */
6229 mRemoteUSBDevices.erase (it);
6230 }
6231
6232 LogFlowThisFuncLeave();
6233}
6234
6235
6236
6237/**
6238 * Thread function which starts the VM (also from saved state) and
6239 * track progress.
6240 *
6241 * @param Thread The thread id.
6242 * @param pvUser Pointer to a VMPowerUpTask structure.
6243 * @return VINF_SUCCESS (ignored).
6244 *
6245 * @note Locks the Console object for writing.
6246 */
6247/*static*/
6248DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6249{
6250 LogFlowFuncEnter();
6251
6252 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6253 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6254
6255 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6256 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6257
6258#if defined(__WIN__)
6259 {
6260 /* initialize COM */
6261 HRESULT hrc = CoInitializeEx (NULL,
6262 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6263 COINIT_SPEED_OVER_MEMORY);
6264 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6265 }
6266#endif
6267
6268 HRESULT hrc = S_OK;
6269 int vrc = VINF_SUCCESS;
6270
6271 ComObjPtr <Console> console = task->mConsole;
6272
6273 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6274
6275 AutoLock alock (console);
6276
6277 /* sanity */
6278 Assert (console->mpVM == NULL);
6279
6280 do
6281 {
6282 /*
6283 * Initialize the release logging facility. In case something
6284 * goes wrong, there will be no release logging. Maybe in the future
6285 * we can add some logic to use different file names in this case.
6286 * Note that the logic must be in sync with Machine::DeleteSettings().
6287 */
6288
6289 Bstr logFolder;
6290 hrc = console->mControl->GetLogFolder (logFolder.asOutParam());
6291 CheckComRCBreakRC (hrc);
6292
6293 Utf8Str logDir = logFolder;
6294
6295 /* make sure the Logs folder exists */
6296 Assert (!logDir.isEmpty());
6297 if (!RTDirExists (logDir))
6298 RTDirCreateFullPath (logDir, 0777);
6299
6300 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
6301 logDir.raw(), RTPATH_DELIMITER);
6302
6303 /*
6304 * Age the old log files
6305 * Rename .2 to .3, .1 to .2 and the last log file to .1
6306 * Overwrite target files in case they exist;
6307 */
6308 for (int i = 2; i >= 0; i--)
6309 {
6310 Utf8Str oldName;
6311 if (i > 0)
6312 oldName = Utf8StrFmt ("%s.%d", logFile.raw(), i);
6313 else
6314 oldName = logFile;
6315 Utf8Str newName = Utf8StrFmt ("%s.%d", logFile.raw(), i + 1);
6316 RTFileRename(oldName.raw(), newName.raw(), RTFILEMOVE_FLAGS_REPLACE);
6317 }
6318
6319 PRTLOGGER loggerRelease;
6320 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
6321 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
6322#ifdef __WIN__
6323 fFlags |= RTLOGFLAGS_USECRLF;
6324#endif /* __WIN__ */
6325 vrc = RTLogCreate(&loggerRelease, fFlags, "all",
6326 "VBOX_RELEASE_LOG", ELEMENTS(s_apszGroups), s_apszGroups,
6327 RTLOGDEST_FILE, logFile.raw());
6328 if (VBOX_SUCCESS(vrc))
6329 {
6330 /* some introductory information */
6331 RTTIMESPEC timeSpec;
6332 char nowUct[64];
6333 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
6334 RTLogRelLogger(loggerRelease, 0, ~0U,
6335 "VirtualBox %d.%d.%d (%s %s) release log\n"
6336 "Log opened %s\n",
6337 VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD,
6338 __DATE__, __TIME__,
6339 nowUct);
6340
6341 /* register this logger as the release logger */
6342 RTLogRelSetDefaultInstance(loggerRelease);
6343 }
6344 else
6345 {
6346 hrc = setError (E_FAIL,
6347 tr ("Failed to open release log file '%s' (%Vrc)"),
6348 logFile.raw(), vrc);
6349 break;
6350 }
6351
6352#ifdef VBOX_VRDP
6353 if (VBOX_SUCCESS (vrc))
6354 {
6355 /* Create the VRDP server. In case of headless operation, this will
6356 * also create the framebuffer, required at VM creation.
6357 */
6358 ConsoleVRDPServer *server = console->consoleVRDPServer();
6359 Assert (server);
6360 /// @todo (dmik)
6361 // does VRDP server call Console from the other thread?
6362 // Not sure, so leave the lock just in case
6363 alock.leave();
6364 vrc = server->Launch();
6365 alock.enter();
6366 if (VBOX_FAILURE (vrc))
6367 {
6368 Utf8Str errMsg;
6369 switch (vrc)
6370 {
6371 case VERR_NET_ADDRESS_IN_USE:
6372 {
6373 ULONG port = 0;
6374 console->mVRDPServer->COMGETTER(Port) (&port);
6375 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6376 port);
6377 break;
6378 }
6379 default:
6380 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6381 vrc);
6382 }
6383 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6384 vrc, errMsg.raw()));
6385 hrc = setError (E_FAIL, errMsg);
6386 break;
6387 }
6388 }
6389#endif /* VBOX_VRDP */
6390
6391 /*
6392 * Create the VM
6393 */
6394 PVM pVM;
6395 /*
6396 * leave the lock since EMT will call Console. It's safe because
6397 * mMachineState is either Starting or Restoring state here.
6398 */
6399 alock.leave();
6400
6401 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6402 task->mConfigConstructor, task.get(),
6403 &pVM);
6404
6405 alock.enter();
6406
6407#ifdef VBOX_VRDP
6408 {
6409 /* Enable client connections to the server. */
6410 ConsoleVRDPServer *server = console->consoleVRDPServer();
6411 server->SetCallback ();
6412 }
6413#endif /* VBOX_VRDP */
6414
6415 if (VBOX_SUCCESS (vrc))
6416 {
6417 do
6418 {
6419 /*
6420 * Register our load/save state file handlers
6421 */
6422 vrc = SSMR3RegisterExternal (pVM,
6423 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6424 0 /* cbGuess */,
6425 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6426 static_cast <Console *> (console));
6427 AssertRC (vrc);
6428 if (VBOX_FAILURE (vrc))
6429 break;
6430
6431 /*
6432 * Synchronize debugger settings
6433 */
6434 MachineDebugger *machineDebugger = console->getMachineDebugger();
6435 if (machineDebugger)
6436 {
6437 machineDebugger->flushQueuedSettings();
6438 }
6439
6440 if (console->getVMMDev()->getShFlClientId())
6441 {
6442 /// @todo (dmik)
6443 // does the code below call Console from the other thread?
6444 // Not sure, so leave the lock just in case
6445 alock.leave();
6446
6447 /*
6448 * Shared Folders
6449 */
6450 for (std::map <Bstr, ComPtr <ISharedFolder> >::const_iterator
6451 it = task->mSharedFolders.begin();
6452 it != task->mSharedFolders.end();
6453 ++ it)
6454 {
6455 Bstr name = (*it).first;
6456 ComPtr <ISharedFolder> folder = (*it).second;
6457
6458 Bstr hostPath;
6459 hrc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
6460 CheckComRCBreakRC (hrc);
6461
6462 LogFlowFunc (("Adding shared folder '%ls' -> '%ls'\n",
6463 name.raw(), hostPath.raw()));
6464 ComAssertBreak (!name.isEmpty() && !hostPath.isEmpty(),
6465 hrc = E_FAIL);
6466
6467 /** @todo should move this into the shared folder class */
6468 VBOXHGCMSVCPARM parms[2];
6469 SHFLSTRING *pFolderName, *pMapName;
6470 int cbString;
6471
6472 cbString = (hostPath.length() + 1) * sizeof(RTUCS2);
6473 pFolderName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6474 Assert(pFolderName);
6475 memcpy(pFolderName->String.ucs2, hostPath.raw(), cbString);
6476
6477 pFolderName->u16Size = cbString;
6478 pFolderName->u16Length = cbString - sizeof(RTUCS2);
6479
6480 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
6481 parms[0].u.pointer.addr = pFolderName;
6482 parms[0].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6483
6484 cbString = (name.length() + 1) * sizeof(RTUCS2);
6485 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6486 Assert(pMapName);
6487 memcpy(pMapName->String.ucs2, name.raw(), cbString);
6488
6489 pMapName->u16Size = cbString;
6490 pMapName->u16Length = cbString - sizeof(RTUCS2);
6491
6492 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
6493 parms[1].u.pointer.addr = pMapName;
6494 parms[1].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6495
6496 vrc = console->getVMMDev()->hgcmHostCall("VBoxSharedFolders",
6497 SHFL_FN_ADD_MAPPING, 2, &parms[0]);
6498
6499 RTMemFree(pFolderName);
6500 RTMemFree(pMapName);
6501
6502 if (VBOX_FAILURE (vrc))
6503 {
6504 hrc = setError (E_FAIL,
6505 tr ("Unable to add mapping '%ls' to '%ls' (%Vrc)"),
6506 hostPath.raw(), name.raw(), vrc);
6507 break;
6508 }
6509 }
6510
6511 /* enter the lock again */
6512 alock.enter();
6513
6514 CheckComRCBreakRC (hrc);
6515 }
6516
6517 /*
6518 * Capture USB devices.
6519 */
6520 hrc = console->captureUSBDevices (pVM);
6521 CheckComRCBreakRC (hrc);
6522
6523 /* leave the lock before a lengthy operation */
6524 alock.leave();
6525
6526 /* Load saved state? */
6527 if (!!task->mSavedStateFile)
6528 {
6529 LogFlowFunc (("Restoring saved state from '%s'...\n",
6530 task->mSavedStateFile.raw()));
6531
6532 vrc = VMR3Load (pVM, task->mSavedStateFile,
6533 Console::stateProgressCallback,
6534 static_cast <VMProgressTask *> (task.get()));
6535
6536 /* Start/Resume the VM execution */
6537 if (VBOX_SUCCESS (vrc))
6538 {
6539 vrc = VMR3Resume (pVM);
6540 AssertRC (vrc);
6541 }
6542
6543 /* Power off in case we failed loading or resuming the VM */
6544 if (VBOX_FAILURE (vrc))
6545 {
6546 int vrc2 = VMR3PowerOff (pVM);
6547 AssertRC (vrc2);
6548 }
6549 }
6550 else
6551 {
6552 /* Power on the VM (i.e. start executing) */
6553 vrc = VMR3PowerOn(pVM);
6554 AssertRC (vrc);
6555 }
6556
6557 /* enter the lock again */
6558 alock.enter();
6559 }
6560 while (0);
6561
6562 /* On failure, destroy the VM */
6563 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6564 {
6565 /* preserve the current error info */
6566 ErrorInfo ei;
6567
6568 /*
6569 * powerDown() will call VMR3Destroy() and do all necessary
6570 * cleanup (VRDP, USB devices)
6571 */
6572 HRESULT hrc2 = console->powerDown();
6573 AssertComRC (hrc2);
6574
6575 setError (ei);
6576 }
6577 }
6578 else
6579 {
6580 /*
6581 * If VMR3Create() failed it has released the VM memory.
6582 */
6583 console->mpVM = NULL;
6584 }
6585
6586 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6587 {
6588 /*
6589 * If VMR3Create() or one of the other calls in this function fail,
6590 * an appropriate error message has been already set. However since
6591 * that happens via a callback, the status code in this function is
6592 * not updated.
6593 */
6594 if (!task->mProgress->completed())
6595 {
6596 /*
6597 * If the COM error info is not yet set but we've got a
6598 * failure, convert the VBox status code into a meaningful
6599 * error message. This becomes unused once all the sources of
6600 * errors set the appropriate error message themselves.
6601 * Note that we don't use VMSetError() below because pVM is
6602 * either invalid or NULL here.
6603 */
6604 AssertMsgFailed (("Missing error message during powerup for "
6605 "status code %Vrc\n", vrc));
6606 hrc = setError (E_FAIL,
6607 tr ("Failed to start VM execution (%Vrc)"), vrc);
6608 }
6609 else
6610 hrc = task->mProgress->resultCode();
6611
6612 Assert (FAILED (hrc));
6613 break;
6614 }
6615 }
6616 while (0);
6617
6618 if (console->mMachineState == MachineState_Starting ||
6619 console->mMachineState == MachineState_Restoring)
6620 {
6621 /*
6622 * We are still in the Starting/Restoring state. This means one of:
6623 * 1) we failed before VMR3Create() was called;
6624 * 2) VMR3Create() failed.
6625 * In both cases, there is no need to call powerDown(), but we still
6626 * need to go back to the PoweredOff/Saved state. Reuse
6627 * vmstateChangeCallback() for that purpose.
6628 */
6629
6630 /* preserve the current error info */
6631 ErrorInfo ei;
6632
6633 Assert (console->mpVM == NULL);
6634 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6635 console);
6636 setError (ei);
6637 }
6638
6639 /*
6640 * Evaluate the final result.
6641 * Note that the appropriate mMachineState value is already set by
6642 * vmstateChangeCallback() in all cases.
6643 */
6644
6645 /* leave the lock, don't need it any more */
6646 alock.leave();
6647
6648 if (SUCCEEDED (hrc))
6649 {
6650 /* Notify the progress object of the success */
6651 task->mProgress->notifyComplete (S_OK);
6652 }
6653 else
6654 {
6655 if (!task->mProgress->completed())
6656 {
6657 /* The progress object will fetch the current error info. This
6658 * gets the errors signalled by using setError(). The ones
6659 * signalled via VMSetError() immediately notify the progress
6660 * object that the operation is completed. */
6661 task->mProgress->notifyComplete (hrc);
6662 }
6663
6664 LogRel (("Power up failed (vrc=%Vrc, hrc=0x%08X)\n", vrc, hrc));
6665 }
6666
6667#if defined(__WIN__)
6668 /* uninitialize COM */
6669 CoUninitialize();
6670#endif
6671
6672 LogFlowFuncLeave();
6673
6674 return VINF_SUCCESS;
6675}
6676
6677
6678/**
6679 * Reconfigures a VDI.
6680 *
6681 * @param pVM The VM handle.
6682 * @param hda The harddisk attachment.
6683 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6684 * @return VBox status code.
6685 */
6686static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6687{
6688 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6689
6690 int rc;
6691 HRESULT hrc;
6692 char *psz = NULL;
6693 BSTR str = NULL;
6694 *phrc = S_OK;
6695#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
6696#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6697#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6698#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6699
6700 /*
6701 * Figure out which IDE device this is.
6702 */
6703 ComPtr<IHardDisk> hardDisk;
6704 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6705 DiskControllerType_T enmCtl;
6706 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
6707 LONG lDev;
6708 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
6709
6710 int i;
6711 switch (enmCtl)
6712 {
6713 case DiskControllerType_IDE0Controller:
6714 i = 0;
6715 break;
6716 case DiskControllerType_IDE1Controller:
6717 i = 2;
6718 break;
6719 default:
6720 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
6721 return VERR_GENERAL_FAILURE;
6722 }
6723
6724 if (lDev < 0 || lDev >= 2)
6725 {
6726 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6727 return VERR_GENERAL_FAILURE;
6728 }
6729
6730 i = i + lDev;
6731
6732 /*
6733 * Is there an existing LUN? If not create it.
6734 * We ASSUME that this will NEVER collide with the DVD.
6735 */
6736 PCFGMNODE pCfg;
6737 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", i);
6738 if (!pLunL1)
6739 {
6740 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6741 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6742
6743 PCFGMNODE pLunL0;
6744 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", i); RC_CHECK();
6745 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6746 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6747 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6748 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6749
6750 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6751 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6752 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6753 }
6754 else
6755 {
6756#ifdef VBOX_STRICT
6757 char *pszDriver;
6758 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6759 Assert(!strcmp(pszDriver, "VBoxHDD"));
6760 MMR3HeapFree(pszDriver);
6761#endif
6762
6763 /*
6764 * Check if things has changed.
6765 */
6766 pCfg = CFGMR3GetChild(pLunL1, "Config");
6767 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6768
6769 /* the image */
6770 /// @todo (dmik) we temporarily use the location property to
6771 // determine the image file name. This is subject to change
6772 // when iSCSI disks are here (we should either query a
6773 // storage-specific interface from IHardDisk, or "standardize"
6774 // the location property)
6775 hrc = hardDisk->COMGETTER(Location)(&str); H();
6776 STR_CONV();
6777 char *pszPath;
6778 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6779 if (!strcmp(psz, pszPath))
6780 {
6781 /* parent images. */
6782 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6783 for (PCFGMNODE pParent = pCfg;;)
6784 {
6785 MMR3HeapFree(pszPath);
6786 pszPath = NULL;
6787 STR_FREE();
6788
6789 /* get parent */
6790 ComPtr<IHardDisk> curHardDisk;
6791 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6792 PCFGMNODE pCur;
6793 pCur = CFGMR3GetChild(pParent, "Parent");
6794 if (!pCur && !curHardDisk)
6795 {
6796 /* no change */
6797 LogFlowFunc (("No change!\n"));
6798 return VINF_SUCCESS;
6799 }
6800 if (!pCur || !curHardDisk)
6801 break;
6802
6803 /* compare paths. */
6804 /// @todo (dmik) we temporarily use the location property to
6805 // determine the image file name. This is subject to change
6806 // when iSCSI disks are here (we should either query a
6807 // storage-specific interface from IHardDisk, or "standardize"
6808 // the location property)
6809 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6810 STR_CONV();
6811 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6812 if (strcmp(psz, pszPath))
6813 break;
6814
6815 /* next */
6816 pParent = pCur;
6817 parentHardDisk = curHardDisk;
6818 }
6819
6820 }
6821 else
6822 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", i, pszPath));
6823
6824 MMR3HeapFree(pszPath);
6825 STR_FREE();
6826
6827 /*
6828 * Detach the driver and replace the config node.
6829 */
6830 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, i); RC_CHECK();
6831 CFGMR3RemoveNode(pCfg);
6832 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6833 }
6834
6835 /*
6836 * Create the driver configuration.
6837 */
6838 /// @todo (dmik) we temporarily use the location property to
6839 // determine the image file name. This is subject to change
6840 // when iSCSI disks are here (we should either query a
6841 // storage-specific interface from IHardDisk, or "standardize"
6842 // the location property)
6843 hrc = hardDisk->COMGETTER(Location)(&str); H();
6844 STR_CONV();
6845 LogFlowFunc (("LUN#%d: leaf image '%s'\n", i, psz));
6846 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6847 STR_FREE();
6848 /* Create an inversed tree of parents. */
6849 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6850 for (PCFGMNODE pParent = pCfg;;)
6851 {
6852 ComPtr<IHardDisk> curHardDisk;
6853 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6854 if (!curHardDisk)
6855 break;
6856
6857 PCFGMNODE pCur;
6858 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6859 /// @todo (dmik) we temporarily use the location property to
6860 // determine the image file name. This is subject to change
6861 // when iSCSI disks are here (we should either query a
6862 // storage-specific interface from IHardDisk, or "standardize"
6863 // the location property)
6864 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6865 STR_CONV();
6866 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6867 STR_FREE();
6868
6869 /* next */
6870 pParent = pCur;
6871 parentHardDisk = curHardDisk;
6872 }
6873
6874 /*
6875 * Attach the new driver.
6876 */
6877 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, i, NULL); RC_CHECK();
6878
6879 LogFlowFunc (("Returns success\n"));
6880 return rc;
6881}
6882
6883
6884/**
6885 * Thread for executing the saved state operation.
6886 *
6887 * @param Thread The thread handle.
6888 * @param pvUser Pointer to a VMSaveTask structure.
6889 * @return VINF_SUCCESS (ignored).
6890 *
6891 * @note Locks the Console object for writing.
6892 */
6893/*static*/
6894DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6895{
6896 LogFlowFuncEnter();
6897
6898 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6899 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6900
6901 Assert (!task->mSavedStateFile.isNull());
6902 Assert (!task->mProgress.isNull());
6903
6904 const ComObjPtr <Console> &that = task->mConsole;
6905
6906 /*
6907 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6908 * protect mpVM because VMSaveTask does that
6909 */
6910
6911 Utf8Str errMsg;
6912 HRESULT rc = S_OK;
6913
6914 if (task->mIsSnapshot)
6915 {
6916 Assert (!task->mServerProgress.isNull());
6917 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6918
6919 rc = task->mServerProgress->WaitForCompletion (-1);
6920 if (SUCCEEDED (rc))
6921 {
6922 HRESULT result = S_OK;
6923 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6924 if (SUCCEEDED (rc))
6925 rc = result;
6926 }
6927 }
6928
6929 if (SUCCEEDED (rc))
6930 {
6931 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6932
6933 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6934 Console::stateProgressCallback,
6935 static_cast <VMProgressTask *> (task.get()));
6936 if (VBOX_FAILURE (vrc))
6937 {
6938 errMsg = Utf8StrFmt (
6939 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6940 task->mSavedStateFile.raw(), vrc);
6941 rc = E_FAIL;
6942 }
6943 }
6944
6945 /* lock the console sonce we're going to access it */
6946 AutoLock thatLock (that);
6947
6948 if (SUCCEEDED (rc))
6949 {
6950 if (task->mIsSnapshot)
6951 do
6952 {
6953 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
6954
6955 ComPtr <IHardDiskAttachmentCollection> hdaColl;
6956 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
6957 if (FAILED (rc))
6958 break;
6959 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
6960 rc = hdaColl->Enumerate (hdaEn.asOutParam());
6961 if (FAILED (rc))
6962 break;
6963 BOOL more = FALSE;
6964 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
6965 {
6966 ComPtr <IHardDiskAttachment> hda;
6967 rc = hdaEn->GetNext (hda.asOutParam());
6968 if (FAILED (rc))
6969 break;
6970
6971 PVMREQ pReq;
6972 IHardDiskAttachment *pHda = hda;
6973 /*
6974 * don't leave the lock since reconfigureVDI isn't going to
6975 * access Console.
6976 */
6977 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
6978 (PFNRT)reconfigureVDI, 3, that->mpVM,
6979 pHda, &rc);
6980 if (VBOX_SUCCESS (rc))
6981 rc = pReq->iStatus;
6982 VMR3ReqFree (pReq);
6983 if (FAILED (rc))
6984 break;
6985 if (VBOX_FAILURE (vrc))
6986 {
6987 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
6988 rc = E_FAIL;
6989 break;
6990 }
6991 }
6992 }
6993 while (0);
6994 }
6995
6996 /* finalize the procedure regardless of the result */
6997 if (task->mIsSnapshot)
6998 {
6999 /*
7000 * finalize the requested snapshot object.
7001 * This will reset the machine state to the state it had right
7002 * before calling mControl->BeginTakingSnapshot().
7003 */
7004 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
7005 }
7006 else
7007 {
7008 /*
7009 * finalize the requested save state procedure.
7010 * In case of success, the server will set the machine state to Saved;
7011 * in case of failure it will reset the it to the state it had right
7012 * before calling mControl->BeginSavingState().
7013 */
7014 that->mControl->EndSavingState (SUCCEEDED (rc));
7015 }
7016
7017 /* synchronize the state with the server */
7018 if (task->mIsSnapshot || FAILED (rc))
7019 {
7020 if (task->mLastMachineState == MachineState_Running)
7021 {
7022 /* restore the paused state if appropriate */
7023 that->setMachineStateLocally (MachineState_Paused);
7024 /* restore the running state if appropriate */
7025 that->Resume();
7026 }
7027 else
7028 that->setMachineStateLocally (task->mLastMachineState);
7029 }
7030 else
7031 {
7032 /*
7033 * The machine has been successfully saved, so power it down
7034 * (vmstateChangeCallback() will set state to Saved on success).
7035 * Note: we release the task's VM caller, otherwise it will
7036 * deadlock.
7037 */
7038 task->releaseVMCaller();
7039
7040 rc = that->powerDown();
7041 }
7042
7043 /* notify the progress object about operation completion */
7044 if (SUCCEEDED (rc))
7045 task->mProgress->notifyComplete (S_OK);
7046 else
7047 {
7048 if (!errMsg.isNull())
7049 task->mProgress->notifyComplete (rc,
7050 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
7051 else
7052 task->mProgress->notifyComplete (rc);
7053 }
7054
7055 LogFlowFuncLeave();
7056 return VINF_SUCCESS;
7057}
7058
7059/**
7060 * Thread for powering down the Console.
7061 *
7062 * @param Thread The thread handle.
7063 * @param pvUser Pointer to the VMTask structure.
7064 * @return VINF_SUCCESS (ignored).
7065 *
7066 * @note Locks the Console object for writing.
7067 */
7068/*static*/
7069DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
7070{
7071 LogFlowFuncEnter();
7072
7073 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
7074 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7075
7076 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
7077
7078 const ComObjPtr <Console> &that = task->mConsole;
7079
7080 /*
7081 * Note: no need to use addCaller() to protect Console
7082 * because VMTask does that
7083 */
7084
7085 /* release VM caller to let powerDown() proceed */
7086 task->releaseVMCaller();
7087
7088 HRESULT rc = that->powerDown();
7089 AssertComRC (rc);
7090
7091 LogFlowFuncLeave();
7092 return VINF_SUCCESS;
7093}
7094
7095/**
7096 * The Main status driver instance data.
7097 */
7098typedef struct DRVMAINSTATUS
7099{
7100 /** The LED connectors. */
7101 PDMILEDCONNECTORS ILedConnectors;
7102 /** Pointer to the LED ports interface above us. */
7103 PPDMILEDPORTS pLedPorts;
7104 /** Pointer to the array of LED pointers. */
7105 PPDMLED *papLeds;
7106 /** The unit number corresponding to the first entry in the LED array. */
7107 RTUINT iFirstLUN;
7108 /** The unit number corresponding to the last entry in the LED array.
7109 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7110 RTUINT iLastLUN;
7111} DRVMAINSTATUS, *PDRVMAINSTATUS;
7112
7113
7114/**
7115 * Notification about a unit which have been changed.
7116 *
7117 * The driver must discard any pointers to data owned by
7118 * the unit and requery it.
7119 *
7120 * @param pInterface Pointer to the interface structure containing the called function pointer.
7121 * @param iLUN The unit number.
7122 */
7123DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7124{
7125 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7126 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7127 {
7128 PPDMLED pLed;
7129 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7130 if (VBOX_FAILURE(rc))
7131 pLed = NULL;
7132 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7133 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7134 }
7135}
7136
7137
7138/**
7139 * Queries an interface to the driver.
7140 *
7141 * @returns Pointer to interface.
7142 * @returns NULL if the interface was not supported by the driver.
7143 * @param pInterface Pointer to this interface structure.
7144 * @param enmInterface The requested interface identification.
7145 */
7146DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7147{
7148 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7149 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7150 switch (enmInterface)
7151 {
7152 case PDMINTERFACE_BASE:
7153 return &pDrvIns->IBase;
7154 case PDMINTERFACE_LED_CONNECTORS:
7155 return &pDrv->ILedConnectors;
7156 default:
7157 return NULL;
7158 }
7159}
7160
7161
7162/**
7163 * Destruct a status driver instance.
7164 *
7165 * @returns VBox status.
7166 * @param pDrvIns The driver instance data.
7167 */
7168DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7169{
7170 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7171 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7172 if (pData->papLeds)
7173 {
7174 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7175 while (iLed-- > 0)
7176 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7177 }
7178}
7179
7180
7181/**
7182 * Construct a status driver instance.
7183 *
7184 * @returns VBox status.
7185 * @param pDrvIns The driver instance data.
7186 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7187 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7188 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7189 * iInstance it's expected to be used a bit in this function.
7190 */
7191DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7192{
7193 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7194 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7195
7196 /*
7197 * Validate configuration.
7198 */
7199 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7200 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7201 PPDMIBASE pBaseIgnore;
7202 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7203 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7204 {
7205 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7206 return VERR_PDM_DRVINS_NO_ATTACH;
7207 }
7208
7209 /*
7210 * Data.
7211 */
7212 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7213 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7214
7215 /*
7216 * Read config.
7217 */
7218 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7219 if (VBOX_FAILURE(rc))
7220 {
7221 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7222 return rc;
7223 }
7224
7225 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7226 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7227 pData->iFirstLUN = 0;
7228 else if (VBOX_FAILURE(rc))
7229 {
7230 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7231 return rc;
7232 }
7233
7234 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7235 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7236 pData->iLastLUN = 0;
7237 else if (VBOX_FAILURE(rc))
7238 {
7239 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7240 return rc;
7241 }
7242 if (pData->iFirstLUN > pData->iLastLUN)
7243 {
7244 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7245 return VERR_GENERAL_FAILURE;
7246 }
7247
7248 /*
7249 * Get the ILedPorts interface of the above driver/device and
7250 * query the LEDs we want.
7251 */
7252 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7253 if (!pData->pLedPorts)
7254 {
7255 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7256 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7257 }
7258
7259 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7260 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7261
7262 return VINF_SUCCESS;
7263}
7264
7265
7266/**
7267 * Keyboard driver registration record.
7268 */
7269const PDMDRVREG Console::DrvStatusReg =
7270{
7271 /* u32Version */
7272 PDM_DRVREG_VERSION,
7273 /* szDriverName */
7274 "MainStatus",
7275 /* pszDescription */
7276 "Main status driver (Main as in the API).",
7277 /* fFlags */
7278 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7279 /* fClass. */
7280 PDM_DRVREG_CLASS_STATUS,
7281 /* cMaxInstances */
7282 ~0,
7283 /* cbInstance */
7284 sizeof(DRVMAINSTATUS),
7285 /* pfnConstruct */
7286 Console::drvStatus_Construct,
7287 /* pfnDestruct */
7288 Console::drvStatus_Destruct,
7289 /* pfnIOCtl */
7290 NULL,
7291 /* pfnPowerOn */
7292 NULL,
7293 /* pfnReset */
7294 NULL,
7295 /* pfnSuspend */
7296 NULL,
7297 /* pfnResume */
7298 NULL,
7299 /* pfnDetach */
7300 NULL
7301};
7302
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