VirtualBox

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

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

VRDP NO_COM code in Main.

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