VirtualBox

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

Last change on this file since 2988 was 2981, checked in by vboxsync, 17 years ago

InnoTek -> innotek: all the headers and comments.

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