VirtualBox

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

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

Include VBOX_SVN_VER in the release log header.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette