VirtualBox

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

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

use generic functions for determining paths instead of home-brewn solutions

  • 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 memset (&mCallbackData, 0, sizeof (mCallbackData));
262
263 /* Cache essential properties and objects */
264
265 rc = mMachine->COMGETTER(State) (&mMachineState);
266 AssertComRCReturn (rc, rc);
267
268#ifdef VBOX_VRDP
269 rc = mMachine->COMGETTER(VRDPServer) (unconst (mVRDPServer).asOutParam());
270 AssertComRCReturn (rc, rc);
271#endif
272
273 rc = mMachine->COMGETTER(DVDDrive) (unconst (mDVDDrive).asOutParam());
274 AssertComRCReturn (rc, rc);
275
276 rc = mMachine->COMGETTER(FloppyDrive) (unconst (mFloppyDrive).asOutParam());
277 AssertComRCReturn (rc, rc);
278
279 /* Create associated child COM objects */
280
281 unconst (mGuest).createObject();
282 rc = mGuest->init (this);
283 AssertComRCReturn (rc, rc);
284
285 unconst (mKeyboard).createObject();
286 rc = mKeyboard->init (this);
287 AssertComRCReturn (rc, rc);
288
289 unconst (mMouse).createObject();
290 rc = mMouse->init (this);
291 AssertComRCReturn (rc, rc);
292
293 unconst (mDisplay).createObject();
294 rc = mDisplay->init (this);
295 AssertComRCReturn (rc, rc);
296
297 unconst (mRemoteDisplayInfo).createObject();
298 rc = mRemoteDisplayInfo->init (this);
299 AssertComRCReturn (rc, rc);
300
301 /* Create other child objects */
302
303 unconst (mConsoleVRDPServer) = new ConsoleVRDPServer (this);
304 AssertReturn (mConsoleVRDPServer, E_FAIL);
305
306 mcAudioRefs = 0;
307 mcVRDPClients = 0;
308
309 unconst (mVMMDev) = new VMMDev(this);
310 AssertReturn (mVMMDev, E_FAIL);
311
312 unconst (mAudioSniffer) = new AudioSniffer(this);
313 AssertReturn (mAudioSniffer, E_FAIL);
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#if 0
3427 LogFlowThisFuncEnter();
3428 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3429 "height=%d, shape=%p\n",
3430 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3431#endif
3432
3433 AutoCaller autoCaller (this);
3434 AssertComRCReturnVoid (autoCaller.rc());
3435
3436 /* We need a write lock because we alter the cached callback data */
3437 AutoLock alock (this);
3438
3439 /* Save the callback arguments */
3440 mCallbackData.mpsc.visible = fVisible;
3441 mCallbackData.mpsc.alpha = fAlpha;
3442 mCallbackData.mpsc.xHot = xHot;
3443 mCallbackData.mpsc.yHot = yHot;
3444 mCallbackData.mpsc.width = width;
3445 mCallbackData.mpsc.height = height;
3446
3447 /* start with not valid */
3448 bool wasValid = mCallbackData.mpsc.valid;
3449 mCallbackData.mpsc.valid = false;
3450
3451 if (pShape != NULL)
3452 {
3453 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3454 cb += ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3455 /* try to reuse the old shape buffer if the size is the same */
3456 if (!wasValid)
3457 mCallbackData.mpsc.shape = NULL;
3458 else
3459 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3460 {
3461 RTMemFree (mCallbackData.mpsc.shape);
3462 mCallbackData.mpsc.shape = NULL;
3463 }
3464 if (mCallbackData.mpsc.shape == NULL)
3465 {
3466 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3467 AssertReturnVoid (mCallbackData.mpsc.shape);
3468 }
3469 mCallbackData.mpsc.shapeSize = cb;
3470 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3471 }
3472 else
3473 {
3474 if (wasValid && mCallbackData.mpsc.shape != NULL)
3475 RTMemFree (mCallbackData.mpsc.shape);
3476 mCallbackData.mpsc.shape = NULL;
3477 mCallbackData.mpsc.shapeSize = 0;
3478 }
3479
3480 mCallbackData.mpsc.valid = true;
3481
3482 CallbackList::iterator it = mCallbacks.begin();
3483 while (it != mCallbacks.end())
3484 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3485 width, height, (BYTE *) pShape);
3486
3487#if 0
3488 LogFlowThisFuncLeave();
3489#endif
3490}
3491
3492/**
3493 * @note Locks this object for writing.
3494 */
3495void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3496{
3497 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3498 supportsAbsolute, needsHostCursor));
3499
3500 AutoCaller autoCaller (this);
3501 AssertComRCReturnVoid (autoCaller.rc());
3502
3503 /* We need a write lock because we alter the cached callback data */
3504 AutoLock alock (this);
3505
3506 /* save the callback arguments */
3507 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3508 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3509 mCallbackData.mcc.valid = true;
3510
3511 CallbackList::iterator it = mCallbacks.begin();
3512 while (it != mCallbacks.end())
3513 {
3514 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3515 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3516 }
3517}
3518
3519/**
3520 * @note Locks this object for reading.
3521 */
3522void Console::onStateChange (MachineState_T machineState)
3523{
3524 AutoCaller autoCaller (this);
3525 AssertComRCReturnVoid (autoCaller.rc());
3526
3527 AutoReaderLock alock (this);
3528
3529 CallbackList::iterator it = mCallbacks.begin();
3530 while (it != mCallbacks.end())
3531 (*it++)->OnStateChange (machineState);
3532}
3533
3534/**
3535 * @note Locks this object for reading.
3536 */
3537void Console::onAdditionsStateChange()
3538{
3539 AutoCaller autoCaller (this);
3540 AssertComRCReturnVoid (autoCaller.rc());
3541
3542 AutoReaderLock alock (this);
3543
3544 CallbackList::iterator it = mCallbacks.begin();
3545 while (it != mCallbacks.end())
3546 (*it++)->OnAdditionsStateChange();
3547}
3548
3549/**
3550 * @note Locks this object for reading.
3551 */
3552void Console::onAdditionsOutdated()
3553{
3554 AutoCaller autoCaller (this);
3555 AssertComRCReturnVoid (autoCaller.rc());
3556
3557 AutoReaderLock alock (this);
3558
3559 /** @todo Use the On-Screen Display feature to report the fact.
3560 * The user should be told to install additions that are
3561 * provided with the current VBox build:
3562 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3563 */
3564}
3565
3566/**
3567 * @note Locks this object for writing.
3568 */
3569void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3570{
3571 AutoCaller autoCaller (this);
3572 AssertComRCReturnVoid (autoCaller.rc());
3573
3574 /* We need a write lock because we alter the cached callback data */
3575 AutoLock alock (this);
3576
3577 /* save the callback arguments */
3578 mCallbackData.klc.numLock = fNumLock;
3579 mCallbackData.klc.capsLock = fCapsLock;
3580 mCallbackData.klc.scrollLock = fScrollLock;
3581 mCallbackData.klc.valid = true;
3582
3583 CallbackList::iterator it = mCallbacks.begin();
3584 while (it != mCallbacks.end())
3585 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3586}
3587
3588/**
3589 * @note Locks this object for reading.
3590 */
3591void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
3592 IVirtualBoxErrorInfo *aError)
3593{
3594 AutoCaller autoCaller (this);
3595 AssertComRCReturnVoid (autoCaller.rc());
3596
3597 AutoReaderLock alock (this);
3598
3599 CallbackList::iterator it = mCallbacks.begin();
3600 while (it != mCallbacks.end())
3601 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
3602}
3603
3604/**
3605 * @note Locks this object for reading.
3606 */
3607void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3608{
3609 AutoCaller autoCaller (this);
3610 AssertComRCReturnVoid (autoCaller.rc());
3611
3612 AutoReaderLock alock (this);
3613
3614 CallbackList::iterator it = mCallbacks.begin();
3615 while (it != mCallbacks.end())
3616 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3617}
3618
3619/**
3620 * @note Locks this object for reading.
3621 */
3622HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
3623{
3624 AssertReturn (aCanShow, E_POINTER);
3625 AssertReturn (aWinId, E_POINTER);
3626
3627 *aCanShow = FALSE;
3628 *aWinId = 0;
3629
3630 AutoCaller autoCaller (this);
3631 AssertComRCReturnRC (autoCaller.rc());
3632
3633 AutoReaderLock alock (this);
3634
3635 HRESULT rc = S_OK;
3636 CallbackList::iterator it = mCallbacks.begin();
3637
3638 if (aCheck)
3639 {
3640 while (it != mCallbacks.end())
3641 {
3642 BOOL canShow = FALSE;
3643 rc = (*it++)->OnCanShowWindow (&canShow);
3644 AssertComRC (rc);
3645 if (FAILED (rc) || !canShow)
3646 return rc;
3647 }
3648 *aCanShow = TRUE;
3649 }
3650 else
3651 {
3652 while (it != mCallbacks.end())
3653 {
3654 ULONG64 winId = 0;
3655 rc = (*it++)->OnShowWindow (&winId);
3656 AssertComRC (rc);
3657 if (FAILED (rc))
3658 return rc;
3659 /* only one callback may return non-null winId */
3660 Assert (*aWinId == 0 || winId == 0);
3661 if (*aWinId == 0)
3662 *aWinId = winId;
3663 }
3664 }
3665
3666 return S_OK;
3667}
3668
3669// private mehtods
3670////////////////////////////////////////////////////////////////////////////////
3671
3672/**
3673 * Increases the usage counter of the mpVM pointer. Guarantees that
3674 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
3675 * is called.
3676 *
3677 * If this method returns a failure, the caller is not allowed to use mpVM
3678 * and may return the failed result code to the upper level. This method sets
3679 * the extended error info on failure if \a aQuiet is false.
3680 *
3681 * Setting \a aQuiet to true is useful for methods that don't want to return
3682 * the failed result code to the caller when this method fails (e.g. need to
3683 * silently check for the mpVM avaliability).
3684 *
3685 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
3686 * returned instead of asserting. Having it false is intended as a sanity check
3687 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
3688 *
3689 * @param aQuiet true to suppress setting error info
3690 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
3691 * (otherwise this method will assert if mpVM is NULL)
3692 *
3693 * @note Locks this object for writing.
3694 */
3695HRESULT Console::addVMCaller (bool aQuiet /* = false */,
3696 bool aAllowNullVM /* = false */)
3697{
3698 AutoCaller autoCaller (this);
3699 AssertComRCReturnRC (autoCaller.rc());
3700
3701 AutoLock alock (this);
3702
3703 if (mVMDestroying)
3704 {
3705 /* powerDown() is waiting for all callers to finish */
3706 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3707 tr ("Virtual machine is being powered down"));
3708 }
3709
3710 if (mpVM == NULL)
3711 {
3712 Assert (aAllowNullVM == true);
3713
3714 /* The machine is not powered up */
3715 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3716 tr ("Virtual machine is not powered up"));
3717 }
3718
3719 ++ mVMCallers;
3720
3721 return S_OK;
3722}
3723
3724/**
3725 * Decreases the usage counter of the mpVM pointer. Must always complete
3726 * the addVMCaller() call after the mpVM pointer is no more necessary.
3727 *
3728 * @note Locks this object for writing.
3729 */
3730void Console::releaseVMCaller()
3731{
3732 AutoCaller autoCaller (this);
3733 AssertComRCReturnVoid (autoCaller.rc());
3734
3735 AutoLock alock (this);
3736
3737 AssertReturnVoid (mpVM != NULL);
3738
3739 Assert (mVMCallers > 0);
3740 -- mVMCallers;
3741
3742 if (mVMCallers == 0 && mVMDestroying)
3743 {
3744 /* inform powerDown() there are no more callers */
3745 RTSemEventSignal (mVMZeroCallersSem);
3746 }
3747}
3748
3749/**
3750 * Internal power off worker routine.
3751 *
3752 * This method may be called only at certain places with the folliwing meaning
3753 * as shown below:
3754 *
3755 * - if the machine state is either Running or Paused, a normal
3756 * Console-initiated powerdown takes place (e.g. PowerDown());
3757 * - if the machine state is Saving, saveStateThread() has successfully
3758 * done its job;
3759 * - if the machine state is Starting or Restoring, powerUpThread() has
3760 * failed to start/load the VM;
3761 * - if the machine state is Stopping, the VM has powered itself off
3762 * (i.e. not as a result of the powerDown() call).
3763 *
3764 * Calling it in situations other than the above will cause unexpected
3765 * behavior.
3766 *
3767 * Note that this method should be the only one that destroys mpVM and sets
3768 * it to NULL.
3769 *
3770 * @note Locks this object for writing.
3771 *
3772 * @note Never call this method from a thread that called addVMCaller() or
3773 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
3774 * release(). Otherwise it will deadlock.
3775 */
3776HRESULT Console::powerDown()
3777{
3778 LogFlowThisFuncEnter();
3779
3780 AutoCaller autoCaller (this);
3781 AssertComRCReturnRC (autoCaller.rc());
3782
3783 AutoLock alock (this);
3784
3785 /* sanity */
3786 AssertReturn (mVMDestroying == false, E_FAIL);
3787
3788 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
3789 "(mMachineState=%d, InUninit=%d)\n",
3790 mMachineState, autoCaller.state() == InUninit));
3791
3792 /* First, wait for all mpVM callers to finish their work if necessary */
3793 if (mVMCallers > 0)
3794 {
3795 /* go to the destroying state to prevent from adding new callers */
3796 mVMDestroying = true;
3797
3798 /* lazy creation */
3799 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
3800 RTSemEventCreate (&mVMZeroCallersSem);
3801
3802 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
3803 mVMCallers));
3804
3805 alock.leave();
3806
3807 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
3808
3809 alock.enter();
3810 }
3811
3812 AssertReturn (mpVM, E_FAIL);
3813
3814 AssertMsg (mMachineState == MachineState_Running ||
3815 mMachineState == MachineState_Paused ||
3816 mMachineState == MachineState_Saving ||
3817 mMachineState == MachineState_Starting ||
3818 mMachineState == MachineState_Restoring ||
3819 mMachineState == MachineState_Stopping,
3820 ("Invalid machine state: %d\n", mMachineState));
3821
3822 HRESULT rc = S_OK;
3823 int vrc = VINF_SUCCESS;
3824
3825 /*
3826 * Power off the VM if not already done that. In case of Stopping, the VM
3827 * has powered itself off and notified Console in vmstateChangeCallback().
3828 * In case of Starting or Restoring, powerUpThread() is calling us on
3829 * failure, so the VM is already off at that point.
3830 */
3831 if (mMachineState != MachineState_Stopping &&
3832 mMachineState != MachineState_Starting &&
3833 mMachineState != MachineState_Restoring)
3834 {
3835 /*
3836 * don't go from Saving to Stopping, vmstateChangeCallback needs it
3837 * to set the state to Saved on VMSTATE_TERMINATED.
3838 */
3839 if (mMachineState != MachineState_Saving)
3840 setMachineState (MachineState_Stopping);
3841
3842 LogFlowThisFunc (("Powering off the VM...\n"));
3843
3844 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
3845 alock.leave();
3846
3847 vrc = VMR3PowerOff (mpVM);
3848 /*
3849 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
3850 * VM-(guest-)initiated power off happened in parallel a ms before
3851 * this call. So far, we let this error pop up on the user's side.
3852 */
3853
3854 alock.enter();
3855 }
3856
3857 LogFlowThisFunc (("Ready for VM destruction\n"));
3858
3859 /*
3860 * If we are called from Console::uninit(), then try to destroy the VM
3861 * even on failure (this will most likely fail too, but what to do?..)
3862 */
3863 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
3864 {
3865 /*
3866 * Stop the VRDP server and release all USB device.
3867 * (When called from uninit mConsoleVRDPServer is already destroyed.)
3868 */
3869 if (mConsoleVRDPServer)
3870 {
3871 LogFlowThisFunc (("Stopping VRDP server...\n"));
3872
3873 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
3874 alock.leave();
3875
3876 mConsoleVRDPServer->Stop();
3877
3878 alock.enter();
3879 }
3880
3881 /* If the machine has an USB comtroller, release all USB devices
3882 * (symmetric to the code in captureUSBDevices()) */
3883 bool fHasUSBController = false;
3884 {
3885 PPDMIBASE pBase;
3886 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3887 if (VBOX_SUCCESS (vrc))
3888 {
3889 fHasUSBController = true;
3890 detachAllUSBDevices (false /* aDone */);
3891 }
3892 }
3893
3894 /*
3895 * Now we've got to destroy the VM as well. (mpVM is not valid
3896 * beyond this point). We leave the lock before calling VMR3Destroy()
3897 * because it will result into calling destructors of drivers
3898 * associated with Console children which may in turn try to lock
3899 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
3900 * here because mVMDestroying is set which should prevent any activity.
3901 */
3902
3903 /*
3904 * Set mpVM to NULL early just in case if some old code is not using
3905 * addVMCaller()/releaseVMCaller().
3906 */
3907 PVM pVM = mpVM;
3908 mpVM = NULL;
3909
3910 LogFlowThisFunc (("Destroying the VM...\n"));
3911
3912 alock.leave();
3913
3914 vrc = VMR3Destroy (pVM);
3915
3916 /* take the lock again */
3917 alock.enter();
3918
3919 if (VBOX_SUCCESS (vrc))
3920 {
3921 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
3922 mMachineState));
3923 /*
3924 * Note: the Console-level machine state change happens on the
3925 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
3926 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
3927 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
3928 * occured yet. This is okay, because mMachineState is already
3929 * Stopping in this case, so any other attempt to call PowerDown()
3930 * will be rejected.
3931 */
3932 }
3933 else
3934 {
3935 /* bad bad bad, but what to do? */
3936 mpVM = pVM;
3937 rc = setError (E_FAIL,
3938 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
3939 }
3940
3941 /*
3942 * Complete the detaching of the USB devices.
3943 */
3944 if (fHasUSBController)
3945 detachAllUSBDevices (true /* aDone */);
3946 }
3947 else
3948 {
3949 rc = setError (E_FAIL,
3950 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
3951 }
3952
3953 /*
3954 * Finished with destruction. Note that if something impossible happened
3955 * and we've failed to destroy the VM, mVMDestroying will remain false and
3956 * mMachineState will be something like Stopping, so most Console methods
3957 * will return an error to the caller.
3958 */
3959 if (mpVM == NULL)
3960 mVMDestroying = false;
3961
3962 if (SUCCEEDED (rc))
3963 {
3964 /* uninit dynamically allocated members of mCallbackData */
3965 if (mCallbackData.mpsc.valid)
3966 {
3967 if (mCallbackData.mpsc.shape != NULL)
3968 RTMemFree (mCallbackData.mpsc.shape);
3969 }
3970 memset (&mCallbackData, 0, sizeof (mCallbackData));
3971 }
3972
3973 LogFlowThisFuncLeave();
3974 return rc;
3975}
3976
3977/**
3978 * @note Locks this object for writing.
3979 */
3980HRESULT Console::setMachineState (MachineState_T aMachineState,
3981 bool aUpdateServer /* = true */)
3982{
3983 AutoCaller autoCaller (this);
3984 AssertComRCReturnRC (autoCaller.rc());
3985
3986 AutoLock alock (this);
3987
3988 HRESULT rc = S_OK;
3989
3990 if (mMachineState != aMachineState)
3991 {
3992 LogFlowThisFunc (("machineState=%d\n", aMachineState));
3993 mMachineState = aMachineState;
3994
3995 /// @todo (dmik)
3996 // possibly, we need to redo onStateChange() using the dedicated
3997 // Event thread, like it is done in VirtualBox. This will make it
3998 // much safer (no deadlocks possible if someone tries to use the
3999 // console from the callback), however, listeners will lose the
4000 // ability to synchronously react to state changes (is it really
4001 // necessary??)
4002 LogFlowThisFunc (("Doing onStateChange()...\n"));
4003 onStateChange (aMachineState);
4004 LogFlowThisFunc (("Done onStateChange()\n"));
4005
4006 if (aUpdateServer)
4007 {
4008 /*
4009 * Server notification MUST be done from under the lock; otherwise
4010 * the machine state here and on the server might go out of sync, that
4011 * can lead to various unexpected results (like the machine state being
4012 * >= MachineState_Running on the server, while the session state is
4013 * already SessionState_SessionClosed at the same time there).
4014 *
4015 * Cross-lock conditions should be carefully watched out: calling
4016 * UpdateState we will require Machine and SessionMachine locks
4017 * (remember that here we're holding the Console lock here, and
4018 * also all locks that have been entered by the thread before calling
4019 * this method).
4020 */
4021 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4022 rc = mControl->UpdateState (aMachineState);
4023 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4024 }
4025 }
4026
4027 return rc;
4028}
4029
4030/**
4031 * Searches for a shared folder with the given logical name
4032 * in the collection of shared folders.
4033 *
4034 * @param aName logical name of the shared folder
4035 * @param aSharedFolder where to return the found object
4036 * @param aSetError whether to set the error info if the folder is
4037 * not found
4038 * @return
4039 * S_OK when found or E_INVALIDARG when not found
4040 *
4041 * @note The caller must lock this object for writing.
4042 */
4043HRESULT Console::findSharedFolder (const BSTR aName,
4044 ComObjPtr <SharedFolder> &aSharedFolder,
4045 bool aSetError /* = false */)
4046{
4047 /* sanity check */
4048 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4049
4050 bool found = false;
4051 for (SharedFolderList::const_iterator it = mSharedFolders.begin();
4052 !found && it != mSharedFolders.end();
4053 ++ it)
4054 {
4055 AutoLock alock (*it);
4056 found = (*it)->name() == aName;
4057 if (found)
4058 aSharedFolder = *it;
4059 }
4060
4061 HRESULT rc = found ? S_OK : E_INVALIDARG;
4062
4063 if (aSetError && !found)
4064 setError (rc, tr ("Could not find a shared folder named '%ls'."), aName);
4065
4066 return rc;
4067}
4068
4069/**
4070 * VM state callback function. Called by the VMM
4071 * using its state machine states.
4072 *
4073 * Primarily used to handle VM initiated power off, suspend and state saving,
4074 * but also for doing termination completed work (VMSTATE_TERMINATE).
4075 *
4076 * In general this function is called in the context of the EMT.
4077 *
4078 * @param aVM The VM handle.
4079 * @param aState The new state.
4080 * @param aOldState The old state.
4081 * @param aUser The user argument (pointer to the Console object).
4082 *
4083 * @note Locks the Console object for writing.
4084 */
4085DECLCALLBACK(void)
4086Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
4087 void *aUser)
4088{
4089 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
4090 aOldState, aState, aVM));
4091
4092 Console *that = static_cast <Console *> (aUser);
4093 AssertReturnVoid (that);
4094
4095 AutoCaller autoCaller (that);
4096 /*
4097 * Note that we must let this method proceed even if Console::uninit() has
4098 * been already called. In such case this VMSTATE change is a result of:
4099 * 1) powerDown() called from uninit() itself, or
4100 * 2) VM-(guest-)initiated power off.
4101 */
4102 AssertReturnVoid (autoCaller.isOk() ||
4103 autoCaller.state() == InUninit);
4104
4105 switch (aState)
4106 {
4107 /*
4108 * The VM has terminated
4109 */
4110 case VMSTATE_OFF:
4111 {
4112 AutoLock alock (that);
4113
4114 if (that->mVMStateChangeCallbackDisabled)
4115 break;
4116
4117 /*
4118 * Do we still think that it is running? It may happen if this is
4119 * a VM-(guest-)initiated shutdown/poweroff.
4120 */
4121 if (that->mMachineState != MachineState_Stopping &&
4122 that->mMachineState != MachineState_Saving &&
4123 that->mMachineState != MachineState_Restoring)
4124 {
4125 LogFlowFunc (("VM has powered itself off but Console still "
4126 "thinks it is running. Notifying.\n"));
4127
4128 /* prevent powerDown() from calling VMR3PowerOff() again */
4129 that->setMachineState (MachineState_Stopping);
4130
4131 /*
4132 * Setup task object and thread to carry out the operation
4133 * asynchronously (if we call powerDown() right here but there
4134 * is one or more mpVM callers (added with addVMCaller()) we'll
4135 * deadlock.
4136 */
4137 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
4138 /*
4139 * If creating a task is falied, this can currently mean one
4140 * of two: either Console::uninit() has been called just a ms
4141 * before (so a powerDown() call is already on the way), or
4142 * powerDown() itself is being already executed. Just do
4143 * nothing .
4144 */
4145 if (!task->isOk())
4146 {
4147 LogFlowFunc (("Console is already being uninitialized.\n"));
4148 break;
4149 }
4150
4151 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
4152 (void *) task.get(), 0,
4153 RTTHREADTYPE_MAIN_WORKER, 0,
4154 "VMPowerDowm");
4155
4156 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
4157 if (VBOX_FAILURE (vrc))
4158 break;
4159
4160 /* task is now owned by powerDownThread(), so release it */
4161 task.release();
4162 }
4163 break;
4164 }
4165
4166 /*
4167 * The VM has been completely destroyed.
4168 *
4169 * Note: This state change can happen at two points:
4170 * 1) At the end of VMR3Destroy() if it was not called from EMT.
4171 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
4172 * called by EMT.
4173 */
4174 case VMSTATE_TERMINATED:
4175 {
4176 AutoLock alock (that);
4177
4178 if (that->mVMStateChangeCallbackDisabled)
4179 break;
4180
4181 /*
4182 * Terminate host interface networking. If aVM is NULL, we've been
4183 * manually called from powerUpThread() either before calling
4184 * VMR3Create() or after VMR3Create() failed, so no need to touch
4185 * networking.
4186 */
4187 if (aVM)
4188 that->powerDownHostInterfaces();
4189
4190 /*
4191 * From now on the machine is officially powered down or
4192 * remains in the Saved state.
4193 */
4194 switch (that->mMachineState)
4195 {
4196 default:
4197 AssertFailed();
4198 /* fall through */
4199 case MachineState_Stopping:
4200 /* successfully powered down */
4201 that->setMachineState (MachineState_PoweredOff);
4202 break;
4203 case MachineState_Saving:
4204 /*
4205 * successfully saved (note that the machine is already
4206 * in the Saved state on the server due to EndSavingState()
4207 * called from saveStateThread(), so only change the local
4208 * state)
4209 */
4210 that->setMachineStateLocally (MachineState_Saved);
4211 break;
4212 case MachineState_Starting:
4213 /*
4214 * failed to start, but be patient: set back to PoweredOff
4215 * (for similarity with the below)
4216 */
4217 that->setMachineState (MachineState_PoweredOff);
4218 break;
4219 case MachineState_Restoring:
4220 /*
4221 * failed to load the saved state file, but be patient:
4222 * set back to Saved (to preserve the saved state file)
4223 */
4224 that->setMachineState (MachineState_Saved);
4225 break;
4226 }
4227
4228 break;
4229 }
4230
4231 case VMSTATE_SUSPENDED:
4232 {
4233 if (aOldState == VMSTATE_RUNNING)
4234 {
4235 AutoLock alock (that);
4236
4237 if (that->mVMStateChangeCallbackDisabled)
4238 break;
4239
4240 /* Change the machine state from Running to Paused */
4241 Assert (that->mMachineState == MachineState_Running);
4242 that->setMachineState (MachineState_Paused);
4243 }
4244 }
4245
4246 case VMSTATE_RUNNING:
4247 {
4248 if (aOldState == VMSTATE_CREATED ||
4249 aOldState == VMSTATE_SUSPENDED)
4250 {
4251 AutoLock alock (that);
4252
4253 if (that->mVMStateChangeCallbackDisabled)
4254 break;
4255
4256 /*
4257 * Change the machine state from Starting, Restoring or Paused
4258 * to Running
4259 */
4260 Assert ((that->mMachineState == MachineState_Starting &&
4261 aOldState == VMSTATE_CREATED) ||
4262 ((that->mMachineState == MachineState_Restoring ||
4263 that->mMachineState == MachineState_Paused) &&
4264 aOldState == VMSTATE_SUSPENDED));
4265
4266 that->setMachineState (MachineState_Running);
4267 }
4268 }
4269
4270 default: /* shut up gcc */
4271 break;
4272 }
4273}
4274
4275/**
4276 * Sends a request to VMM to attach the given host device.
4277 * After this method succeeds, the attached device will appear in the
4278 * mUSBDevices collection.
4279 *
4280 * @param aHostDevice device to attach
4281 *
4282 * @note Synchronously calls EMT.
4283 * @note Must be called from under this object's lock.
4284 */
4285HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, PVUSBIRHCONFIG aConfig)
4286{
4287 AssertReturn (aHostDevice && aConfig, E_FAIL);
4288
4289 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4290
4291 /* still want a lock object because we need to leave it */
4292 AutoLock alock (this);
4293
4294 HRESULT hrc;
4295
4296 /*
4297 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
4298 * method in EMT (using usbAttachCallback()).
4299 */
4300 Bstr BstrAddress;
4301 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
4302 ComAssertComRCRetRC (hrc);
4303
4304 Utf8Str Address (BstrAddress);
4305
4306 Guid Uuid;
4307 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
4308 ComAssertComRCRetRC (hrc);
4309
4310 BOOL fRemote = FALSE;
4311 void *pvRemote = NULL;
4312
4313 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
4314 ComAssertComRCRetRC (hrc);
4315
4316 /* protect mpVM */
4317 AutoVMCaller autoVMCaller (this);
4318 CheckComRCReturnRC (autoVMCaller.rc());
4319
4320 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
4321 Address.raw(), Uuid.ptr()));
4322
4323 /* leave the lock before a VMR3* call (EMT will call us back)! */
4324 alock.leave();
4325
4326 PVMREQ pReq = NULL;
4327 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4328 (PFNRT) usbAttachCallback, 7,
4329 this, aHostDevice,
4330 aConfig, Uuid.ptr(), fRemote, Address.raw(), pvRemote);
4331 if (VBOX_SUCCESS (vrc))
4332 vrc = pReq->iStatus;
4333 VMR3ReqFree (pReq);
4334
4335 /* restore the lock */
4336 alock.enter();
4337
4338 /* hrc is S_OK here */
4339
4340 if (VBOX_FAILURE (vrc))
4341 {
4342 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
4343 Address.raw(), Uuid.ptr(), vrc));
4344
4345 switch (vrc)
4346 {
4347 case VERR_VUSB_NO_PORTS:
4348 hrc = setError (E_FAIL,
4349 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
4350 break;
4351 case VERR_VUSB_USBFS_PERMISSION:
4352 hrc = setError (E_FAIL,
4353 tr ("Not permitted to open the USB device, check usbfs options"));
4354 break;
4355 default:
4356 hrc = setError (E_FAIL,
4357 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
4358 break;
4359 }
4360 }
4361
4362 return hrc;
4363}
4364
4365/**
4366 * USB device attach callback used by AttachUSBDevice().
4367 * Note that AttachUSBDevice() doesn't return until this callback is executed,
4368 * so we don't use AutoCaller and don't care about reference counters of
4369 * interface pointers passed in.
4370 *
4371 * @thread EMT
4372 * @note Locks the console object for writing.
4373 */
4374//static
4375DECLCALLBACK(int)
4376Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice,
4377 PVUSBIRHCONFIG aConfig, PCRTUUID aUuid, bool aRemote,
4378 const char *aAddress, void *aRemoteBackend)
4379{
4380 LogFlowFuncEnter();
4381 LogFlowFunc (("that={%p}\n", that));
4382
4383 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4384
4385 if (aRemote)
4386 {
4387 /* @todo aRemoteBackend input parameter is not needed. */
4388 Assert (aRemoteBackend == NULL);
4389
4390 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
4391
4392 Guid guid (*aUuid);
4393
4394 aRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
4395
4396 if (aRemoteBackend == NULL)
4397 {
4398 /* The clientId is invalid then. */
4399 return VERR_INVALID_PARAMETER;
4400 }
4401 }
4402
4403 int vrc = aConfig->pfnCreateProxyDevice (aConfig, aUuid, aRemote, aAddress,
4404 aRemoteBackend);
4405
4406 if (VBOX_SUCCESS (vrc))
4407 {
4408 /* Create a OUSBDevice and add it to the device list */
4409 ComObjPtr <OUSBDevice> device;
4410 device.createObject();
4411 HRESULT hrc = device->init (aHostDevice);
4412 AssertComRC (hrc);
4413
4414 AutoLock alock (that);
4415 that->mUSBDevices.push_back (device);
4416 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
4417
4418 /* notify callbacks */
4419 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
4420 }
4421
4422 LogFlowFunc (("vrc=%Vrc\n", vrc));
4423 LogFlowFuncLeave();
4424 return vrc;
4425}
4426
4427/**
4428 * Sends a request to VMM to detach the given host device. After this method
4429 * succeeds, the detached device will disappear from the mUSBDevices
4430 * collection.
4431 *
4432 * @param aIt Iterator pointing to the device to detach.
4433 *
4434 * @note Synchronously calls EMT.
4435 * @note Must be called from under this object's lock.
4436 */
4437HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
4438{
4439 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4440
4441 /* still want a lock object because we need to leave it */
4442 AutoLock alock (this);
4443
4444 /* protect mpVM */
4445 AutoVMCaller autoVMCaller (this);
4446 CheckComRCReturnRC (autoVMCaller.rc());
4447
4448 PPDMIBASE pBase = NULL;
4449 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4450
4451 /* if the device is attached, then there must be a USB controller */
4452 AssertRCReturn (vrc, E_FAIL);
4453
4454 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
4455 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
4456 AssertReturn (pRhConfig, E_FAIL);
4457
4458 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
4459 (*aIt)->id().raw()));
4460
4461 /* leave the lock before a VMR3* call (EMT will call us back)! */
4462 alock.leave();
4463
4464 PVMREQ pReq;
4465 vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4466 (PFNRT) usbDetachCallback, 5,
4467 this, &aIt, pRhConfig, (*aIt)->id().raw());
4468 if (VBOX_SUCCESS (vrc))
4469 vrc = pReq->iStatus;
4470 VMR3ReqFree (pReq);
4471
4472 ComAssertRCRet (vrc, E_FAIL);
4473
4474 return S_OK;
4475}
4476
4477/**
4478 * USB device detach callback used by DetachUSBDevice().
4479 * Note that DetachUSBDevice() doesn't return until this callback is executed,
4480 * so we don't use AutoCaller and don't care about reference counters of
4481 * interface pointers passed in.
4482 *
4483 * @thread EMT
4484 * @note Locks the console object for writing.
4485 */
4486//static
4487DECLCALLBACK(int)
4488Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt,
4489 PVUSBIRHCONFIG aConfig, PCRTUUID aUuid)
4490{
4491 LogFlowFuncEnter();
4492 LogFlowFunc (("that={%p}\n", that));
4493
4494 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4495
4496 /*
4497 * If that was a remote device, release the backend pointer.
4498 * The pointer was requested in usbAttachCallback.
4499 */
4500 BOOL fRemote = FALSE;
4501
4502 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
4503 ComAssertComRC (hrc2);
4504
4505 if (fRemote)
4506 {
4507 Guid guid (*aUuid);
4508 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
4509 }
4510
4511 int vrc = aConfig->pfnDestroyProxyDevice (aConfig, aUuid);
4512
4513 if (VBOX_SUCCESS (vrc))
4514 {
4515 AutoLock alock (that);
4516
4517 /* Remove the device from the collection */
4518 that->mUSBDevices.erase (*aIt);
4519 LogFlowFunc (("Detached device {%Vuuid}\n", (**aIt)->id().raw()));
4520
4521 /* notify callbacks */
4522 that->onUSBDeviceStateChange (**aIt, false /* aAttached */, NULL);
4523 }
4524
4525 LogFlowFunc (("vrc=%Vrc\n", vrc));
4526 LogFlowFuncLeave();
4527 return vrc;
4528}
4529
4530/**
4531 * Construct the VM configuration tree (CFGM).
4532 *
4533 * This is a callback for VMR3Create() call. It is called from CFGMR3Init()
4534 * in the emulation thread (EMT). Any per thread COM/XPCOM initialization
4535 * is done here.
4536 *
4537 * @param pVM VM handle.
4538 * @param pvTask Pointer to the VMPowerUpTask object.
4539 * @return VBox status code.
4540 *
4541 * @note Locks the Console object for writing.
4542 */
4543DECLCALLBACK(int) Console::configConstructor(PVM pVM, void *pvTask)
4544{
4545 LogFlowFuncEnter();
4546
4547 /* Note: the task pointer is owned by powerUpThread() */
4548 VMPowerUpTask *task = static_cast <VMPowerUpTask *> (pvTask);
4549 AssertReturn (task, VERR_GENERAL_FAILURE);
4550
4551#if defined(RT_OS_WINDOWS)
4552 {
4553 /* initialize COM */
4554 HRESULT hrc = CoInitializeEx(NULL,
4555 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
4556 COINIT_SPEED_OVER_MEMORY);
4557 LogFlow (("Console::configConstructor(): CoInitializeEx()=%08X\n", hrc));
4558 AssertComRCReturn (hrc, VERR_GENERAL_FAILURE);
4559 }
4560#endif
4561
4562 ComObjPtr <Console> pConsole = task->mConsole;
4563
4564 AutoCaller autoCaller (pConsole);
4565 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
4566
4567 /* lock the console because we widely use internal fields and methods */
4568 AutoLock alock (pConsole);
4569
4570 ComPtr <IMachine> pMachine = pConsole->machine();
4571
4572 int rc;
4573 HRESULT hrc;
4574 char *psz = NULL;
4575 BSTR str = NULL;
4576 ULONG cRamMBs;
4577 ULONG cMonitors;
4578 unsigned i;
4579
4580#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
4581#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
4582#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
4583#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); return VERR_GENERAL_FAILURE; } } while (0)
4584
4585 /* Get necessary objects */
4586
4587 ComPtr<IVirtualBox> virtualBox;
4588 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
4589
4590 ComPtr<IHost> host;
4591 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
4592
4593 ComPtr <ISystemProperties> systemProperties;
4594 hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam()); H();
4595
4596 ComPtr<IBIOSSettings> biosSettings;
4597 hrc = pMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam()); H();
4598
4599
4600 /*
4601 * Get root node first.
4602 * This is the only node in the tree.
4603 */
4604 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4605 Assert(pRoot);
4606
4607 /*
4608 * Set the root level values.
4609 */
4610 hrc = pMachine->COMGETTER(Name)(&str); H();
4611 STR_CONV();
4612 rc = CFGMR3InsertString(pRoot, "Name", psz); RC_CHECK();
4613 STR_FREE();
4614 hrc = pMachine->COMGETTER(MemorySize)(&cRamMBs); H();
4615 rc = CFGMR3InsertInteger(pRoot, "RamSize", cRamMBs * _1M); RC_CHECK();
4616 rc = CFGMR3InsertInteger(pRoot, "TimerMillies", 10); RC_CHECK();
4617 rc = CFGMR3InsertInteger(pRoot, "RawR3Enabled", 1); /* boolean */ RC_CHECK();
4618 rc = CFGMR3InsertInteger(pRoot, "RawR0Enabled", 1); /* boolean */ RC_CHECK();
4619 /** @todo Config: RawR0, PATMEnabled and CASMEnabled needs attention later. */
4620 rc = CFGMR3InsertInteger(pRoot, "PATMEnabled", 1); /* boolean */ RC_CHECK();
4621 rc = CFGMR3InsertInteger(pRoot, "CSAMEnabled", 1); /* boolean */ RC_CHECK();
4622
4623 /* hardware virtualization extensions */
4624 TriStateBool_T hwVirtExEnabled;
4625 BOOL fHWVirtExEnabled;
4626 hrc = pMachine->COMGETTER(HWVirtExEnabled)(&hwVirtExEnabled); H();
4627 if (hwVirtExEnabled == TriStateBool_Default)
4628 {
4629 /* check the default value */
4630 hrc = systemProperties->COMGETTER(HWVirtExEnabled)(&fHWVirtExEnabled); H();
4631 }
4632 else
4633 fHWVirtExEnabled = (hwVirtExEnabled == TriStateBool_True);
4634#ifndef RT_OS_DARWIN /** @todo Implement HWVirtExt on darwin. See #1865. */
4635 if (fHWVirtExEnabled)
4636 {
4637 PCFGMNODE pHWVirtExt;
4638 rc = CFGMR3InsertNode(pRoot, "HWVirtExt", &pHWVirtExt); RC_CHECK();
4639 rc = CFGMR3InsertInteger(pHWVirtExt, "Enabled", 1); RC_CHECK();
4640 }
4641#endif
4642
4643 BOOL fIOAPIC;
4644 hrc = biosSettings->COMGETTER(IOAPICEnabled)(&fIOAPIC); H();
4645
4646 /*
4647 * PDM config.
4648 * Load drivers in VBoxC.[so|dll]
4649 */
4650 PCFGMNODE pPDM;
4651 PCFGMNODE pDrivers;
4652 PCFGMNODE pMod;
4653 rc = CFGMR3InsertNode(pRoot, "PDM", &pPDM); RC_CHECK();
4654 rc = CFGMR3InsertNode(pPDM, "Drivers", &pDrivers); RC_CHECK();
4655 rc = CFGMR3InsertNode(pDrivers, "VBoxC", &pMod); RC_CHECK();
4656#ifdef VBOX_WITH_XPCOM
4657 // VBoxC is located in the components subdirectory
4658 char szPathVBoxC[RTPATH_MAX];
4659 rc = RTPathAppPrivateArch(szPathVBoxC, RTPATH_MAX - sizeof("/components/VBoxC")); AssertRC(rc);
4660 strcat(szPathVBoxC, "/components/VBoxC");
4661 rc = CFGMR3InsertString(pMod, "Path", szPathVBoxC); RC_CHECK();
4662#else
4663 rc = CFGMR3InsertString(pMod, "Path", "VBoxC"); RC_CHECK();
4664#endif
4665
4666 /*
4667 * Devices
4668 */
4669 PCFGMNODE pDevices = NULL; /* /Devices */
4670 PCFGMNODE pDev = NULL; /* /Devices/Dev/ */
4671 PCFGMNODE pInst = NULL; /* /Devices/Dev/0/ */
4672 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
4673 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
4674 PCFGMNODE pLunL1 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
4675 PCFGMNODE pLunL2 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/Config/ */
4676
4677 rc = CFGMR3InsertNode(pRoot, "Devices", &pDevices); RC_CHECK();
4678
4679 /*
4680 * PC Arch.
4681 */
4682 rc = CFGMR3InsertNode(pDevices, "pcarch", &pDev); RC_CHECK();
4683 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4684 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4685 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4686
4687 /*
4688 * PC Bios.
4689 */
4690 rc = CFGMR3InsertNode(pDevices, "pcbios", &pDev); RC_CHECK();
4691 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4692 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4693 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4694 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
4695 rc = CFGMR3InsertString(pCfg, "HardDiskDevice", "piix3ide"); RC_CHECK();
4696 rc = CFGMR3InsertString(pCfg, "FloppyDevice", "i82078"); RC_CHECK();
4697 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4698
4699 DeviceType_T bootDevice;
4700 if (SchemaDefs::MaxBootPosition > 9)
4701 {
4702 AssertMsgFailed (("Too many boot devices %d\n",
4703 SchemaDefs::MaxBootPosition));
4704 return VERR_INVALID_PARAMETER;
4705 }
4706
4707 for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; pos ++)
4708 {
4709 hrc = pMachine->GetBootOrder(pos, &bootDevice); H();
4710
4711 char szParamName[] = "BootDeviceX";
4712 szParamName[sizeof (szParamName) - 2] = ((char (pos - 1)) + '0');
4713
4714 const char *pszBootDevice;
4715 switch (bootDevice)
4716 {
4717 case DeviceType_NoDevice:
4718 pszBootDevice = "NONE";
4719 break;
4720 case DeviceType_HardDiskDevice:
4721 pszBootDevice = "IDE";
4722 break;
4723 case DeviceType_DVDDevice:
4724 pszBootDevice = "DVD";
4725 break;
4726 case DeviceType_FloppyDevice:
4727 pszBootDevice = "FLOPPY";
4728 break;
4729 case DeviceType_NetworkDevice:
4730 pszBootDevice = "LAN";
4731 break;
4732 default:
4733 AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
4734 return VERR_INVALID_PARAMETER;
4735 }
4736 rc = CFGMR3InsertString(pCfg, szParamName, pszBootDevice); RC_CHECK();
4737 }
4738
4739 /*
4740 * BIOS logo
4741 */
4742 BOOL fFadeIn;
4743 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
4744 rc = CFGMR3InsertInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0); RC_CHECK();
4745 BOOL fFadeOut;
4746 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
4747 rc = CFGMR3InsertInteger(pCfg, "FadeOut", fFadeOut ? 1: 0); RC_CHECK();
4748 ULONG logoDisplayTime;
4749 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
4750 rc = CFGMR3InsertInteger(pCfg, "LogoTime", logoDisplayTime); RC_CHECK();
4751 Bstr logoImagePath;
4752 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
4753 rc = CFGMR3InsertString(pCfg, "LogoFile", logoImagePath ? Utf8Str(logoImagePath) : ""); RC_CHECK();
4754
4755 /*
4756 * Boot menu
4757 */
4758 BIOSBootMenuMode_T bootMenuMode;
4759 int value;
4760 biosSettings->COMGETTER(BootMenuMode)(&bootMenuMode);
4761 switch (bootMenuMode)
4762 {
4763 case BIOSBootMenuMode_Disabled:
4764 value = 0;
4765 break;
4766 case BIOSBootMenuMode_MenuOnly:
4767 value = 1;
4768 break;
4769 default:
4770 value = 2;
4771 }
4772 rc = CFGMR3InsertInteger(pCfg, "ShowBootMenu", value); RC_CHECK();
4773
4774 /*
4775 * The time offset
4776 */
4777 LONG64 timeOffset;
4778 hrc = biosSettings->COMGETTER(TimeOffset)(&timeOffset); H();
4779 PCFGMNODE pTMNode;
4780 rc = CFGMR3InsertNode(pRoot, "TM", &pTMNode); RC_CHECK();
4781 rc = CFGMR3InsertInteger(pTMNode, "UTCOffset", timeOffset * 1000000); RC_CHECK();
4782
4783 /*
4784 * ACPI
4785 */
4786 BOOL fACPI;
4787 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
4788 if (fACPI)
4789 {
4790 rc = CFGMR3InsertNode(pDevices, "acpi", &pDev); RC_CHECK();
4791 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4792 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4793 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4794 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
4795 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4796 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 7); RC_CHECK();
4797 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
4798
4799 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4800 rc = CFGMR3InsertString(pLunL0, "Driver", "ACPIHost"); RC_CHECK();
4801 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4802 }
4803
4804 /*
4805 * DMA
4806 */
4807 rc = CFGMR3InsertNode(pDevices, "8237A", &pDev); RC_CHECK();
4808 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4809 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4810
4811 /*
4812 * PCI bus.
4813 */
4814 rc = CFGMR3InsertNode(pDevices, "pci", &pDev); /* piix3 */ RC_CHECK();
4815 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4816 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4817 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4818 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4819
4820 /*
4821 * PS/2 keyboard & mouse.
4822 */
4823 rc = CFGMR3InsertNode(pDevices, "pckbd", &pDev); RC_CHECK();
4824 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4825 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4826 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4827
4828 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4829 rc = CFGMR3InsertString(pLunL0, "Driver", "KeyboardQueue"); RC_CHECK();
4830 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4831 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 64); RC_CHECK();
4832
4833 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4834 rc = CFGMR3InsertString(pLunL1, "Driver", "MainKeyboard"); RC_CHECK();
4835 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4836 Keyboard *pKeyboard = pConsole->mKeyboard;
4837 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pKeyboard); RC_CHECK();
4838
4839 rc = CFGMR3InsertNode(pInst, "LUN#1", &pLunL0); RC_CHECK();
4840 rc = CFGMR3InsertString(pLunL0, "Driver", "MouseQueue"); RC_CHECK();
4841 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4842 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 128); RC_CHECK();
4843
4844 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4845 rc = CFGMR3InsertString(pLunL1, "Driver", "MainMouse"); RC_CHECK();
4846 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4847 Mouse *pMouse = pConsole->mMouse;
4848 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pMouse); RC_CHECK();
4849
4850 /*
4851 * i82078 Floppy drive controller
4852 */
4853 ComPtr<IFloppyDrive> floppyDrive;
4854 hrc = pMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam()); H();
4855 BOOL fFloppyEnabled;
4856 hrc = floppyDrive->COMGETTER(Enabled)(&fFloppyEnabled); H();
4857 if (fFloppyEnabled)
4858 {
4859 rc = CFGMR3InsertNode(pDevices, "i82078", &pDev); RC_CHECK();
4860 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4861 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); RC_CHECK();
4862 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4863 rc = CFGMR3InsertInteger(pCfg, "IRQ", 6); RC_CHECK();
4864 rc = CFGMR3InsertInteger(pCfg, "DMA", 2); RC_CHECK();
4865 rc = CFGMR3InsertInteger(pCfg, "MemMapped", 0 ); RC_CHECK();
4866 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x3f0); RC_CHECK();
4867
4868 /* Attach the status driver */
4869 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
4870 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
4871 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4872 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapFDLeds[0]); RC_CHECK();
4873 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
4874 rc = CFGMR3InsertInteger(pCfg, "Last", 0); RC_CHECK();
4875
4876 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4877
4878 ComPtr<IFloppyImage> floppyImage;
4879 hrc = floppyDrive->GetImage(floppyImage.asOutParam()); H();
4880 if (floppyImage)
4881 {
4882 pConsole->meFloppyState = DriveState_ImageMounted;
4883 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4884 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4885 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
4886 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4887
4888 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4889 rc = CFGMR3InsertString(pLunL1, "Driver", "RawImage"); RC_CHECK();
4890 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4891 hrc = floppyImage->COMGETTER(FilePath)(&str); H();
4892 STR_CONV();
4893 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4894 STR_FREE();
4895 }
4896 else
4897 {
4898 ComPtr<IHostFloppyDrive> hostFloppyDrive;
4899 hrc = floppyDrive->GetHostDrive(hostFloppyDrive.asOutParam()); H();
4900 if (hostFloppyDrive)
4901 {
4902 pConsole->meFloppyState = DriveState_HostDriveCaptured;
4903 rc = CFGMR3InsertString(pLunL0, "Driver", "HostFloppy"); RC_CHECK();
4904 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4905 hrc = hostFloppyDrive->COMGETTER(Name)(&str); H();
4906 STR_CONV();
4907 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4908 STR_FREE();
4909 }
4910 else
4911 {
4912 pConsole->meFloppyState = DriveState_NotMounted;
4913 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4914 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4915 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
4916 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4917 }
4918 }
4919 }
4920
4921 /*
4922 * i8254 Programmable Interval Timer And Dummy Speaker
4923 */
4924 rc = CFGMR3InsertNode(pDevices, "i8254", &pDev); RC_CHECK();
4925 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4926 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4927#ifdef DEBUG
4928 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4929#endif
4930
4931 /*
4932 * i8259 Programmable Interrupt Controller.
4933 */
4934 rc = CFGMR3InsertNode(pDevices, "i8259", &pDev); RC_CHECK();
4935 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4936 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4937 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4938
4939 /*
4940 * Advanced Programmable Interrupt Controller.
4941 */
4942 rc = CFGMR3InsertNode(pDevices, "apic", &pDev); RC_CHECK();
4943 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4944 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4945 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4946 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4947
4948 if (fIOAPIC)
4949 {
4950 /*
4951 * I/O Advanced Programmable Interrupt Controller.
4952 */
4953 rc = CFGMR3InsertNode(pDevices, "ioapic", &pDev); RC_CHECK();
4954 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4955 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4956 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4957 }
4958
4959 /*
4960 * RTC MC146818.
4961 */
4962 rc = CFGMR3InsertNode(pDevices, "mc146818", &pDev); RC_CHECK();
4963 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4964 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4965
4966 /*
4967 * VGA.
4968 */
4969 rc = CFGMR3InsertNode(pDevices, "vga", &pDev); RC_CHECK();
4970 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4971 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4972 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 2); RC_CHECK();
4973 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
4974 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4975 hrc = pMachine->COMGETTER(VRAMSize)(&cRamMBs); H();
4976 rc = CFGMR3InsertInteger(pCfg, "VRamSize", cRamMBs * _1M); RC_CHECK();
4977 hrc = pMachine->COMGETTER(MonitorCount)(&cMonitors); H();
4978 rc = CFGMR3InsertInteger(pCfg, "MonitorCount", cMonitors); RC_CHECK();
4979
4980 /* Custom VESA mode list */
4981 unsigned cModes = 0;
4982 for (unsigned iMode = 1; iMode <= 16; iMode++)
4983 {
4984 char szExtraDataKey[sizeof("CustomVideoModeXX")];
4985 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%d", iMode);
4986 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey), &str); H();
4987 if (!str || !*str)
4988 break;
4989 STR_CONV();
4990 rc = CFGMR3InsertString(pCfg, szExtraDataKey, psz);
4991 STR_FREE();
4992 cModes++;
4993 }
4994 rc = CFGMR3InsertInteger(pCfg, "CustomVideoModes", cModes);
4995
4996 /* VESA height reduction */
4997 ULONG ulHeightReduction;
4998 IFramebuffer *pFramebuffer = pConsole->getDisplay()->getFramebuffer();
4999 if (pFramebuffer)
5000 {
5001 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
5002 }
5003 else
5004 {
5005 /* If framebuffer is not available, there is no height reduction. */
5006 ulHeightReduction = 0;
5007 }
5008 rc = CFGMR3InsertInteger(pCfg, "HeightReduction", ulHeightReduction); RC_CHECK();
5009
5010 /* Attach the display. */
5011 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5012 rc = CFGMR3InsertString(pLunL0, "Driver", "MainDisplay"); RC_CHECK();
5013 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5014 Display *pDisplay = pConsole->mDisplay;
5015 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pDisplay); RC_CHECK();
5016
5017 /*
5018 * IDE (update this when the main interface changes)
5019 */
5020 rc = CFGMR3InsertNode(pDevices, "piix3ide", &pDev); /* piix3 */ RC_CHECK();
5021 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5022 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5023 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 1); RC_CHECK();
5024 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 1); RC_CHECK();
5025 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5026
5027 /* Attach the status driver */
5028 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5029 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5030 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5031 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapIDELeds[0]);RC_CHECK();
5032 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
5033 rc = CFGMR3InsertInteger(pCfg, "Last", 3); RC_CHECK();
5034
5035 /* Attach the harddisks */
5036 ComPtr<IHardDiskAttachmentCollection> hdaColl;
5037 hrc = pMachine->COMGETTER(HardDiskAttachments)(hdaColl.asOutParam()); H();
5038 ComPtr<IHardDiskAttachmentEnumerator> hdaEnum;
5039 hrc = hdaColl->Enumerate(hdaEnum.asOutParam()); H();
5040
5041 BOOL fMore = FALSE;
5042 while ( SUCCEEDED(hrc = hdaEnum->HasMore(&fMore))
5043 && fMore)
5044 {
5045 ComPtr<IHardDiskAttachment> hda;
5046 hrc = hdaEnum->GetNext(hda.asOutParam()); H();
5047 ComPtr<IHardDisk> hardDisk;
5048 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
5049 DiskControllerType_T enmCtl;
5050 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
5051 LONG lDev;
5052 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
5053
5054 switch (enmCtl)
5055 {
5056 case DiskControllerType_IDE0Controller:
5057 i = 0;
5058 break;
5059 case DiskControllerType_IDE1Controller:
5060 i = 2;
5061 break;
5062 default:
5063 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
5064 return VERR_GENERAL_FAILURE;
5065 }
5066
5067 if (lDev < 0 || lDev >= 2)
5068 {
5069 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
5070 return VERR_GENERAL_FAILURE;
5071 }
5072
5073 i = i + lDev;
5074
5075 char szLUN[16];
5076 RTStrPrintf(szLUN, sizeof(szLUN), "LUN#%d", i);
5077 rc = CFGMR3InsertNode(pInst, szLUN, &pLunL0); RC_CHECK();
5078 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
5079 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5080 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
5081 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
5082
5083 HardDiskStorageType_T hddType;
5084 hardDisk->COMGETTER(StorageType)(&hddType);
5085 if (hddType == HardDiskStorageType_VirtualDiskImage)
5086 {
5087 ComPtr<IVirtualDiskImage> vdiDisk = hardDisk;
5088 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
5089
5090 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5091 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
5092 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5093 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
5094 STR_CONV();
5095 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5096 STR_FREE();
5097
5098 /* Create an inversed tree of parents. */
5099 ComPtr<IHardDisk> parentHardDisk = hardDisk;
5100 for (PCFGMNODE pParent = pCfg;;)
5101 {
5102 ComPtr<IHardDisk> curHardDisk;
5103 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
5104 if (!curHardDisk)
5105 break;
5106
5107 vdiDisk = curHardDisk;
5108 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
5109
5110 PCFGMNODE pCur;
5111 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
5112 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
5113 STR_CONV();
5114 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
5115 STR_FREE();
5116 rc = CFGMR3InsertInteger(pCur, "ReadOnly", 1); RC_CHECK();
5117
5118 /* next */
5119 pParent = pCur;
5120 parentHardDisk = curHardDisk;
5121 }
5122 }
5123 else if (hddType == HardDiskStorageType_ISCSIHardDisk)
5124 {
5125 ComPtr<IISCSIHardDisk> iSCSIDisk = hardDisk;
5126 AssertBreak (!iSCSIDisk.isNull(), hrc = E_FAIL);
5127
5128 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5129 rc = CFGMR3InsertString(pLunL1, "Driver", "iSCSI"); RC_CHECK();
5130 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5131
5132 /* Set up the iSCSI initiator driver configuration. */
5133 hrc = iSCSIDisk->COMGETTER(Target)(&str); H();
5134 STR_CONV();
5135 rc = CFGMR3InsertString(pCfg, "TargetName", psz); RC_CHECK();
5136 STR_FREE();
5137
5138 // @todo currently there is no Initiator name config.
5139 rc = CFGMR3InsertString(pCfg, "InitiatorName", "iqn.2006-02.de.innotek.initiator"); RC_CHECK();
5140
5141 ULONG64 lun;
5142 hrc = iSCSIDisk->COMGETTER(Lun)(&lun); H();
5143 rc = CFGMR3InsertInteger(pCfg, "LUN", lun); RC_CHECK();
5144
5145 hrc = iSCSIDisk->COMGETTER(Server)(&str); H();
5146 STR_CONV();
5147 USHORT port;
5148 hrc = iSCSIDisk->COMGETTER(Port)(&port); H();
5149 if (port != 0)
5150 {
5151 char *pszTN;
5152 RTStrAPrintf(&pszTN, "%s:%u", psz, port);
5153 rc = CFGMR3InsertString(pCfg, "TargetAddress", pszTN); RC_CHECK();
5154 RTStrFree(pszTN);
5155 }
5156 else
5157 {
5158 rc = CFGMR3InsertString(pCfg, "TargetAddress", psz); RC_CHECK();
5159 }
5160 STR_FREE();
5161
5162 hrc = iSCSIDisk->COMGETTER(UserName)(&str); H();
5163 if (str)
5164 {
5165 STR_CONV();
5166 rc = CFGMR3InsertString(pCfg, "InitiatorUsername", psz); RC_CHECK();
5167 STR_FREE();
5168 }
5169
5170 hrc = iSCSIDisk->COMGETTER(Password)(&str); H();
5171 if (str)
5172 {
5173 STR_CONV();
5174 rc = CFGMR3InsertString(pCfg, "InitiatorSecret", psz); RC_CHECK();
5175 STR_FREE();
5176 }
5177
5178 // @todo currently there is no target username config.
5179 //rc = CFGMR3InsertString(pCfg, "TargetUsername", ""); RC_CHECK();
5180
5181 // @todo currently there is no target password config.
5182 //rc = CFGMR3InsertString(pCfg, "TargetSecret", ""); RC_CHECK();
5183
5184 /* The iSCSI initiator needs an attached iSCSI transport driver. */
5185 rc = CFGMR3InsertNode(pLunL1, "AttachedDriver", &pLunL2); RC_CHECK();
5186 rc = CFGMR3InsertString(pLunL2, "Driver", "iSCSITCP"); RC_CHECK();
5187 /* Currently the transport driver has no config options. */
5188 }
5189 else if (hddType == HardDiskStorageType_VMDKImage)
5190 {
5191 ComPtr<IVMDKImage> vmdkDisk = hardDisk;
5192 AssertBreak (!vmdkDisk.isNull(), hrc = E_FAIL);
5193
5194 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5195#if 1 /* Enable new VD container code (and new VMDK), as the bugs are fixed. */
5196 rc = CFGMR3InsertString(pLunL1, "Driver", "VD"); RC_CHECK();
5197#else
5198 rc = CFGMR3InsertString(pLunL1, "Driver", "VmdkHDD"); RC_CHECK();
5199#endif
5200 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5201 hrc = vmdkDisk->COMGETTER(FilePath)(&str); H();
5202 STR_CONV();
5203 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5204 STR_FREE();
5205 }
5206 else
5207 AssertFailed();
5208 }
5209 H();
5210
5211 ComPtr<IDVDDrive> dvdDrive;
5212 hrc = pMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam()); H();
5213 if (dvdDrive)
5214 {
5215 // ASSUME: DVD drive is always attached to LUN#2 (i.e. secondary IDE master)
5216 rc = CFGMR3InsertNode(pInst, "LUN#2", &pLunL0); RC_CHECK();
5217 ComPtr<IHostDVDDrive> hostDvdDrive;
5218 hrc = dvdDrive->GetHostDrive(hostDvdDrive.asOutParam()); H();
5219 if (hostDvdDrive)
5220 {
5221 pConsole->meDVDState = DriveState_HostDriveCaptured;
5222 rc = CFGMR3InsertString(pLunL0, "Driver", "HostDVD"); RC_CHECK();
5223 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5224 hrc = hostDvdDrive->COMGETTER(Name)(&str); H();
5225 STR_CONV();
5226 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5227 STR_FREE();
5228 BOOL fPassthrough;
5229 hrc = dvdDrive->COMGETTER(Passthrough)(&fPassthrough); H();
5230 rc = CFGMR3InsertInteger(pCfg, "Passthrough", !!fPassthrough); RC_CHECK();
5231 }
5232 else
5233 {
5234 pConsole->meDVDState = DriveState_NotMounted;
5235 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
5236 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5237 rc = CFGMR3InsertString(pCfg, "Type", "DVD"); RC_CHECK();
5238 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
5239
5240 ComPtr<IDVDImage> dvdImage;
5241 hrc = dvdDrive->GetImage(dvdImage.asOutParam()); H();
5242 if (dvdImage)
5243 {
5244 pConsole->meDVDState = DriveState_ImageMounted;
5245 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5246 rc = CFGMR3InsertString(pLunL1, "Driver", "MediaISO"); RC_CHECK();
5247 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5248 hrc = dvdImage->COMGETTER(FilePath)(&str); H();
5249 STR_CONV();
5250 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5251 STR_FREE();
5252 }
5253 }
5254 }
5255
5256 /*
5257 * Network adapters
5258 */
5259 rc = CFGMR3InsertNode(pDevices, "pcnet", &pDev); RC_CHECK();
5260 //rc = CFGMR3InsertNode(pDevices, "ne2000", &pDev); RC_CHECK();
5261 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::NetworkAdapterCount; ulInstance++)
5262 {
5263 ComPtr<INetworkAdapter> networkAdapter;
5264 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
5265 BOOL fEnabled = FALSE;
5266 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabled); H();
5267 if (!fEnabled)
5268 continue;
5269
5270 char szInstance[4]; Assert(ulInstance <= 999);
5271 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5272 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5273 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5274 /* the first network card gets the PCI ID 3, the followings starting from 8 */
5275 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", !ulInstance ? 3 : ulInstance - 1 + 8); RC_CHECK();
5276 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5277 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5278
5279 /*
5280 * The virtual hardware type.
5281 */
5282 NetworkAdapterType_T adapterType;
5283 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
5284 switch (adapterType)
5285 {
5286 case NetworkAdapterType_NetworkAdapterAm79C970A:
5287 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 0); RC_CHECK();
5288 break;
5289 case NetworkAdapterType_NetworkAdapterAm79C973:
5290 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 1); RC_CHECK();
5291 break;
5292 default:
5293 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
5294 adapterType, ulInstance));
5295 return VERR_GENERAL_FAILURE;
5296 }
5297
5298 /*
5299 * Get the MAC address and convert it to binary representation
5300 */
5301 Bstr macAddr;
5302 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
5303 Assert(macAddr);
5304 Utf8Str macAddrUtf8 = macAddr;
5305 char *macStr = (char*)macAddrUtf8.raw();
5306 Assert(strlen(macStr) == 12);
5307 PDMMAC Mac;
5308 memset(&Mac, 0, sizeof(Mac));
5309 char *pMac = (char*)&Mac;
5310 for (uint32_t i = 0; i < 6; i++)
5311 {
5312 char c1 = *macStr++ - '0';
5313 if (c1 > 9)
5314 c1 -= 7;
5315 char c2 = *macStr++ - '0';
5316 if (c2 > 9)
5317 c2 -= 7;
5318 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
5319 }
5320 rc = CFGMR3InsertBytes(pCfg, "MAC", &Mac, sizeof(Mac)); RC_CHECK();
5321
5322 /*
5323 * Check if the cable is supposed to be unplugged
5324 */
5325 BOOL fCableConnected;
5326 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
5327 rc = CFGMR3InsertInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0); RC_CHECK();
5328
5329 /*
5330 * Attach the status driver.
5331 */
5332 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5333 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5334 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5335 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapNetworkLeds[ulInstance]); RC_CHECK();
5336
5337 /*
5338 * Enable the packet sniffer if requested.
5339 */
5340 BOOL fSniffer;
5341 hrc = networkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
5342 if (fSniffer)
5343 {
5344 /* insert the sniffer filter driver. */
5345 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5346 rc = CFGMR3InsertString(pLunL0, "Driver", "NetSniffer"); RC_CHECK();
5347 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5348 hrc = networkAdapter->COMGETTER(TraceFile)(&str); H();
5349 if (str) /* check convention for indicating default file. */
5350 {
5351 STR_CONV();
5352 rc = CFGMR3InsertString(pCfg, "File", psz); RC_CHECK();
5353 STR_FREE();
5354 }
5355 }
5356
5357 NetworkAttachmentType_T networkAttachment;
5358 hrc = networkAdapter->COMGETTER(AttachmentType)(&networkAttachment); H();
5359 switch (networkAttachment)
5360 {
5361 case NetworkAttachmentType_NoNetworkAttachment:
5362 break;
5363
5364 case NetworkAttachmentType_NATNetworkAttachment:
5365 {
5366 if (fSniffer)
5367 {
5368 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5369 }
5370 else
5371 {
5372 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5373 }
5374 rc = CFGMR3InsertString(pLunL0, "Driver", "NAT"); RC_CHECK();
5375 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5376 /* (Port forwarding goes here.) */
5377 break;
5378 }
5379
5380 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
5381 {
5382 /*
5383 * Perform the attachment if required (don't return on error!)
5384 */
5385 hrc = pConsole->attachToHostInterface(networkAdapter);
5386 if (SUCCEEDED(hrc))
5387 {
5388#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5389 Assert (pConsole->maTapFD[ulInstance] >= 0);
5390 if (pConsole->maTapFD[ulInstance] >= 0)
5391 {
5392 if (fSniffer)
5393 {
5394 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5395 }
5396 else
5397 {
5398 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5399 }
5400 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5401 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5402 rc = CFGMR3InsertInteger(pCfg, "FileHandle", pConsole->maTapFD[ulInstance]); RC_CHECK();
5403 }
5404#elif defined(RT_OS_WINDOWS)
5405 if (fSniffer)
5406 {
5407 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5408 }
5409 else
5410 {
5411 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5412 }
5413 Bstr hostInterfaceName;
5414 hrc = networkAdapter->COMGETTER(HostInterface)(hostInterfaceName.asOutParam()); H();
5415 ComPtr<IHostNetworkInterfaceCollection> coll;
5416 hrc = host->COMGETTER(NetworkInterfaces)(coll.asOutParam()); H();
5417 ComPtr<IHostNetworkInterface> hostInterface;
5418 rc = coll->FindByName(hostInterfaceName, hostInterface.asOutParam());
5419 if (!SUCCEEDED(rc))
5420 {
5421 AssertMsgFailed(("Cannot get GUID for host interface '%ls'\n", hostInterfaceName));
5422 hrc = networkAdapter->Detach(); H();
5423 }
5424 else
5425 {
5426 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5427 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5428 rc = CFGMR3InsertString(pCfg, "HostInterfaceName", Utf8Str(hostInterfaceName)); RC_CHECK();
5429 Guid hostIFGuid;
5430 hrc = hostInterface->COMGETTER(Id)(hostIFGuid.asOutParam()); H();
5431 char szDriverGUID[256] = {0};
5432 /* add curly brackets */
5433 szDriverGUID[0] = '{';
5434 strcpy(szDriverGUID + 1, hostIFGuid.toString().raw());
5435 strcat(szDriverGUID, "}");
5436 rc = CFGMR3InsertBytes(pCfg, "GUID", szDriverGUID, sizeof(szDriverGUID)); RC_CHECK();
5437 }
5438#else
5439# error "Port me"
5440#endif
5441 }
5442 else
5443 {
5444 switch (hrc)
5445 {
5446#ifdef RT_OS_LINUX
5447 case VERR_ACCESS_DENIED:
5448 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5449 "Failed to open '/dev/net/tun' for read/write access. Please check the "
5450 "permissions of that node. Either do 'chmod 0666 /dev/net/tun' or "
5451 "change the group of that node and get member of that group. Make "
5452 "sure that these changes are permanently in particular if you are "
5453 "using udev"));
5454#endif /* RT_OS_LINUX */
5455 default:
5456 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
5457 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5458 "Failed to initialize Host Interface Networking"));
5459 }
5460 }
5461 break;
5462 }
5463
5464 case NetworkAttachmentType_InternalNetworkAttachment:
5465 {
5466 hrc = networkAdapter->COMGETTER(InternalNetwork)(&str); H();
5467 STR_CONV();
5468 if (psz && *psz)
5469 {
5470 if (fSniffer)
5471 {
5472 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5473 }
5474 else
5475 {
5476 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5477 }
5478 rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet"); RC_CHECK();
5479 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5480 rc = CFGMR3InsertString(pCfg, "Network", psz); RC_CHECK();
5481 }
5482 STR_FREE();
5483 break;
5484 }
5485
5486 default:
5487 AssertMsgFailed(("should not get here!\n"));
5488 break;
5489 }
5490 }
5491
5492 /*
5493 * Serial (UART) Ports
5494 */
5495 rc = CFGMR3InsertNode(pDevices, "serial", &pDev); RC_CHECK();
5496 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::SerialPortCount; ulInstance++)
5497 {
5498 ComPtr<ISerialPort> serialPort;
5499 hrc = pMachine->GetSerialPort (ulInstance, serialPort.asOutParam()); H();
5500 BOOL fEnabled = FALSE;
5501 if (serialPort)
5502 hrc = serialPort->COMGETTER(Enabled)(&fEnabled); H();
5503 if (!fEnabled)
5504 continue;
5505
5506 char szInstance[4]; Assert(ulInstance <= 999);
5507 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5508
5509 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5510 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5511
5512 ULONG uIRQ, uIOBase;
5513 Bstr pipe;
5514 BOOL fServer;
5515 hrc = serialPort->COMGETTER(IRQ)(&uIRQ); H();
5516 hrc = serialPort->COMGETTER(IOBase)(&uIOBase); H();
5517 hrc = serialPort->COMGETTER(Pipe)(pipe.asOutParam()); H();
5518 hrc = serialPort->COMGETTER(Server)(&fServer); H();
5519 rc = CFGMR3InsertInteger(pCfg, "IRQ", uIRQ); RC_CHECK();
5520 rc = CFGMR3InsertInteger(pCfg, "IOBase", uIOBase); RC_CHECK();
5521 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5522 rc = CFGMR3InsertString(pLunL0, "Driver", "Char"); RC_CHECK();
5523 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5524 rc = CFGMR3InsertString(pLunL1, "Driver", "NamedPipe"); RC_CHECK();
5525 rc = CFGMR3InsertNode(pLunL1, "Config", &pLunL2); RC_CHECK();
5526 rc = CFGMR3InsertString(pLunL2, "Location", Utf8Str(pipe)); RC_CHECK();
5527 rc = CFGMR3InsertInteger(pLunL2, "IsServer", fServer); RC_CHECK();
5528 }
5529
5530 /*
5531 * Parallel (LPT) Ports
5532 */
5533 rc = CFGMR3InsertNode(pDevices, "parallel", &pDev); RC_CHECK();
5534 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::ParallelPortCount; ulInstance++)
5535 {
5536 ComPtr<IParallelPort> parallelPort;
5537 hrc = pMachine->GetParallelPort (ulInstance, parallelPort.asOutParam()); H();
5538 BOOL fEnabled = FALSE;
5539 if (parallelPort)
5540 hrc = parallelPort->COMGETTER(Enabled)(&fEnabled); H();
5541 if (!fEnabled)
5542 continue;
5543
5544 char szInstance[4]; Assert(ulInstance <= 999);
5545 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5546
5547 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5548 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5549
5550 ULONG uIRQ, uIOBase;
5551 Bstr DevicePath;
5552 hrc = parallelPort->COMGETTER(IRQ)(&uIRQ); H();
5553 hrc = parallelPort->COMGETTER(IOBase)(&uIOBase); H();
5554 hrc = parallelPort->COMGETTER(DevicePath)(DevicePath.asOutParam()); H();
5555 rc = CFGMR3InsertInteger(pCfg, "IRQ", uIRQ); RC_CHECK();
5556 rc = CFGMR3InsertInteger(pCfg, "IOBase", uIOBase); RC_CHECK();
5557 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5558 rc = CFGMR3InsertString(pLunL0, "Driver", "HostParallel"); RC_CHECK();
5559 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5560 rc = CFGMR3InsertString(pLunL1, "DevicePath", Utf8Str(DevicePath)); RC_CHECK();
5561 }
5562
5563 /*
5564 * VMM Device
5565 */
5566 rc = CFGMR3InsertNode(pDevices, "VMMDev", &pDev); RC_CHECK();
5567 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5568 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5569 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5570 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 4); RC_CHECK();
5571 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5572
5573 /* the VMM device's Main driver */
5574 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5575 rc = CFGMR3InsertString(pLunL0, "Driver", "MainVMMDev"); RC_CHECK();
5576 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5577 VMMDev *pVMMDev = pConsole->mVMMDev;
5578 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pVMMDev); RC_CHECK();
5579
5580 /*
5581 * Audio Sniffer Device
5582 */
5583 rc = CFGMR3InsertNode(pDevices, "AudioSniffer", &pDev); RC_CHECK();
5584 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5585 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5586
5587 /* the Audio Sniffer device's Main driver */
5588 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5589 rc = CFGMR3InsertString(pLunL0, "Driver", "MainAudioSniffer"); RC_CHECK();
5590 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5591 AudioSniffer *pAudioSniffer = pConsole->mAudioSniffer;
5592 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pAudioSniffer); RC_CHECK();
5593
5594 /*
5595 * AC'97 ICH audio
5596 */
5597 ComPtr<IAudioAdapter> audioAdapter;
5598 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
5599 BOOL enabled = FALSE;
5600 if (audioAdapter)
5601 {
5602 hrc = audioAdapter->COMGETTER(Enabled)(&enabled); H();
5603 }
5604 if (enabled)
5605 {
5606 rc = CFGMR3InsertNode(pDevices, "ichac97", &pDev); /* ichac97 */
5607 rc = CFGMR3InsertNode(pDev, "0", &pInst);
5608 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5609 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 5); RC_CHECK();
5610 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5611 rc = CFGMR3InsertNode(pInst, "Config", &pCfg);
5612
5613 /* the Audio driver */
5614 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5615 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
5616 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5617 AudioDriverType_T audioDriver;
5618 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
5619 switch (audioDriver)
5620 {
5621 case AudioDriverType_NullAudioDriver:
5622 {
5623 rc = CFGMR3InsertString(pCfg, "AudioDriver", "null"); RC_CHECK();
5624 break;
5625 }
5626#ifdef RT_OS_WINDOWS
5627#ifdef VBOX_WITH_WINMM
5628 case AudioDriverType_WINMMAudioDriver:
5629 {
5630 rc = CFGMR3InsertString(pCfg, "AudioDriver", "winmm"); RC_CHECK();
5631 break;
5632 }
5633#endif
5634 case AudioDriverType_DSOUNDAudioDriver:
5635 {
5636 rc = CFGMR3InsertString(pCfg, "AudioDriver", "dsound"); RC_CHECK();
5637 break;
5638 }
5639#endif /* RT_OS_WINDOWS */
5640#ifdef RT_OS_LINUX
5641 case AudioDriverType_OSSAudioDriver:
5642 {
5643 rc = CFGMR3InsertString(pCfg, "AudioDriver", "oss"); RC_CHECK();
5644 break;
5645 }
5646# ifdef VBOX_WITH_ALSA
5647 case AudioDriverType_ALSAAudioDriver:
5648 {
5649 rc = CFGMR3InsertString(pCfg, "AudioDriver", "alsa"); RC_CHECK();
5650 break;
5651 }
5652# endif
5653#endif /* RT_OS_LINUX */
5654#ifdef RT_OS_DARWIN
5655 case AudioDriverType_CoreAudioDriver:
5656 {
5657 rc = CFGMR3InsertString(pCfg, "AudioDriver", "coreaudio"); RC_CHECK();
5658 break;
5659 }
5660#endif
5661 }
5662 }
5663
5664 /*
5665 * The USB Controller.
5666 */
5667 ComPtr<IUSBController> USBCtlPtr;
5668 hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
5669 if (USBCtlPtr)
5670 {
5671 BOOL fEnabled;
5672 hrc = USBCtlPtr->COMGETTER(Enabled)(&fEnabled); H();
5673 if (fEnabled)
5674 {
5675 rc = CFGMR3InsertNode(pDevices, "usb-ohci", &pDev); RC_CHECK();
5676 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5677 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5678 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5679 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 6); RC_CHECK();
5680 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5681
5682 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5683 rc = CFGMR3InsertString(pLunL0, "Driver", "VUSBRootHub"); RC_CHECK();
5684 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5685 }
5686 }
5687
5688 /*
5689 * Clipboard
5690 */
5691 {
5692 ClipboardMode_T mode = ClipboardMode_ClipDisabled;
5693 hrc = pMachine->COMGETTER(ClipboardMode) (&mode); H();
5694
5695 if (mode != ClipboardMode_ClipDisabled)
5696 {
5697 /* Load the service */
5698 rc = pConsole->mVMMDev->hgcmLoadService ("VBoxSharedClipboard", "VBoxSharedClipboard");
5699
5700 if (VBOX_FAILURE (rc))
5701 {
5702 LogRel(("VBoxSharedClipboard is not available. rc = %Vrc\n", rc));
5703 /* That is not a fatal failure. */
5704 rc = VINF_SUCCESS;
5705 }
5706 else
5707 {
5708 /* Setup the service. */
5709 VBOXHGCMSVCPARM parm;
5710
5711 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
5712
5713 switch (mode)
5714 {
5715 default:
5716 case ClipboardMode_ClipDisabled:
5717 {
5718 LogRel(("VBoxSharedClipboard mode: Off\n"));
5719 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
5720 break;
5721 }
5722 case ClipboardMode_ClipGuestToHost:
5723 {
5724 LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
5725 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
5726 break;
5727 }
5728 case ClipboardMode_ClipHostToGuest:
5729 {
5730 LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
5731 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
5732 break;
5733 }
5734 case ClipboardMode_ClipBidirectional:
5735 {
5736 LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
5737 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
5738 break;
5739 }
5740 }
5741
5742 pConsole->mVMMDev->hgcmHostCall ("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
5743
5744 Log(("Set VBoxSharedClipboard mode\n"));
5745 }
5746 }
5747 }
5748
5749 /*
5750 * CFGM overlay handling.
5751 *
5752 * Here we check the extra data entries for CFGM values
5753 * and create the nodes and insert the values on the fly. Existing
5754 * values will be removed and reinserted. If a value is a valid number,
5755 * it will be inserted as a number, otherwise as a string.
5756 *
5757 * We first perform a run on global extra data, then on the machine
5758 * extra data to support global settings with local overrides.
5759 *
5760 */
5761 Bstr strExtraDataKey;
5762 bool fGlobalExtraData = true;
5763 for (;;)
5764 {
5765 Bstr strNextExtraDataKey;
5766 Bstr strExtraDataValue;
5767
5768 /* get the next key */
5769 if (fGlobalExtraData)
5770 hrc = virtualBox->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5771 strExtraDataValue.asOutParam());
5772 else
5773 hrc = pMachine->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5774 strExtraDataValue.asOutParam());
5775
5776 /* stop if for some reason there's nothing more to request */
5777 if (FAILED(hrc) || !strNextExtraDataKey)
5778 {
5779 /* if we're out of global keys, continue with machine, otherwise we're done */
5780 if (fGlobalExtraData)
5781 {
5782 fGlobalExtraData = false;
5783 strExtraDataKey.setNull();
5784 continue;
5785 }
5786 break;
5787 }
5788
5789 strExtraDataKey = strNextExtraDataKey;
5790 Utf8Str strExtraDataKeyUtf8 = Utf8Str(strExtraDataKey);
5791
5792 /* we only care about keys starting with "VBoxInternal/" */
5793 if (strncmp(strExtraDataKeyUtf8.raw(), "VBoxInternal/", 13) != 0)
5794 continue;
5795 char *pszExtraDataKey = (char*)strExtraDataKeyUtf8.raw() + 13;
5796
5797 /* the key will be in the format "Node1/Node2/Value" or simply "Value". */
5798 PCFGMNODE pNode;
5799 char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
5800 if (pszCFGMValueName)
5801 {
5802 /* terminate the node and advance to the value */
5803 *pszCFGMValueName = '\0';
5804 pszCFGMValueName++;
5805
5806 /* does the node already exist? */
5807 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
5808 if (pNode)
5809 {
5810 /* the value might already exist, remove it to be safe */
5811 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5812 }
5813 else
5814 {
5815 /* create the node */
5816 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
5817 AssertMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
5818 if (VBOX_FAILURE(rc) || !pNode)
5819 continue;
5820 }
5821 }
5822 else
5823 {
5824 pNode = pRoot;
5825 pszCFGMValueName = pszExtraDataKey;
5826 pszExtraDataKey--;
5827
5828 /* the value might already exist, remove it to be safe */
5829 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5830 }
5831
5832 /* now let's have a look at the value */
5833 Utf8Str strCFGMValueUtf8 = Utf8Str(strExtraDataValue);
5834 const char *pszCFGMValue = strCFGMValueUtf8.raw();
5835 /* empty value means remove value which we've already done */
5836 if (pszCFGMValue && *pszCFGMValue)
5837 {
5838 /* if it's a valid number, we'll insert it as such, otherwise string */
5839 uint64_t u64Value;
5840 if (RTStrToUInt64Ex(pszCFGMValue, NULL, 0, &u64Value) == VINF_SUCCESS)
5841 {
5842 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
5843 }
5844 else
5845 {
5846 rc = CFGMR3InsertString(pNode, pszCFGMValueName, pszCFGMValue);
5847 }
5848 AssertMsgRC(rc, ("failed to insert CFGM value '%s' to key '%s'\n", pszCFGMValue, pszExtraDataKey));
5849 }
5850 }
5851
5852#undef H
5853#undef RC_CHECK
5854#undef STR_FREE
5855#undef STR_CONV
5856
5857 /* Register VM state change handler */
5858 int rc2 = VMR3AtStateRegister (pVM, Console::vmstateChangeCallback, pConsole);
5859 AssertRC (rc2);
5860 if (VBOX_SUCCESS (rc))
5861 rc = rc2;
5862
5863 /* Register VM runtime error handler */
5864 rc2 = VMR3AtRuntimeErrorRegister (pVM, Console::setVMRuntimeErrorCallback, pConsole);
5865 AssertRC (rc2);
5866 if (VBOX_SUCCESS (rc))
5867 rc = rc2;
5868
5869 /* Save the VM pointer in the machine object */
5870 pConsole->mpVM = pVM;
5871
5872 LogFlowFunc (("vrc = %Vrc\n", rc));
5873 LogFlowFuncLeave();
5874
5875 return rc;
5876}
5877
5878/**
5879 * Call the initialisation script for a dynamic TAP interface.
5880 *
5881 * The initialisation script should create a TAP interface, set it up and write its name to
5882 * standard output followed by a carriage return. Anything further written to standard
5883 * output will be ignored. If it returns a non-zero exit code, or does not write an
5884 * intelligable interface name to standard output, it will be treated as having failed.
5885 * For now, this method only works on Linux.
5886 *
5887 * @returns COM status code
5888 * @param tapDevice string to store the name of the tap device created to
5889 * @param tapSetupApplication the name of the setup script
5890 */
5891HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5892 Bstr &tapSetupApplication)
5893{
5894 LogFlowThisFunc(("\n"));
5895#ifdef RT_OS_LINUX
5896 /* Command line to start the script with. */
5897 char szCommand[4096];
5898 /* Result code */
5899 int rc;
5900
5901 /* Get the script name. */
5902 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5903 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5904 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5905 /*
5906 * Create the process and read its output.
5907 */
5908 Log2(("About to start the TAP setup script with the following command line: %s\n",
5909 szCommand));
5910 FILE *pfScriptHandle = popen(szCommand, "r");
5911 if (pfScriptHandle == 0)
5912 {
5913 int iErr = errno;
5914 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5915 szCommand, strerror(iErr)));
5916 LogFlowThisFunc(("rc=E_FAIL\n"));
5917 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5918 szCommand, strerror(iErr));
5919 }
5920 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5921 if (!isStatic)
5922 {
5923 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5924 interested in the first few (normally 5 or 6) bytes. */
5925 char acBuffer[64];
5926 /* The length of the string returned by the application. We only accept strings of 63
5927 characters or less. */
5928 size_t cBufSize;
5929
5930 /* Read the name of the device from the application. */
5931 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5932 cBufSize = strlen(acBuffer);
5933 /* The script must return the name of the interface followed by a carriage return as the
5934 first line of its output. We need a null-terminated string. */
5935 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5936 {
5937 pclose(pfScriptHandle);
5938 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5939 LogFlowThisFunc(("rc=E_FAIL\n"));
5940 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5941 }
5942 /* Overwrite the terminating newline character. */
5943 acBuffer[cBufSize - 1] = 0;
5944 tapDevice = acBuffer;
5945 }
5946 rc = pclose(pfScriptHandle);
5947 if (!WIFEXITED(rc))
5948 {
5949 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5950 LogFlowThisFunc(("rc=E_FAIL\n"));
5951 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5952 }
5953 if (WEXITSTATUS(rc) != 0)
5954 {
5955 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5956 LogFlowThisFunc(("rc=E_FAIL\n"));
5957 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5958 }
5959 LogFlowThisFunc(("rc=S_OK\n"));
5960 return S_OK;
5961#else /* RT_OS_LINUX not defined */
5962 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5963 return E_NOTIMPL; /* not yet supported */
5964#endif
5965}
5966
5967/**
5968 * Helper function to handle host interface device creation and attachment.
5969 *
5970 * @param networkAdapter the network adapter which attachment should be reset
5971 * @return COM status code
5972 *
5973 * @note The caller must lock this object for writing.
5974 */
5975HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5976{
5977 LogFlowThisFunc(("\n"));
5978 /* sanity check */
5979 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5980
5981#ifdef DEBUG
5982 /* paranoia */
5983 NetworkAttachmentType_T attachment;
5984 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5985 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5986#endif /* DEBUG */
5987
5988 HRESULT rc = S_OK;
5989
5990#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5991 ULONG slot = 0;
5992 rc = networkAdapter->COMGETTER(Slot)(&slot);
5993 AssertComRC(rc);
5994
5995 /*
5996 * Try get the FD.
5997 */
5998 LONG ltapFD;
5999 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
6000 if (SUCCEEDED(rc))
6001 maTapFD[slot] = (RTFILE)ltapFD;
6002 else
6003 maTapFD[slot] = NIL_RTFILE;
6004
6005 /*
6006 * Are we supposed to use an existing TAP interface?
6007 */
6008 if (maTapFD[slot] != NIL_RTFILE)
6009 {
6010 /* nothing to do */
6011 Assert(ltapFD >= 0);
6012 Assert((LONG)maTapFD[slot] == ltapFD);
6013 rc = S_OK;
6014 }
6015 else
6016#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
6017 {
6018 /*
6019 * Allocate a host interface device
6020 */
6021#ifdef RT_OS_WINDOWS
6022 /* nothing to do */
6023 int rcVBox = VINF_SUCCESS;
6024#elif defined(RT_OS_LINUX)
6025 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
6026 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
6027 if (VBOX_SUCCESS(rcVBox))
6028 {
6029 /*
6030 * Set/obtain the tap interface.
6031 */
6032 bool isStatic = false;
6033 struct ifreq IfReq;
6034 memset(&IfReq, 0, sizeof(IfReq));
6035 /* The name of the TAP interface we are using and the TAP setup script resp. */
6036 Bstr tapDeviceName, tapSetupApplication;
6037 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6038 if (FAILED(rc))
6039 {
6040 tapDeviceName.setNull(); /* Is this necessary? */
6041 }
6042 else if (!tapDeviceName.isEmpty())
6043 {
6044 isStatic = true;
6045 /* If we are using a static TAP device then try to open it. */
6046 Utf8Str str(tapDeviceName);
6047 if (str.length() <= sizeof(IfReq.ifr_name))
6048 strcpy(IfReq.ifr_name, str.raw());
6049 else
6050 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
6051 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
6052 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
6053 if (rcVBox != 0)
6054 {
6055 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
6056 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
6057 tapDeviceName.raw());
6058 }
6059 }
6060 if (SUCCEEDED(rc))
6061 {
6062 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
6063 if (tapSetupApplication.isEmpty())
6064 {
6065 if (tapDeviceName.isEmpty())
6066 {
6067 LogRel(("No setup application was supplied for the TAP interface.\n"));
6068 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
6069 }
6070 }
6071 else
6072 {
6073 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
6074 tapSetupApplication);
6075 }
6076 }
6077 if (SUCCEEDED(rc))
6078 {
6079 if (!isStatic)
6080 {
6081 Utf8Str str(tapDeviceName);
6082 if (str.length() <= sizeof(IfReq.ifr_name))
6083 strcpy(IfReq.ifr_name, str.raw());
6084 else
6085 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
6086 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
6087 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
6088 if (rcVBox != 0)
6089 {
6090 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
6091 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
6092 }
6093 }
6094 if (SUCCEEDED(rc))
6095 {
6096 /*
6097 * Make it pollable.
6098 */
6099 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
6100 {
6101 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
6102
6103 /*
6104 * Here is the right place to communicate the TAP file descriptor and
6105 * the host interface name to the server if/when it becomes really
6106 * necessary.
6107 */
6108 maTAPDeviceName[slot] = tapDeviceName;
6109 rcVBox = VINF_SUCCESS;
6110 }
6111 else
6112 {
6113 int iErr = errno;
6114
6115 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
6116 rcVBox = VERR_HOSTIF_BLOCKING;
6117 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
6118 strerror(errno));
6119 }
6120 }
6121 }
6122 }
6123 else
6124 {
6125 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
6126 switch (rcVBox)
6127 {
6128 case VERR_ACCESS_DENIED:
6129 /* will be handled by our caller */
6130 rc = rcVBox;
6131 break;
6132 default:
6133 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
6134 break;
6135 }
6136 }
6137#elif defined(RT_OS_DARWIN)
6138 /** @todo Implement tap networking for Darwin. */
6139 int rcVBox = VERR_NOT_IMPLEMENTED;
6140#elif defined(RT_OS_OS2)
6141 /** @todo Implement tap networking for OS/2. */
6142 int rcVBox = VERR_NOT_IMPLEMENTED;
6143#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
6144# error "PORTME: Implement OS specific TAP interface open/creation."
6145#else
6146# error "Unknown host OS"
6147#endif
6148 /* in case of failure, cleanup. */
6149 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
6150 {
6151 LogRel(("General failure attaching to host interface\n"));
6152 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
6153 }
6154 }
6155 LogFlowThisFunc(("rc=%d\n", rc));
6156 return rc;
6157}
6158
6159/**
6160 * Helper function to handle detachment from a host interface
6161 *
6162 * @param networkAdapter the network adapter which attachment should be reset
6163 * @return COM status code
6164 *
6165 * @note The caller must lock this object for writing.
6166 */
6167HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
6168{
6169 /* sanity check */
6170 LogFlowThisFunc(("\n"));
6171 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
6172
6173 HRESULT rc = S_OK;
6174#ifdef DEBUG
6175 /* paranoia */
6176 NetworkAttachmentType_T attachment;
6177 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6178 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
6179#endif /* DEBUG */
6180
6181#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
6182
6183 ULONG slot = 0;
6184 rc = networkAdapter->COMGETTER(Slot)(&slot);
6185 AssertComRC(rc);
6186
6187 /* is there an open TAP device? */
6188 if (maTapFD[slot] != NIL_RTFILE)
6189 {
6190 /*
6191 * Close the file handle.
6192 */
6193 Bstr tapDeviceName, tapTerminateApplication;
6194 bool isStatic = true;
6195 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6196 if (FAILED(rc) || tapDeviceName.isEmpty())
6197 {
6198 /* If the name is not empty, this is a dynamic TAP device, so close it now,
6199 so that the termination script can remove the interface. Otherwise we still
6200 need the FD to pass to the termination script. */
6201 isStatic = false;
6202 int rcVBox = RTFileClose(maTapFD[slot]);
6203 AssertRC(rcVBox);
6204 maTapFD[slot] = NIL_RTFILE;
6205 }
6206 /*
6207 * Execute the termination command.
6208 */
6209 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
6210 if (tapTerminateApplication)
6211 {
6212 /* Get the program name. */
6213 Utf8Str tapTermAppUtf8(tapTerminateApplication);
6214
6215 /* Build the command line. */
6216 char szCommand[4096];
6217 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
6218 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
6219
6220 /*
6221 * Create the process and wait for it to complete.
6222 */
6223 Log(("Calling the termination command: %s\n", szCommand));
6224 int rcCommand = system(szCommand);
6225 if (rcCommand == -1)
6226 {
6227 LogRel(("Failed to execute the clean up script for the TAP interface"));
6228 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
6229 }
6230 if (!WIFEXITED(rc))
6231 {
6232 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
6233 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
6234 }
6235 if (WEXITSTATUS(rc) != 0)
6236 {
6237 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
6238 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
6239 }
6240 }
6241
6242 if (isStatic)
6243 {
6244 /* If we are using a static TAP device, we close it now, after having called the
6245 termination script. */
6246 int rcVBox = RTFileClose(maTapFD[slot]);
6247 AssertRC(rcVBox);
6248 }
6249 /* the TAP device name and handle are no longer valid */
6250 maTapFD[slot] = NIL_RTFILE;
6251 maTAPDeviceName[slot] = "";
6252 }
6253#endif
6254 LogFlowThisFunc(("returning %d\n", rc));
6255 return rc;
6256}
6257
6258
6259/**
6260 * Called at power down to terminate host interface networking.
6261 *
6262 * @note The caller must lock this object for writing.
6263 */
6264HRESULT Console::powerDownHostInterfaces()
6265{
6266 LogFlowThisFunc (("\n"));
6267
6268 /* sanity check */
6269 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
6270
6271 /*
6272 * host interface termination handling
6273 */
6274 HRESULT rc;
6275 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
6276 {
6277 ComPtr<INetworkAdapter> networkAdapter;
6278 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
6279 CheckComRCBreakRC (rc);
6280
6281 BOOL enabled = FALSE;
6282 networkAdapter->COMGETTER(Enabled) (&enabled);
6283 if (!enabled)
6284 continue;
6285
6286 NetworkAttachmentType_T attachment;
6287 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6288 if (attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment)
6289 {
6290 HRESULT rc2 = detachFromHostInterface(networkAdapter);
6291 if (FAILED(rc2) && SUCCEEDED(rc))
6292 rc = rc2;
6293 }
6294 }
6295
6296 return rc;
6297}
6298
6299
6300/**
6301 * Process callback handler for VMR3Load and VMR3Save.
6302 *
6303 * @param pVM The VM handle.
6304 * @param uPercent Completetion precentage (0-100).
6305 * @param pvUser Pointer to the VMProgressTask structure.
6306 * @return VINF_SUCCESS.
6307 */
6308/*static*/ DECLCALLBACK (int)
6309Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
6310{
6311 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6312 AssertReturn (task, VERR_INVALID_PARAMETER);
6313
6314 /* update the progress object */
6315 if (task->mProgress)
6316 task->mProgress->notifyProgress (uPercent);
6317
6318 return VINF_SUCCESS;
6319}
6320
6321/**
6322 * VM error callback function. Called by the various VM components.
6323 *
6324 * @param pVM The VM handle. Can be NULL if an error occurred before
6325 * successfully creating a VM.
6326 * @param pvUser Pointer to the VMProgressTask structure.
6327 * @param rc VBox status code.
6328 * @param pszFormat The error message.
6329 * @thread EMT.
6330 */
6331/* static */ DECLCALLBACK (void)
6332Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
6333 const char *pszFormat, va_list args)
6334{
6335 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6336 AssertReturnVoid (task);
6337
6338 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
6339 HRESULT hrc = setError (E_FAIL, tr ("%N.\n"
6340 "VBox status code: %d (%Vrc)"),
6341 tr (pszFormat), &args,
6342 rc, rc);
6343 task->mProgress->notifyComplete (hrc);
6344}
6345
6346/**
6347 * VM runtime error callback function.
6348 * See VMSetRuntimeError for the detailed description of parameters.
6349 *
6350 * @param pVM The VM handle.
6351 * @param pvUser The user argument.
6352 * @param fFatal Whether it is a fatal error or not.
6353 * @param pszErrorID Error ID string.
6354 * @param pszFormat Error message format string.
6355 * @param args Error message arguments.
6356 * @thread EMT.
6357 */
6358/* static */ DECLCALLBACK(void)
6359Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
6360 const char *pszErrorID,
6361 const char *pszFormat, va_list args)
6362{
6363 LogFlowFuncEnter();
6364
6365 Console *that = static_cast <Console *> (pvUser);
6366 AssertReturnVoid (that);
6367
6368 Utf8Str message = Utf8StrFmt (pszFormat, args);
6369
6370 LogRel (("Console: VM runtime error: fatal=%RTbool, "
6371 "errorID=%s message=\"%s\"\n",
6372 fFatal, pszErrorID, message.raw()));
6373
6374 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
6375
6376 LogFlowFuncLeave();
6377}
6378
6379/**
6380 * Captures USB devices that match filters of the VM.
6381 * Called at VM startup.
6382 *
6383 * @param pVM The VM handle.
6384 *
6385 * @note The caller must lock this object for writing.
6386 */
6387HRESULT Console::captureUSBDevices (PVM pVM)
6388{
6389 LogFlowThisFunc (("\n"));
6390
6391 /* sanity check */
6392 ComAssertRet (isLockedOnCurrentThread(), E_FAIL);
6393
6394 /* If the machine has an USB controller, ask the USB proxy service to
6395 * capture devices */
6396 PPDMIBASE pBase;
6397 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
6398 if (VBOX_SUCCESS (vrc))
6399 {
6400 /* leave the lock before calling Host in VBoxSVC since Host may call
6401 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6402 * produce an inter-process dead-lock otherwise. */
6403 AutoLock alock (this);
6404 alock.leave();
6405
6406 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6407 ComAssertComRCRetRC (hrc);
6408 }
6409 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6410 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6411 vrc = VINF_SUCCESS;
6412 else
6413 AssertRC (vrc);
6414
6415 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
6416}
6417
6418
6419/**
6420 * Detach all USB device which are attached to the VM for the
6421 * purpose of clean up and such like.
6422 *
6423 * @note The caller must lock this object for writing.
6424 */
6425void Console::detachAllUSBDevices (bool aDone)
6426{
6427 LogFlowThisFunc (("\n"));
6428
6429 /* sanity check */
6430 AssertReturnVoid (isLockedOnCurrentThread());
6431
6432 mUSBDevices.clear();
6433
6434 /* leave the lock before calling Host in VBoxSVC since Host may call
6435 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6436 * produce an inter-process dead-lock otherwise. */
6437 AutoLock alock (this);
6438 alock.leave();
6439
6440 mControl->DetachAllUSBDevices (aDone);
6441}
6442
6443/**
6444 * @note Locks this object for writing.
6445 */
6446void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6447{
6448 LogFlowThisFuncEnter();
6449 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6450
6451 AutoCaller autoCaller (this);
6452 if (!autoCaller.isOk())
6453 {
6454 /* Console has been already uninitialized, deny request */
6455 AssertMsgFailed (("Temporary assertion to prove that it happens, "
6456 "please report to dmik\n"));
6457 LogFlowThisFunc (("Console is already uninitialized\n"));
6458 LogFlowThisFuncLeave();
6459 return;
6460 }
6461
6462 AutoLock alock (this);
6463
6464 /*
6465 * Mark all existing remote USB devices as dirty.
6466 */
6467 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6468 while (it != mRemoteUSBDevices.end())
6469 {
6470 (*it)->dirty (true);
6471 ++ it;
6472 }
6473
6474 /*
6475 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6476 */
6477 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6478 VRDPUSBDEVICEDESC *e = pDevList;
6479
6480 /* The cbDevList condition must be checked first, because the function can
6481 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6482 */
6483 while (cbDevList >= 2 && e->oNext)
6484 {
6485 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6486 e->idVendor, e->idProduct,
6487 e->oProduct? (char *)e + e->oProduct: ""));
6488
6489 bool fNewDevice = true;
6490
6491 it = mRemoteUSBDevices.begin();
6492 while (it != mRemoteUSBDevices.end())
6493 {
6494 if ((*it)->devId () == e->id
6495 && (*it)->clientId () == u32ClientId)
6496 {
6497 /* The device is already in the list. */
6498 (*it)->dirty (false);
6499 fNewDevice = false;
6500 break;
6501 }
6502
6503 ++ it;
6504 }
6505
6506 if (fNewDevice)
6507 {
6508 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6509 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6510 ));
6511
6512 /* Create the device object and add the new device to list. */
6513 ComObjPtr <RemoteUSBDevice> device;
6514 device.createObject();
6515 device->init (u32ClientId, e);
6516
6517 mRemoteUSBDevices.push_back (device);
6518
6519 /* Check if the device is ok for current USB filters. */
6520 BOOL fMatched = FALSE;
6521
6522 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched);
6523
6524 AssertComRC (hrc);
6525
6526 LogFlowThisFunc (("USB filters return %d\n", fMatched));
6527
6528 if (fMatched)
6529 {
6530 hrc = onUSBDeviceAttach (device, NULL);
6531
6532 /// @todo (r=dmik) warning reporting subsystem
6533
6534 if (hrc == S_OK)
6535 {
6536 LogFlowThisFunc (("Device attached\n"));
6537 device->captured (true);
6538 }
6539 }
6540 }
6541
6542 if (cbDevList < e->oNext)
6543 {
6544 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6545 cbDevList, e->oNext));
6546 break;
6547 }
6548
6549 cbDevList -= e->oNext;
6550
6551 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6552 }
6553
6554 /*
6555 * Remove dirty devices, that is those which are not reported by the server anymore.
6556 */
6557 for (;;)
6558 {
6559 ComObjPtr <RemoteUSBDevice> device;
6560
6561 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6562 while (it != mRemoteUSBDevices.end())
6563 {
6564 if ((*it)->dirty ())
6565 {
6566 device = *it;
6567 break;
6568 }
6569
6570 ++ it;
6571 }
6572
6573 if (!device)
6574 {
6575 break;
6576 }
6577
6578 USHORT vendorId = 0;
6579 device->COMGETTER(VendorId) (&vendorId);
6580
6581 USHORT productId = 0;
6582 device->COMGETTER(ProductId) (&productId);
6583
6584 Bstr product;
6585 device->COMGETTER(Product) (product.asOutParam());
6586
6587 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6588 vendorId, productId, product.raw ()
6589 ));
6590
6591 /* Detach the device from VM. */
6592 if (device->captured ())
6593 {
6594 Guid uuid;
6595 device->COMGETTER (Id) (uuid.asOutParam());
6596 onUSBDeviceDetach (uuid, NULL);
6597 }
6598
6599 /* And remove it from the list. */
6600 mRemoteUSBDevices.erase (it);
6601 }
6602
6603 LogFlowThisFuncLeave();
6604}
6605
6606
6607
6608/**
6609 * Thread function which starts the VM (also from saved state) and
6610 * track progress.
6611 *
6612 * @param Thread The thread id.
6613 * @param pvUser Pointer to a VMPowerUpTask structure.
6614 * @return VINF_SUCCESS (ignored).
6615 *
6616 * @note Locks the Console object for writing.
6617 */
6618/*static*/
6619DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6620{
6621 LogFlowFuncEnter();
6622
6623 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6624 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6625
6626 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6627 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6628
6629#if defined(RT_OS_WINDOWS)
6630 {
6631 /* initialize COM */
6632 HRESULT hrc = CoInitializeEx (NULL,
6633 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6634 COINIT_SPEED_OVER_MEMORY);
6635 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6636 }
6637#endif
6638
6639 HRESULT hrc = S_OK;
6640 int vrc = VINF_SUCCESS;
6641
6642 ComObjPtr <Console> console = task->mConsole;
6643
6644 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6645
6646 AutoLock alock (console);
6647
6648 /* sanity */
6649 Assert (console->mpVM == NULL);
6650
6651 do
6652 {
6653 /*
6654 * Initialize the release logging facility. In case something
6655 * goes wrong, there will be no release logging. Maybe in the future
6656 * we can add some logic to use different file names in this case.
6657 * Note that the logic must be in sync with Machine::DeleteSettings().
6658 */
6659
6660 Bstr logFolder;
6661 hrc = console->mMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
6662 CheckComRCBreakRC (hrc);
6663
6664 Utf8Str logDir = logFolder;
6665
6666 /* make sure the Logs folder exists */
6667 Assert (!logDir.isEmpty());
6668 if (!RTDirExists (logDir))
6669 RTDirCreateFullPath (logDir, 0777);
6670
6671 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
6672 logDir.raw(), RTPATH_DELIMITER);
6673
6674 /*
6675 * Age the old log files
6676 * Rename .2 to .3, .1 to .2 and the last log file to .1
6677 * Overwrite target files in case they exist;
6678 */
6679 for (int i = 2; i >= 0; i--)
6680 {
6681 Utf8Str oldName;
6682 if (i > 0)
6683 oldName = Utf8StrFmt ("%s.%d", logFile.raw(), i);
6684 else
6685 oldName = logFile;
6686 Utf8Str newName = Utf8StrFmt ("%s.%d", logFile.raw(), i + 1);
6687 RTFileRename(oldName.raw(), newName.raw(), RTFILEMOVE_FLAGS_REPLACE);
6688 }
6689
6690 PRTLOGGER loggerRelease;
6691 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
6692 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
6693#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
6694 fFlags |= RTLOGFLAGS_USECRLF;
6695#endif
6696 char szError[RTPATH_MAX + 128] = "";
6697 vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
6698 "VBOX_RELEASE_LOG", ELEMENTS(s_apszGroups), s_apszGroups,
6699 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
6700 if (VBOX_SUCCESS(vrc))
6701 {
6702 /* some introductory information */
6703 RTTIMESPEC timeSpec;
6704 char nowUct[64];
6705 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
6706 RTLogRelLogger(loggerRelease, 0, ~0U,
6707 "VirtualBox %s r%d (%s %s) release log\n"
6708 "Log opened %s\n",
6709 VBOX_VERSION_STRING, VBOX_SVN_REV, __DATE__, __TIME__,
6710 nowUct);
6711
6712 /* register this logger as the release logger */
6713 RTLogRelSetDefaultInstance(loggerRelease);
6714 }
6715 else
6716 {
6717 hrc = setError (E_FAIL,
6718 tr ("Failed to open release log (%s, %Vrc)"), szError, vrc);
6719 break;
6720 }
6721
6722#ifdef VBOX_VRDP
6723 if (VBOX_SUCCESS (vrc))
6724 {
6725 /* Create the VRDP server. In case of headless operation, this will
6726 * also create the framebuffer, required at VM creation.
6727 */
6728 ConsoleVRDPServer *server = console->consoleVRDPServer();
6729 Assert (server);
6730 /// @todo (dmik)
6731 // does VRDP server call Console from the other thread?
6732 // Not sure, so leave the lock just in case
6733 alock.leave();
6734 vrc = server->Launch();
6735 alock.enter();
6736 if (VBOX_FAILURE (vrc))
6737 {
6738 Utf8Str errMsg;
6739 switch (vrc)
6740 {
6741 case VERR_NET_ADDRESS_IN_USE:
6742 {
6743 ULONG port = 0;
6744 console->mVRDPServer->COMGETTER(Port) (&port);
6745 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6746 port);
6747 break;
6748 }
6749 default:
6750 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6751 vrc);
6752 }
6753 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6754 vrc, errMsg.raw()));
6755 hrc = setError (E_FAIL, errMsg);
6756 break;
6757 }
6758 }
6759#endif /* VBOX_VRDP */
6760
6761 /*
6762 * Create the VM
6763 */
6764 PVM pVM;
6765 /*
6766 * leave the lock since EMT will call Console. It's safe because
6767 * mMachineState is either Starting or Restoring state here.
6768 */
6769 alock.leave();
6770
6771 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6772 task->mConfigConstructor, task.get(),
6773 &pVM);
6774
6775 alock.enter();
6776
6777#ifdef VBOX_VRDP
6778 {
6779 /* Enable client connections to the server. */
6780 ConsoleVRDPServer *server = console->consoleVRDPServer();
6781#ifdef VRDP_NO_COM
6782 server->EnableConnections ();
6783#else
6784 server->SetCallback ();
6785#endif /* VRDP_NO_COM */
6786 }
6787#endif /* VBOX_VRDP */
6788
6789 if (VBOX_SUCCESS (vrc))
6790 {
6791 do
6792 {
6793 /*
6794 * Register our load/save state file handlers
6795 */
6796 vrc = SSMR3RegisterExternal (pVM,
6797 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6798 0 /* cbGuess */,
6799 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6800 static_cast <Console *> (console));
6801 AssertRC (vrc);
6802 if (VBOX_FAILURE (vrc))
6803 break;
6804
6805 /*
6806 * Synchronize debugger settings
6807 */
6808 MachineDebugger *machineDebugger = console->getMachineDebugger();
6809 if (machineDebugger)
6810 {
6811 machineDebugger->flushQueuedSettings();
6812 }
6813
6814 if (console->getVMMDev()->isShFlActive())
6815 {
6816 /// @todo (dmik)
6817 // does the code below call Console from the other thread?
6818 // Not sure, so leave the lock just in case
6819 alock.leave();
6820
6821 /*
6822 * Shared Folders
6823 */
6824 for (std::map <Bstr, ComPtr <ISharedFolder> >::const_iterator
6825 it = task->mSharedFolders.begin();
6826 it != task->mSharedFolders.end();
6827 ++ it)
6828 {
6829 Bstr name = (*it).first;
6830 ComPtr <ISharedFolder> folder = (*it).second;
6831
6832 Bstr hostPath;
6833 hrc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
6834 CheckComRCBreakRC (hrc);
6835
6836 LogFlowFunc (("Adding shared folder '%ls' -> '%ls'\n",
6837 name.raw(), hostPath.raw()));
6838 ComAssertBreak (!name.isEmpty() && !hostPath.isEmpty(),
6839 hrc = E_FAIL);
6840
6841 /** @todo should move this into the shared folder class */
6842 VBOXHGCMSVCPARM parms[2];
6843 SHFLSTRING *pFolderName, *pMapName;
6844 int cbString;
6845
6846 cbString = (hostPath.length() + 1) * sizeof(RTUCS2);
6847 pFolderName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6848 Assert(pFolderName);
6849 memcpy(pFolderName->String.ucs2, hostPath.raw(), cbString);
6850
6851 pFolderName->u16Size = cbString;
6852 pFolderName->u16Length = cbString - sizeof(RTUCS2);
6853
6854 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
6855 parms[0].u.pointer.addr = pFolderName;
6856 parms[0].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6857
6858 cbString = (name.length() + 1) * sizeof(RTUCS2);
6859 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6860 Assert(pMapName);
6861 memcpy(pMapName->String.ucs2, name.raw(), cbString);
6862
6863 pMapName->u16Size = cbString;
6864 pMapName->u16Length = cbString - sizeof(RTUCS2);
6865
6866 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
6867 parms[1].u.pointer.addr = pMapName;
6868 parms[1].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6869
6870 vrc = console->getVMMDev()->hgcmHostCall("VBoxSharedFolders",
6871 SHFL_FN_ADD_MAPPING, 2, &parms[0]);
6872
6873 RTMemFree(pFolderName);
6874 RTMemFree(pMapName);
6875
6876 if (VBOX_FAILURE (vrc))
6877 {
6878 hrc = setError (E_FAIL,
6879 tr ("Could not create a shared folder '%ls' mapped to '%ls' (%Vrc)"),
6880 name.raw(), hostPath.raw(), vrc);
6881 break;
6882 }
6883 }
6884
6885 /* enter the lock again */
6886 alock.enter();
6887
6888 CheckComRCBreakRC (hrc);
6889 }
6890
6891 /*
6892 * Capture USB devices.
6893 */
6894 hrc = console->captureUSBDevices (pVM);
6895 CheckComRCBreakRC (hrc);
6896
6897 /* leave the lock before a lengthy operation */
6898 alock.leave();
6899
6900 /* Load saved state? */
6901 if (!!task->mSavedStateFile)
6902 {
6903 LogFlowFunc (("Restoring saved state from '%s'...\n",
6904 task->mSavedStateFile.raw()));
6905
6906 vrc = VMR3Load (pVM, task->mSavedStateFile,
6907 Console::stateProgressCallback,
6908 static_cast <VMProgressTask *> (task.get()));
6909
6910 /* Start/Resume the VM execution */
6911 if (VBOX_SUCCESS (vrc))
6912 {
6913 vrc = VMR3Resume (pVM);
6914 AssertRC (vrc);
6915 }
6916
6917 /* Power off in case we failed loading or resuming the VM */
6918 if (VBOX_FAILURE (vrc))
6919 {
6920 int vrc2 = VMR3PowerOff (pVM);
6921 AssertRC (vrc2);
6922 }
6923 }
6924 else
6925 {
6926 /* Power on the VM (i.e. start executing) */
6927 vrc = VMR3PowerOn(pVM);
6928 AssertRC (vrc);
6929 }
6930
6931 /* enter the lock again */
6932 alock.enter();
6933 }
6934 while (0);
6935
6936 /* On failure, destroy the VM */
6937 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6938 {
6939 /* preserve existing error info */
6940 ErrorInfoKeeper eik;
6941
6942 /*
6943 * powerDown() will call VMR3Destroy() and do all necessary
6944 * cleanup (VRDP, USB devices)
6945 */
6946 HRESULT hrc2 = console->powerDown();
6947 AssertComRC (hrc2);
6948 }
6949 }
6950 else
6951 {
6952 /*
6953 * If VMR3Create() failed it has released the VM memory.
6954 */
6955 console->mpVM = NULL;
6956 }
6957
6958 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6959 {
6960 /*
6961 * If VMR3Create() or one of the other calls in this function fail,
6962 * an appropriate error message has been already set. However since
6963 * that happens via a callback, the status code in this function is
6964 * not updated.
6965 */
6966 if (!task->mProgress->completed())
6967 {
6968 /*
6969 * If the COM error info is not yet set but we've got a
6970 * failure, convert the VBox status code into a meaningful
6971 * error message. This becomes unused once all the sources of
6972 * errors set the appropriate error message themselves.
6973 * Note that we don't use VMSetError() below because pVM is
6974 * either invalid or NULL here.
6975 */
6976 AssertMsgFailed (("Missing error message during powerup for "
6977 "status code %Vrc\n", vrc));
6978 hrc = setError (E_FAIL,
6979 tr ("Failed to start VM execution (%Vrc)"), vrc);
6980 }
6981 else
6982 hrc = task->mProgress->resultCode();
6983
6984 Assert (FAILED (hrc));
6985 break;
6986 }
6987 }
6988 while (0);
6989
6990 if (console->mMachineState == MachineState_Starting ||
6991 console->mMachineState == MachineState_Restoring)
6992 {
6993 /*
6994 * We are still in the Starting/Restoring state. This means one of:
6995 * 1) we failed before VMR3Create() was called;
6996 * 2) VMR3Create() failed.
6997 * In both cases, there is no need to call powerDown(), but we still
6998 * need to go back to the PoweredOff/Saved state. Reuse
6999 * vmstateChangeCallback() for that purpose.
7000 */
7001
7002 /* preserve existing error info */
7003 ErrorInfoKeeper eik;
7004
7005 Assert (console->mpVM == NULL);
7006 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
7007 console);
7008 }
7009
7010 /*
7011 * Evaluate the final result.
7012 * Note that the appropriate mMachineState value is already set by
7013 * vmstateChangeCallback() in all cases.
7014 */
7015
7016 /* leave the lock, don't need it any more */
7017 alock.leave();
7018
7019 if (SUCCEEDED (hrc))
7020 {
7021 /* Notify the progress object of the success */
7022 task->mProgress->notifyComplete (S_OK);
7023 }
7024 else
7025 {
7026 if (!task->mProgress->completed())
7027 {
7028 /* The progress object will fetch the current error info. This
7029 * gets the errors signalled by using setError(). The ones
7030 * signalled via VMSetError() immediately notify the progress
7031 * object that the operation is completed. */
7032 task->mProgress->notifyComplete (hrc);
7033 }
7034
7035 LogRel (("Power up failed (vrc=%Vrc, hrc=0x%08X)\n", vrc, hrc));
7036 }
7037
7038#if defined(RT_OS_WINDOWS)
7039 /* uninitialize COM */
7040 CoUninitialize();
7041#endif
7042
7043 LogFlowFuncLeave();
7044
7045 return VINF_SUCCESS;
7046}
7047
7048
7049/**
7050 * Reconfigures a VDI.
7051 *
7052 * @param pVM The VM handle.
7053 * @param hda The harddisk attachment.
7054 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
7055 * @return VBox status code.
7056 */
7057static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
7058{
7059 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
7060
7061 int rc;
7062 HRESULT hrc;
7063 char *psz = NULL;
7064 BSTR str = NULL;
7065 *phrc = S_OK;
7066#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
7067#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
7068#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
7069#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
7070
7071 /*
7072 * Figure out which IDE device this is.
7073 */
7074 ComPtr<IHardDisk> hardDisk;
7075 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
7076 DiskControllerType_T enmCtl;
7077 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
7078 LONG lDev;
7079 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
7080
7081 int i;
7082 switch (enmCtl)
7083 {
7084 case DiskControllerType_IDE0Controller:
7085 i = 0;
7086 break;
7087 case DiskControllerType_IDE1Controller:
7088 i = 2;
7089 break;
7090 default:
7091 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
7092 return VERR_GENERAL_FAILURE;
7093 }
7094
7095 if (lDev < 0 || lDev >= 2)
7096 {
7097 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
7098 return VERR_GENERAL_FAILURE;
7099 }
7100
7101 i = i + lDev;
7102
7103 /*
7104 * Is there an existing LUN? If not create it.
7105 * We ASSUME that this will NEVER collide with the DVD.
7106 */
7107 PCFGMNODE pCfg;
7108 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", i);
7109 if (!pLunL1)
7110 {
7111 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
7112 AssertReturn(pInst, VERR_INTERNAL_ERROR);
7113
7114 PCFGMNODE pLunL0;
7115 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", i); RC_CHECK();
7116 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
7117 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
7118 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
7119 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
7120
7121 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
7122 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
7123 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
7124 }
7125 else
7126 {
7127#ifdef VBOX_STRICT
7128 char *pszDriver;
7129 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
7130 Assert(!strcmp(pszDriver, "VBoxHDD"));
7131 MMR3HeapFree(pszDriver);
7132#endif
7133
7134 /*
7135 * Check if things has changed.
7136 */
7137 pCfg = CFGMR3GetChild(pLunL1, "Config");
7138 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
7139
7140 /* the image */
7141 /// @todo (dmik) we temporarily use the location property to
7142 // determine the image file name. This is subject to change
7143 // when iSCSI disks are here (we should either query a
7144 // storage-specific interface from IHardDisk, or "standardize"
7145 // the location property)
7146 hrc = hardDisk->COMGETTER(Location)(&str); H();
7147 STR_CONV();
7148 char *pszPath;
7149 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
7150 if (!strcmp(psz, pszPath))
7151 {
7152 /* parent images. */
7153 ComPtr<IHardDisk> parentHardDisk = hardDisk;
7154 for (PCFGMNODE pParent = pCfg;;)
7155 {
7156 MMR3HeapFree(pszPath);
7157 pszPath = NULL;
7158 STR_FREE();
7159
7160 /* get parent */
7161 ComPtr<IHardDisk> curHardDisk;
7162 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
7163 PCFGMNODE pCur;
7164 pCur = CFGMR3GetChild(pParent, "Parent");
7165 if (!pCur && !curHardDisk)
7166 {
7167 /* no change */
7168 LogFlowFunc (("No change!\n"));
7169 return VINF_SUCCESS;
7170 }
7171 if (!pCur || !curHardDisk)
7172 break;
7173
7174 /* compare paths. */
7175 /// @todo (dmik) we temporarily use the location property to
7176 // determine the image file name. This is subject to change
7177 // when iSCSI disks are here (we should either query a
7178 // storage-specific interface from IHardDisk, or "standardize"
7179 // the location property)
7180 hrc = curHardDisk->COMGETTER(Location)(&str); H();
7181 STR_CONV();
7182 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
7183 if (strcmp(psz, pszPath))
7184 break;
7185
7186 /* next */
7187 pParent = pCur;
7188 parentHardDisk = curHardDisk;
7189 }
7190
7191 }
7192 else
7193 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", i, pszPath));
7194
7195 MMR3HeapFree(pszPath);
7196 STR_FREE();
7197
7198 /*
7199 * Detach the driver and replace the config node.
7200 */
7201 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, i); RC_CHECK();
7202 CFGMR3RemoveNode(pCfg);
7203 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
7204 }
7205
7206 /*
7207 * Create the driver configuration.
7208 */
7209 /// @todo (dmik) we temporarily use the location property to
7210 // determine the image file name. This is subject to change
7211 // when iSCSI disks are here (we should either query a
7212 // storage-specific interface from IHardDisk, or "standardize"
7213 // the location property)
7214 hrc = hardDisk->COMGETTER(Location)(&str); H();
7215 STR_CONV();
7216 LogFlowFunc (("LUN#%d: leaf image '%s'\n", i, psz));
7217 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
7218 STR_FREE();
7219 /* Create an inversed tree of parents. */
7220 ComPtr<IHardDisk> parentHardDisk = hardDisk;
7221 for (PCFGMNODE pParent = pCfg;;)
7222 {
7223 ComPtr<IHardDisk> curHardDisk;
7224 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
7225 if (!curHardDisk)
7226 break;
7227
7228 PCFGMNODE pCur;
7229 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
7230 /// @todo (dmik) we temporarily use the location property to
7231 // determine the image file name. This is subject to change
7232 // when iSCSI disks are here (we should either query a
7233 // storage-specific interface from IHardDisk, or "standardize"
7234 // the location property)
7235 hrc = curHardDisk->COMGETTER(Location)(&str); H();
7236 STR_CONV();
7237 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
7238 STR_FREE();
7239
7240 /* next */
7241 pParent = pCur;
7242 parentHardDisk = curHardDisk;
7243 }
7244
7245 /*
7246 * Attach the new driver.
7247 */
7248 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, i, NULL); RC_CHECK();
7249
7250 LogFlowFunc (("Returns success\n"));
7251 return rc;
7252}
7253
7254
7255/**
7256 * Thread for executing the saved state operation.
7257 *
7258 * @param Thread The thread handle.
7259 * @param pvUser Pointer to a VMSaveTask structure.
7260 * @return VINF_SUCCESS (ignored).
7261 *
7262 * @note Locks the Console object for writing.
7263 */
7264/*static*/
7265DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
7266{
7267 LogFlowFuncEnter();
7268
7269 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
7270 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7271
7272 Assert (!task->mSavedStateFile.isNull());
7273 Assert (!task->mProgress.isNull());
7274
7275 const ComObjPtr <Console> &that = task->mConsole;
7276
7277 /*
7278 * Note: no need to use addCaller() to protect Console or addVMCaller() to
7279 * protect mpVM because VMSaveTask does that
7280 */
7281
7282 Utf8Str errMsg;
7283 HRESULT rc = S_OK;
7284
7285 if (task->mIsSnapshot)
7286 {
7287 Assert (!task->mServerProgress.isNull());
7288 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
7289
7290 rc = task->mServerProgress->WaitForCompletion (-1);
7291 if (SUCCEEDED (rc))
7292 {
7293 HRESULT result = S_OK;
7294 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
7295 if (SUCCEEDED (rc))
7296 rc = result;
7297 }
7298 }
7299
7300 if (SUCCEEDED (rc))
7301 {
7302 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
7303
7304 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
7305 Console::stateProgressCallback,
7306 static_cast <VMProgressTask *> (task.get()));
7307 if (VBOX_FAILURE (vrc))
7308 {
7309 errMsg = Utf8StrFmt (
7310 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
7311 task->mSavedStateFile.raw(), vrc);
7312 rc = E_FAIL;
7313 }
7314 }
7315
7316 /* lock the console sonce we're going to access it */
7317 AutoLock thatLock (that);
7318
7319 if (SUCCEEDED (rc))
7320 {
7321 if (task->mIsSnapshot)
7322 do
7323 {
7324 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
7325
7326 ComPtr <IHardDiskAttachmentCollection> hdaColl;
7327 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
7328 if (FAILED (rc))
7329 break;
7330 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
7331 rc = hdaColl->Enumerate (hdaEn.asOutParam());
7332 if (FAILED (rc))
7333 break;
7334 BOOL more = FALSE;
7335 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
7336 {
7337 ComPtr <IHardDiskAttachment> hda;
7338 rc = hdaEn->GetNext (hda.asOutParam());
7339 if (FAILED (rc))
7340 break;
7341
7342 PVMREQ pReq;
7343 IHardDiskAttachment *pHda = hda;
7344 /*
7345 * don't leave the lock since reconfigureVDI isn't going to
7346 * access Console.
7347 */
7348 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
7349 (PFNRT)reconfigureVDI, 3, that->mpVM,
7350 pHda, &rc);
7351 if (VBOX_SUCCESS (rc))
7352 rc = pReq->iStatus;
7353 VMR3ReqFree (pReq);
7354 if (FAILED (rc))
7355 break;
7356 if (VBOX_FAILURE (vrc))
7357 {
7358 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
7359 rc = E_FAIL;
7360 break;
7361 }
7362 }
7363 }
7364 while (0);
7365 }
7366
7367 /* finalize the procedure regardless of the result */
7368 if (task->mIsSnapshot)
7369 {
7370 /*
7371 * finalize the requested snapshot object.
7372 * This will reset the machine state to the state it had right
7373 * before calling mControl->BeginTakingSnapshot().
7374 */
7375 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
7376 }
7377 else
7378 {
7379 /*
7380 * finalize the requested save state procedure.
7381 * In case of success, the server will set the machine state to Saved;
7382 * in case of failure it will reset the it to the state it had right
7383 * before calling mControl->BeginSavingState().
7384 */
7385 that->mControl->EndSavingState (SUCCEEDED (rc));
7386 }
7387
7388 /* synchronize the state with the server */
7389 if (task->mIsSnapshot || FAILED (rc))
7390 {
7391 if (task->mLastMachineState == MachineState_Running)
7392 {
7393 /* restore the paused state if appropriate */
7394 that->setMachineStateLocally (MachineState_Paused);
7395 /* restore the running state if appropriate */
7396 that->Resume();
7397 }
7398 else
7399 that->setMachineStateLocally (task->mLastMachineState);
7400 }
7401 else
7402 {
7403 /*
7404 * The machine has been successfully saved, so power it down
7405 * (vmstateChangeCallback() will set state to Saved on success).
7406 * Note: we release the task's VM caller, otherwise it will
7407 * deadlock.
7408 */
7409 task->releaseVMCaller();
7410
7411 rc = that->powerDown();
7412 }
7413
7414 /* notify the progress object about operation completion */
7415 if (SUCCEEDED (rc))
7416 task->mProgress->notifyComplete (S_OK);
7417 else
7418 {
7419 if (!errMsg.isNull())
7420 task->mProgress->notifyComplete (rc,
7421 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
7422 else
7423 task->mProgress->notifyComplete (rc);
7424 }
7425
7426 LogFlowFuncLeave();
7427 return VINF_SUCCESS;
7428}
7429
7430/**
7431 * Thread for powering down the Console.
7432 *
7433 * @param Thread The thread handle.
7434 * @param pvUser Pointer to the VMTask structure.
7435 * @return VINF_SUCCESS (ignored).
7436 *
7437 * @note Locks the Console object for writing.
7438 */
7439/*static*/
7440DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
7441{
7442 LogFlowFuncEnter();
7443
7444 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
7445 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7446
7447 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
7448
7449 const ComObjPtr <Console> &that = task->mConsole;
7450
7451 /*
7452 * Note: no need to use addCaller() to protect Console
7453 * because VMTask does that
7454 */
7455
7456 /* release VM caller to let powerDown() proceed */
7457 task->releaseVMCaller();
7458
7459 HRESULT rc = that->powerDown();
7460 AssertComRC (rc);
7461
7462 LogFlowFuncLeave();
7463 return VINF_SUCCESS;
7464}
7465
7466/**
7467 * The Main status driver instance data.
7468 */
7469typedef struct DRVMAINSTATUS
7470{
7471 /** The LED connectors. */
7472 PDMILEDCONNECTORS ILedConnectors;
7473 /** Pointer to the LED ports interface above us. */
7474 PPDMILEDPORTS pLedPorts;
7475 /** Pointer to the array of LED pointers. */
7476 PPDMLED *papLeds;
7477 /** The unit number corresponding to the first entry in the LED array. */
7478 RTUINT iFirstLUN;
7479 /** The unit number corresponding to the last entry in the LED array.
7480 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7481 RTUINT iLastLUN;
7482} DRVMAINSTATUS, *PDRVMAINSTATUS;
7483
7484
7485/**
7486 * Notification about a unit which have been changed.
7487 *
7488 * The driver must discard any pointers to data owned by
7489 * the unit and requery it.
7490 *
7491 * @param pInterface Pointer to the interface structure containing the called function pointer.
7492 * @param iLUN The unit number.
7493 */
7494DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7495{
7496 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7497 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7498 {
7499 PPDMLED pLed;
7500 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7501 if (VBOX_FAILURE(rc))
7502 pLed = NULL;
7503 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7504 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7505 }
7506}
7507
7508
7509/**
7510 * Queries an interface to the driver.
7511 *
7512 * @returns Pointer to interface.
7513 * @returns NULL if the interface was not supported by the driver.
7514 * @param pInterface Pointer to this interface structure.
7515 * @param enmInterface The requested interface identification.
7516 */
7517DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7518{
7519 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7520 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7521 switch (enmInterface)
7522 {
7523 case PDMINTERFACE_BASE:
7524 return &pDrvIns->IBase;
7525 case PDMINTERFACE_LED_CONNECTORS:
7526 return &pDrv->ILedConnectors;
7527 default:
7528 return NULL;
7529 }
7530}
7531
7532
7533/**
7534 * Destruct a status driver instance.
7535 *
7536 * @returns VBox status.
7537 * @param pDrvIns The driver instance data.
7538 */
7539DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7540{
7541 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7542 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7543 if (pData->papLeds)
7544 {
7545 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7546 while (iLed-- > 0)
7547 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7548 }
7549}
7550
7551
7552/**
7553 * Construct a status driver instance.
7554 *
7555 * @returns VBox status.
7556 * @param pDrvIns The driver instance data.
7557 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7558 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7559 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7560 * iInstance it's expected to be used a bit in this function.
7561 */
7562DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7563{
7564 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7565 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7566
7567 /*
7568 * Validate configuration.
7569 */
7570 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7571 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7572 PPDMIBASE pBaseIgnore;
7573 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7574 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7575 {
7576 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7577 return VERR_PDM_DRVINS_NO_ATTACH;
7578 }
7579
7580 /*
7581 * Data.
7582 */
7583 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7584 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7585
7586 /*
7587 * Read config.
7588 */
7589 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7590 if (VBOX_FAILURE(rc))
7591 {
7592 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7593 return rc;
7594 }
7595
7596 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7597 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7598 pData->iFirstLUN = 0;
7599 else if (VBOX_FAILURE(rc))
7600 {
7601 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7602 return rc;
7603 }
7604
7605 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7606 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7607 pData->iLastLUN = 0;
7608 else if (VBOX_FAILURE(rc))
7609 {
7610 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7611 return rc;
7612 }
7613 if (pData->iFirstLUN > pData->iLastLUN)
7614 {
7615 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7616 return VERR_GENERAL_FAILURE;
7617 }
7618
7619 /*
7620 * Get the ILedPorts interface of the above driver/device and
7621 * query the LEDs we want.
7622 */
7623 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7624 if (!pData->pLedPorts)
7625 {
7626 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7627 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7628 }
7629
7630 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7631 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7632
7633 return VINF_SUCCESS;
7634}
7635
7636
7637/**
7638 * Keyboard driver registration record.
7639 */
7640const PDMDRVREG Console::DrvStatusReg =
7641{
7642 /* u32Version */
7643 PDM_DRVREG_VERSION,
7644 /* szDriverName */
7645 "MainStatus",
7646 /* pszDescription */
7647 "Main status driver (Main as in the API).",
7648 /* fFlags */
7649 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7650 /* fClass. */
7651 PDM_DRVREG_CLASS_STATUS,
7652 /* cMaxInstances */
7653 ~0,
7654 /* cbInstance */
7655 sizeof(DRVMAINSTATUS),
7656 /* pfnConstruct */
7657 Console::drvStatus_Construct,
7658 /* pfnDestruct */
7659 Console::drvStatus_Destruct,
7660 /* pfnIOCtl */
7661 NULL,
7662 /* pfnPowerOn */
7663 NULL,
7664 /* pfnReset */
7665 NULL,
7666 /* pfnSuspend */
7667 NULL,
7668 /* pfnResume */
7669 NULL,
7670 /* pfnDetach */
7671 NULL
7672};
7673
Note: See TracBrowser for help on using the repository browser.

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