VirtualBox

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

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

Main/Frontends: Next step to support asynchronous USB device flow.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 253.1 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 /* Request the device capture */
1949 HRESULT rc = mControl->CaptureUSBDevice (aId);
1950 CheckComRCReturnRC (rc);
1951
1952 return rc;
1953}
1954
1955STDMETHODIMP Console::DetachUSBDevice (INPTR GUIDPARAM aId, IUSBDevice **aDevice)
1956{
1957 if (!aDevice)
1958 return E_POINTER;
1959
1960 AutoCaller autoCaller (this);
1961 CheckComRCReturnRC (autoCaller.rc());
1962
1963 AutoLock alock (this);
1964
1965 /* Find it. */
1966 ComObjPtr <OUSBDevice> device;
1967 USBDeviceList::iterator it = mUSBDevices.begin();
1968 while (it != mUSBDevices.end())
1969 {
1970 if ((*it)->id() == aId)
1971 {
1972 device = *it;
1973 break;
1974 }
1975 ++ it;
1976 }
1977
1978 if (!device)
1979 return setError (E_INVALIDARG,
1980 tr ("USB device with UUID {%Vuuid} is not attached to this machine"),
1981 Guid (aId).raw());
1982
1983 /* Request the device release */
1984 HRESULT rc = mControl->ReleaseUSBDevice (aId);
1985 CheckComRCReturnRC (rc);
1986
1987 return rc;
1988}
1989
1990STDMETHODIMP
1991Console::CreateSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath)
1992{
1993 if (!aName || !aHostPath)
1994 return E_INVALIDARG;
1995
1996 AutoCaller autoCaller (this);
1997 CheckComRCReturnRC (autoCaller.rc());
1998
1999 AutoLock alock (this);
2000
2001 if (mMachineState == MachineState_Saved)
2002 return setError (E_FAIL,
2003 tr ("Cannot create a transient shared folder on a "
2004 "machine in the saved state."));
2005
2006 /// @todo (dmik) check globally shared folders when they are done
2007
2008 /* check machine's shared folders */
2009 {
2010 ComPtr <ISharedFolderCollection> coll;
2011 HRESULT rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
2012 if (FAILED (rc))
2013 return rc;
2014
2015 ComPtr <ISharedFolder> machineSharedFolder;
2016 rc = coll->FindByName (aName, machineSharedFolder.asOutParam());
2017 if (SUCCEEDED (rc))
2018 return setError (E_FAIL,
2019 tr ("A permanent shared folder named '%ls' already "
2020 "exists."), aName);
2021 }
2022
2023 ComObjPtr <SharedFolder> sharedFolder;
2024 HRESULT rc = findSharedFolder (aName, sharedFolder, false /* aSetError */);
2025 if (SUCCEEDED (rc))
2026 return setError (E_FAIL,
2027 tr ("A shared folder named '%ls' already exists."), aName);
2028
2029 sharedFolder.createObject();
2030 rc = sharedFolder->init (this, aName, aHostPath);
2031 CheckComRCReturnRC (rc);
2032
2033 BOOL accessible = FALSE;
2034 rc = sharedFolder->COMGETTER(Accessible) (&accessible);
2035 CheckComRCReturnRC (rc);
2036
2037 if (!accessible)
2038 return setError (E_FAIL,
2039 tr ("The shared folder path '%ls' on the host is not accessible."), aHostPath);
2040
2041 /// @todo (r=sander?) should move this into the shared folder class */
2042 if (mpVM && mVMMDev->isShFlActive())
2043 {
2044 /*
2045 * if the VM is online and supports shared folders, share this folder
2046 * under the specified name. On error, return it to the caller.
2047 */
2048
2049 /* protect mpVM */
2050 AutoVMCaller autoVMCaller (this);
2051 CheckComRCReturnRC (autoVMCaller.rc());
2052
2053 VBOXHGCMSVCPARM parms[2];
2054 SHFLSTRING *pFolderName, *pMapName;
2055 int cbString;
2056
2057 Log(("Add shared folder %ls -> %ls\n", aName, aHostPath));
2058
2059 cbString = (RTStrUcs2Len(aHostPath) + 1) * sizeof(RTUCS2);
2060 pFolderName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
2061 Assert(pFolderName);
2062 memcpy(pFolderName->String.ucs2, aHostPath, cbString);
2063
2064 pFolderName->u16Size = cbString;
2065 pFolderName->u16Length = cbString - sizeof(RTUCS2);
2066
2067 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
2068 parms[0].u.pointer.addr = pFolderName;
2069 parms[0].u.pointer.size = sizeof(SHFLSTRING) + cbString;
2070
2071 cbString = (RTStrUcs2Len(aName) + 1) * sizeof(RTUCS2);
2072 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
2073 Assert(pMapName);
2074 memcpy(pMapName->String.ucs2, aName, cbString);
2075
2076 pMapName->u16Size = cbString;
2077 pMapName->u16Length = cbString - sizeof(RTUCS2);
2078
2079 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
2080 parms[1].u.pointer.addr = pMapName;
2081 parms[1].u.pointer.size = sizeof(SHFLSTRING) + cbString;
2082
2083 rc = mVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_ADD_MAPPING, 2, &parms[0]);
2084 RTMemFree(pFolderName);
2085 RTMemFree(pMapName);
2086 if (rc != VINF_SUCCESS)
2087 return setError (E_FAIL, tr ("Unable to add mapping %ls to %ls."), aHostPath, aName);
2088 }
2089
2090 mSharedFolders.push_back (sharedFolder);
2091 return S_OK;
2092}
2093
2094STDMETHODIMP Console::RemoveSharedFolder (INPTR BSTR aName)
2095{
2096 if (!aName)
2097 return E_INVALIDARG;
2098
2099 AutoCaller autoCaller (this);
2100 CheckComRCReturnRC (autoCaller.rc());
2101
2102 AutoLock alock (this);
2103
2104 if (mMachineState == MachineState_Saved)
2105 return setError (E_FAIL,
2106 tr ("Cannot remove a transient shared folder when the "
2107 "machine is in the saved state."));
2108
2109 ComObjPtr <SharedFolder> sharedFolder;
2110 HRESULT rc = findSharedFolder (aName, sharedFolder, true /* aSetError */);
2111 CheckComRCReturnRC (rc);
2112
2113 /* protect mpVM */
2114 AutoVMCaller autoVMCaller (this);
2115 CheckComRCReturnRC (autoVMCaller.rc());
2116
2117 if (mpVM && mVMMDev->isShFlActive())
2118 {
2119 /*
2120 * if the VM is online and supports shared folders, UNshare this folder.
2121 * On error, return it to the caller.
2122 */
2123 VBOXHGCMSVCPARM parms;
2124 SHFLSTRING *pMapName;
2125 int cbString;
2126
2127 cbString = (RTStrUcs2Len(aName) + 1) * sizeof(RTUCS2);
2128 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
2129 Assert(pMapName);
2130 memcpy(pMapName->String.ucs2, aName, cbString);
2131
2132 pMapName->u16Size = cbString;
2133 pMapName->u16Length = cbString - sizeof(RTUCS2);
2134
2135 parms.type = VBOX_HGCM_SVC_PARM_PTR;
2136 parms.u.pointer.addr = pMapName;
2137 parms.u.pointer.size = sizeof(SHFLSTRING) + cbString;
2138
2139 rc = mVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_REMOVE_MAPPING, 1, &parms);
2140 RTMemFree(pMapName);
2141 if (rc != VINF_SUCCESS)
2142 rc = setError (E_FAIL, tr ("Unable to remove the mapping %ls."), aName);
2143 }
2144
2145 mSharedFolders.remove (sharedFolder);
2146 return rc;
2147}
2148
2149STDMETHODIMP Console::TakeSnapshot (INPTR BSTR aName, INPTR BSTR aDescription,
2150 IProgress **aProgress)
2151{
2152 LogFlowThisFuncEnter();
2153 LogFlowThisFunc (("aName='%ls' mMachineState=%08X\n", aName, mMachineState));
2154
2155 if (!aName)
2156 return E_INVALIDARG;
2157 if (!aProgress)
2158 return E_POINTER;
2159
2160 AutoCaller autoCaller (this);
2161 CheckComRCReturnRC (autoCaller.rc());
2162
2163 AutoLock alock (this);
2164
2165 if (mMachineState > MachineState_Running &&
2166 mMachineState != MachineState_Paused)
2167 {
2168 return setError (E_FAIL,
2169 tr ("Cannot take a snapshot of a machine while it is changing state. (Machine state: %d)"), mMachineState);
2170 }
2171
2172 /* memorize the current machine state */
2173 MachineState_T lastMachineState = mMachineState;
2174
2175 if (mMachineState == MachineState_Running)
2176 {
2177 HRESULT rc = Pause();
2178 CheckComRCReturnRC (rc);
2179 }
2180
2181 HRESULT rc = S_OK;
2182
2183 bool takingSnapshotOnline = mMachineState == MachineState_Paused;
2184
2185 /*
2186 * create a descriptionless VM-side progress object
2187 * (only when creating a snapshot online)
2188 */
2189 ComObjPtr <Progress> saveProgress;
2190 if (takingSnapshotOnline)
2191 {
2192 saveProgress.createObject();
2193 rc = saveProgress->init (FALSE, 1, Bstr (tr ("Saving the execution state")));
2194 AssertComRCReturn (rc, rc);
2195 }
2196
2197 bool beganTakingSnapshot = false;
2198 bool taskCreationFailed = false;
2199
2200 do
2201 {
2202 /* create a task object early to ensure mpVM protection is successful */
2203 std::auto_ptr <VMSaveTask> task;
2204 if (takingSnapshotOnline)
2205 {
2206 task.reset (new VMSaveTask (this, saveProgress));
2207 rc = task->rc();
2208 /*
2209 * If we fail here it means a PowerDown() call happened on another
2210 * thread while we were doing Pause() (which leaves the Console lock).
2211 * We assign PowerDown() a higher precendence than TakeSnapshot(),
2212 * therefore just return the error to the caller.
2213 */
2214 if (FAILED (rc))
2215 {
2216 taskCreationFailed = true;
2217 break;
2218 }
2219 }
2220
2221 Bstr stateFilePath;
2222 ComPtr <IProgress> serverProgress;
2223
2224 /*
2225 * request taking a new snapshot object on the server
2226 * (this will set the machine state to Saving on the server to block
2227 * others from accessing this machine)
2228 */
2229 rc = mControl->BeginTakingSnapshot (this, aName, aDescription,
2230 saveProgress, stateFilePath.asOutParam(),
2231 serverProgress.asOutParam());
2232 if (FAILED (rc))
2233 break;
2234
2235 /*
2236 * state file is non-null only when the VM is paused
2237 * (i.e. createing a snapshot online)
2238 */
2239 ComAssertBreak (
2240 (!stateFilePath.isNull() && takingSnapshotOnline) ||
2241 (stateFilePath.isNull() && !takingSnapshotOnline),
2242 rc = E_FAIL);
2243
2244 beganTakingSnapshot = true;
2245
2246 /* sync the state with the server */
2247 setMachineStateLocally (MachineState_Saving);
2248
2249 /*
2250 * create a combined VM-side progress object and start the save task
2251 * (only when creating a snapshot online)
2252 */
2253 ComObjPtr <CombinedProgress> combinedProgress;
2254 if (takingSnapshotOnline)
2255 {
2256 combinedProgress.createObject();
2257 rc = combinedProgress->init ((IConsole *) this,
2258 Bstr (tr ("Taking snapshot of virtual machine")),
2259 serverProgress, saveProgress);
2260 AssertComRCBreakRC (rc);
2261
2262 /* setup task object and thread to carry out the operation asynchronously */
2263 task->mIsSnapshot = true;
2264 task->mSavedStateFile = stateFilePath;
2265 task->mServerProgress = serverProgress;
2266 /* set the state the operation thread will restore when it is finished */
2267 task->mLastMachineState = lastMachineState;
2268
2269 /* create a thread to wait until the VM state is saved */
2270 int vrc = RTThreadCreate (NULL, Console::saveStateThread, (void *) task.get(),
2271 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMTakeSnap");
2272
2273 ComAssertMsgRCBreak (vrc, ("Could not create VMTakeSnap thread (%Vrc)\n", vrc),
2274 rc = E_FAIL);
2275
2276 /* task is now owned by saveStateThread(), so release it */
2277 task.release();
2278 }
2279
2280 if (SUCCEEDED (rc))
2281 {
2282 /* return the correct progress to the caller */
2283 if (combinedProgress)
2284 combinedProgress.queryInterfaceTo (aProgress);
2285 else
2286 serverProgress.queryInterfaceTo (aProgress);
2287 }
2288 }
2289 while (0);
2290
2291 if (FAILED (rc) && !taskCreationFailed)
2292 {
2293 /* preserve existing error info */
2294 ErrorInfoKeeper eik;
2295
2296 if (beganTakingSnapshot && takingSnapshotOnline)
2297 {
2298 /*
2299 * cancel the requested snapshot (only when creating a snapshot
2300 * online, otherwise the server will cancel the snapshot itself).
2301 * This will reset the machine state to the state it had right
2302 * before calling mControl->BeginTakingSnapshot().
2303 */
2304 mControl->EndTakingSnapshot (FALSE);
2305 }
2306
2307 if (lastMachineState == MachineState_Running)
2308 {
2309 /* restore the paused state if appropriate */
2310 setMachineStateLocally (MachineState_Paused);
2311 /* restore the running state if appropriate */
2312 Resume();
2313 }
2314 else
2315 setMachineStateLocally (lastMachineState);
2316 }
2317
2318 LogFlowThisFunc (("rc=%08X\n", rc));
2319 LogFlowThisFuncLeave();
2320 return rc;
2321}
2322
2323STDMETHODIMP Console::DiscardSnapshot (INPTR GUIDPARAM aId, IProgress **aProgress)
2324{
2325 if (Guid (aId).isEmpty())
2326 return E_INVALIDARG;
2327 if (!aProgress)
2328 return E_POINTER;
2329
2330 AutoCaller autoCaller (this);
2331 CheckComRCReturnRC (autoCaller.rc());
2332
2333 AutoLock alock (this);
2334
2335 if (mMachineState >= MachineState_Running)
2336 return setError (E_FAIL,
2337 tr ("Cannot discard a snapshot on a running machine (Machine state: %d)"), mMachineState);
2338
2339 MachineState_T machineState = MachineState_InvalidMachineState;
2340 HRESULT rc = mControl->DiscardSnapshot (this, aId, &machineState, aProgress);
2341 CheckComRCReturnRC (rc);
2342
2343 setMachineStateLocally (machineState);
2344 return S_OK;
2345}
2346
2347STDMETHODIMP Console::DiscardCurrentState (IProgress **aProgress)
2348{
2349 AutoCaller autoCaller (this);
2350 CheckComRCReturnRC (autoCaller.rc());
2351
2352 AutoLock alock (this);
2353
2354 if (mMachineState >= MachineState_Running)
2355 return setError (E_FAIL,
2356 tr ("Cannot discard the current state of a running machine. (Machine state: %d)"), mMachineState);
2357
2358 MachineState_T machineState = MachineState_InvalidMachineState;
2359 HRESULT rc = mControl->DiscardCurrentState (this, &machineState, aProgress);
2360 CheckComRCReturnRC (rc);
2361
2362 setMachineStateLocally (machineState);
2363 return S_OK;
2364}
2365
2366STDMETHODIMP Console::DiscardCurrentSnapshotAndState (IProgress **aProgress)
2367{
2368 AutoCaller autoCaller (this);
2369 CheckComRCReturnRC (autoCaller.rc());
2370
2371 AutoLock alock (this);
2372
2373 if (mMachineState >= MachineState_Running)
2374 return setError (E_FAIL,
2375 tr ("Cannot discard the current snapshot and state on a running machine. (Machine state: %d)"), mMachineState);
2376
2377 MachineState_T machineState = MachineState_InvalidMachineState;
2378 HRESULT rc =
2379 mControl->DiscardCurrentSnapshotAndState (this, &machineState, aProgress);
2380 CheckComRCReturnRC (rc);
2381
2382 setMachineStateLocally (machineState);
2383 return S_OK;
2384}
2385
2386STDMETHODIMP Console::RegisterCallback (IConsoleCallback *aCallback)
2387{
2388 if (!aCallback)
2389 return E_INVALIDARG;
2390
2391 AutoCaller autoCaller (this);
2392 CheckComRCReturnRC (autoCaller.rc());
2393
2394 AutoLock alock (this);
2395
2396 mCallbacks.push_back (CallbackList::value_type (aCallback));
2397
2398 /* Inform the callback about the current status (for example, the new
2399 * callback must know the current mouse capabilities and the pointer
2400 * shape in order to properly integrate the mouse pointer). */
2401
2402 if (mCallbackData.mpsc.valid)
2403 aCallback->OnMousePointerShapeChange (mCallbackData.mpsc.visible,
2404 mCallbackData.mpsc.alpha,
2405 mCallbackData.mpsc.xHot,
2406 mCallbackData.mpsc.yHot,
2407 mCallbackData.mpsc.width,
2408 mCallbackData.mpsc.height,
2409 mCallbackData.mpsc.shape);
2410 if (mCallbackData.mcc.valid)
2411 aCallback->OnMouseCapabilityChange (mCallbackData.mcc.supportsAbsolute,
2412 mCallbackData.mcc.needsHostCursor);
2413
2414 aCallback->OnAdditionsStateChange();
2415
2416 if (mCallbackData.klc.valid)
2417 aCallback->OnKeyboardLedsChange (mCallbackData.klc.numLock,
2418 mCallbackData.klc.capsLock,
2419 mCallbackData.klc.scrollLock);
2420
2421 /* Note: we don't call OnStateChange for new callbacks because the
2422 * machine state is a) not actually changed on callback registration
2423 * and b) can be always queried from Console. */
2424
2425 return S_OK;
2426}
2427
2428STDMETHODIMP Console::UnregisterCallback (IConsoleCallback *aCallback)
2429{
2430 if (!aCallback)
2431 return E_INVALIDARG;
2432
2433 AutoCaller autoCaller (this);
2434 CheckComRCReturnRC (autoCaller.rc());
2435
2436 AutoLock alock (this);
2437
2438 CallbackList::iterator it;
2439 it = std::find (mCallbacks.begin(),
2440 mCallbacks.end(),
2441 CallbackList::value_type (aCallback));
2442 if (it == mCallbacks.end())
2443 return setError (E_INVALIDARG,
2444 tr ("The given callback handler is not registered"));
2445
2446 mCallbacks.erase (it);
2447 return S_OK;
2448}
2449
2450// Non-interface public methods
2451/////////////////////////////////////////////////////////////////////////////
2452
2453/**
2454 * Called by IInternalSessionControl::OnDVDDriveChange().
2455 *
2456 * @note Locks this object for reading.
2457 */
2458HRESULT Console::onDVDDriveChange()
2459{
2460 LogFlowThisFunc (("\n"));
2461
2462 AutoCaller autoCaller (this);
2463 AssertComRCReturnRC (autoCaller.rc());
2464
2465 AutoReaderLock alock (this);
2466
2467 /* Ignore callbacks when there's no VM around */
2468 if (!mpVM)
2469 return S_OK;
2470
2471 /* protect mpVM */
2472 AutoVMCaller autoVMCaller (this);
2473 CheckComRCReturnRC (autoVMCaller.rc());
2474
2475 /* Get the current DVD state */
2476 HRESULT rc;
2477 DriveState_T eState;
2478
2479 rc = mDVDDrive->COMGETTER (State) (&eState);
2480 ComAssertComRCRetRC (rc);
2481
2482 /* Paranoia */
2483 if ( eState == DriveState_NotMounted
2484 && meDVDState == DriveState_NotMounted)
2485 {
2486 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2487 return S_OK;
2488 }
2489
2490 /* Get the path string and other relevant properties */
2491 Bstr Path;
2492 bool fPassthrough = false;
2493 switch (eState)
2494 {
2495 case DriveState_ImageMounted:
2496 {
2497 ComPtr <IDVDImage> ImagePtr;
2498 rc = mDVDDrive->GetImage (ImagePtr.asOutParam());
2499 if (SUCCEEDED (rc))
2500 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2501 break;
2502 }
2503
2504 case DriveState_HostDriveCaptured:
2505 {
2506 ComPtr <IHostDVDDrive> DrivePtr;
2507 BOOL enabled;
2508 rc = mDVDDrive->GetHostDrive (DrivePtr.asOutParam());
2509 if (SUCCEEDED (rc))
2510 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2511 if (SUCCEEDED (rc))
2512 rc = mDVDDrive->COMGETTER (Passthrough) (&enabled);
2513 if (SUCCEEDED (rc))
2514 fPassthrough = !!enabled;
2515 break;
2516 }
2517
2518 case DriveState_NotMounted:
2519 break;
2520
2521 default:
2522 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2523 rc = E_FAIL;
2524 break;
2525 }
2526
2527 AssertComRC (rc);
2528 if (FAILED (rc))
2529 {
2530 LogFlowThisFunc (("Returns %#x\n", rc));
2531 return rc;
2532 }
2533
2534 return doDriveChange ("piix3ide", 0, 2, eState, &meDVDState,
2535 Utf8Str (Path).raw(), fPassthrough);
2536}
2537
2538
2539/**
2540 * Called by IInternalSessionControl::OnFloppyDriveChange().
2541 *
2542 * @note Locks this object for reading.
2543 */
2544HRESULT Console::onFloppyDriveChange()
2545{
2546 LogFlowThisFunc (("\n"));
2547
2548 AutoCaller autoCaller (this);
2549 AssertComRCReturnRC (autoCaller.rc());
2550
2551 AutoReaderLock alock (this);
2552
2553 /* Ignore callbacks when there's no VM around */
2554 if (!mpVM)
2555 return S_OK;
2556
2557 /* protect mpVM */
2558 AutoVMCaller autoVMCaller (this);
2559 CheckComRCReturnRC (autoVMCaller.rc());
2560
2561 /* Get the current floppy state */
2562 HRESULT rc;
2563 DriveState_T eState;
2564
2565 /* If the floppy drive is disabled, we're not interested */
2566 BOOL fEnabled;
2567 rc = mFloppyDrive->COMGETTER (Enabled) (&fEnabled);
2568 ComAssertComRCRetRC (rc);
2569
2570 if (!fEnabled)
2571 return S_OK;
2572
2573 rc = mFloppyDrive->COMGETTER (State) (&eState);
2574 ComAssertComRCRetRC (rc);
2575
2576 Log2 (("onFloppyDriveChange: eState=%d meFloppyState=%d\n", eState, meFloppyState));
2577
2578
2579 /* Paranoia */
2580 if ( eState == DriveState_NotMounted
2581 && meFloppyState == DriveState_NotMounted)
2582 {
2583 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2584 return S_OK;
2585 }
2586
2587 /* Get the path string and other relevant properties */
2588 Bstr Path;
2589 switch (eState)
2590 {
2591 case DriveState_ImageMounted:
2592 {
2593 ComPtr <IFloppyImage> ImagePtr;
2594 rc = mFloppyDrive->GetImage (ImagePtr.asOutParam());
2595 if (SUCCEEDED (rc))
2596 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2597 break;
2598 }
2599
2600 case DriveState_HostDriveCaptured:
2601 {
2602 ComPtr <IHostFloppyDrive> DrivePtr;
2603 rc = mFloppyDrive->GetHostDrive (DrivePtr.asOutParam());
2604 if (SUCCEEDED (rc))
2605 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2606 break;
2607 }
2608
2609 case DriveState_NotMounted:
2610 break;
2611
2612 default:
2613 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2614 rc = E_FAIL;
2615 break;
2616 }
2617
2618 AssertComRC (rc);
2619 if (FAILED (rc))
2620 {
2621 LogFlowThisFunc (("Returns %#x\n", rc));
2622 return rc;
2623 }
2624
2625 return doDriveChange ("i82078", 0, 0, eState, &meFloppyState,
2626 Utf8Str (Path).raw(), false);
2627}
2628
2629
2630/**
2631 * Process a floppy or dvd change.
2632 *
2633 * @returns COM status code.
2634 *
2635 * @param pszDevice The PDM device name.
2636 * @param uInstance The PDM device instance.
2637 * @param uLun The PDM LUN number of the drive.
2638 * @param eState The new state.
2639 * @param peState Pointer to the variable keeping the actual state of the drive.
2640 * This will be both read and updated to eState or other appropriate state.
2641 * @param pszPath The path to the media / drive which is now being mounted / captured.
2642 * If NULL no media or drive is attached and the lun will be configured with
2643 * the default block driver with no media. This will also be the state if
2644 * mounting / capturing the specified media / drive fails.
2645 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2646 *
2647 * @note Locks this object for reading.
2648 */
2649HRESULT Console::doDriveChange (const char *pszDevice, unsigned uInstance, unsigned uLun, DriveState_T eState,
2650 DriveState_T *peState, const char *pszPath, bool fPassthrough)
2651{
2652 LogFlowThisFunc (("pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2653 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2654 pszDevice, pszDevice, uInstance, uLun, eState,
2655 peState, *peState, pszPath, pszPath, fPassthrough));
2656
2657 AutoCaller autoCaller (this);
2658 AssertComRCReturnRC (autoCaller.rc());
2659
2660 AutoReaderLock alock (this);
2661
2662 /* protect mpVM */
2663 AutoVMCaller autoVMCaller (this);
2664 CheckComRCReturnRC (autoVMCaller.rc());
2665
2666 /*
2667 * Call worker in EMT, that's faster and safer than doing everything
2668 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2669 * here to make requests from under the lock in order to serialize them.
2670 */
2671 PVMREQ pReq;
2672 int vrc = VMR3ReqCall (mpVM, &pReq, 0 /* no wait! */,
2673 (PFNRT) Console::changeDrive, 8,
2674 this, pszDevice, uInstance, uLun, eState, peState,
2675 pszPath, fPassthrough);
2676 /// @todo (r=dmik) bird, it would be nice to have a special VMR3Req method
2677 // for that purpose, that doesn't return useless VERR_TIMEOUT
2678 if (vrc == VERR_TIMEOUT)
2679 vrc = VINF_SUCCESS;
2680
2681 /* leave the lock before waiting for a result (EMT will call us back!) */
2682 alock.leave();
2683
2684 if (VBOX_SUCCESS (vrc))
2685 {
2686 vrc = VMR3ReqWait (pReq, RT_INDEFINITE_WAIT);
2687 AssertRC (vrc);
2688 if (VBOX_SUCCESS (vrc))
2689 vrc = pReq->iStatus;
2690 }
2691 VMR3ReqFree (pReq);
2692
2693 if (VBOX_SUCCESS (vrc))
2694 {
2695 LogFlowThisFunc (("Returns S_OK\n"));
2696 return S_OK;
2697 }
2698
2699 if (pszPath)
2700 return setError (E_FAIL,
2701 tr ("Could not mount the media/drive '%s' (%Vrc)"), pszPath, vrc);
2702
2703 return setError (E_FAIL,
2704 tr ("Could not unmount the currently mounted media/drive (%Vrc)"), vrc);
2705}
2706
2707
2708/**
2709 * Performs the Floppy/DVD change in EMT.
2710 *
2711 * @returns VBox status code.
2712 *
2713 * @param pThis Pointer to the Console object.
2714 * @param pszDevice The PDM device name.
2715 * @param uInstance The PDM device instance.
2716 * @param uLun The PDM LUN number of the drive.
2717 * @param eState The new state.
2718 * @param peState Pointer to the variable keeping the actual state of the drive.
2719 * This will be both read and updated to eState or other appropriate state.
2720 * @param pszPath The path to the media / drive which is now being mounted / captured.
2721 * If NULL no media or drive is attached and the lun will be configured with
2722 * the default block driver with no media. This will also be the state if
2723 * mounting / capturing the specified media / drive fails.
2724 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2725 *
2726 * @thread EMT
2727 * @note Locks the Console object for writing
2728 */
2729DECLCALLBACK(int) Console::changeDrive (Console *pThis, const char *pszDevice, unsigned uInstance, unsigned uLun,
2730 DriveState_T eState, DriveState_T *peState,
2731 const char *pszPath, bool fPassthrough)
2732{
2733 LogFlowFunc (("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2734 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2735 pThis, pszDevice, pszDevice, uInstance, uLun, eState,
2736 peState, *peState, pszPath, pszPath, fPassthrough));
2737
2738 AssertReturn (pThis, VERR_INVALID_PARAMETER);
2739
2740 AssertMsg ( (!strcmp (pszDevice, "i82078") && uLun == 0 && uInstance == 0)
2741 || (!strcmp (pszDevice, "piix3ide") && uLun == 2 && uInstance == 0),
2742 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
2743
2744 AutoCaller autoCaller (pThis);
2745 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
2746
2747 /*
2748 * Locking the object before doing VMR3* calls is quite safe here,
2749 * since we're on EMT. Write lock is necessary because we're indirectly
2750 * modify the meDVDState/meFloppyState members (pointed to by peState).
2751 */
2752 AutoLock alock (pThis);
2753
2754 /* protect mpVM */
2755 AutoVMCaller autoVMCaller (pThis);
2756 CheckComRCReturnRC (autoVMCaller.rc());
2757
2758 PVM pVM = pThis->mpVM;
2759
2760 /*
2761 * Suspend the VM first.
2762 *
2763 * The VM must not be running since it might have pending I/O to
2764 * the drive which is being changed.
2765 */
2766 bool fResume;
2767 VMSTATE enmVMState = VMR3GetState (pVM);
2768 switch (enmVMState)
2769 {
2770 case VMSTATE_RESETTING:
2771 case VMSTATE_RUNNING:
2772 {
2773 LogFlowFunc (("Suspending the VM...\n"));
2774 /* disable the callback to prevent Console-level state change */
2775 pThis->mVMStateChangeCallbackDisabled = true;
2776 int rc = VMR3Suspend (pVM);
2777 pThis->mVMStateChangeCallbackDisabled = false;
2778 AssertRCReturn (rc, rc);
2779 fResume = true;
2780 break;
2781 }
2782
2783 case VMSTATE_SUSPENDED:
2784 case VMSTATE_CREATED:
2785 case VMSTATE_OFF:
2786 fResume = false;
2787 break;
2788
2789 default:
2790 AssertMsgFailedReturn (("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
2791 }
2792
2793 int rc = VINF_SUCCESS;
2794 int rcRet = VINF_SUCCESS;
2795
2796 do
2797 {
2798 /*
2799 * Unmount existing media / detach host drive.
2800 */
2801 PPDMIMOUNT pIMount = NULL;
2802 switch (*peState)
2803 {
2804
2805 case DriveState_ImageMounted:
2806 {
2807 /*
2808 * Resolve the interface.
2809 */
2810 PPDMIBASE pBase;
2811 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2812 if (VBOX_FAILURE (rc))
2813 {
2814 if (rc == VERR_PDM_LUN_NOT_FOUND)
2815 rc = VINF_SUCCESS;
2816 AssertRC (rc);
2817 break;
2818 }
2819
2820 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2821 AssertBreak (pIMount, rc = VERR_INVALID_POINTER);
2822
2823 /*
2824 * Unmount the media.
2825 */
2826 rc = pIMount->pfnUnmount (pIMount);
2827 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2828 rc = VINF_SUCCESS;
2829 break;
2830 }
2831
2832 case DriveState_HostDriveCaptured:
2833 {
2834 rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2835 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2836 rc = VINF_SUCCESS;
2837 AssertRC (rc);
2838 break;
2839 }
2840
2841 case DriveState_NotMounted:
2842 break;
2843
2844 default:
2845 AssertMsgFailed (("Invalid *peState: %d\n", peState));
2846 break;
2847 }
2848
2849 if (VBOX_FAILURE (rc))
2850 {
2851 rcRet = rc;
2852 break;
2853 }
2854
2855 /*
2856 * Nothing is currently mounted.
2857 */
2858 *peState = DriveState_NotMounted;
2859
2860
2861 /*
2862 * Process the HostDriveCaptured state first, as the fallback path
2863 * means mounting the normal block driver without media.
2864 */
2865 if (eState == DriveState_HostDriveCaptured)
2866 {
2867 /*
2868 * Detach existing driver chain (block).
2869 */
2870 int rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2871 if (VBOX_FAILURE (rc))
2872 {
2873 if (rc == VERR_PDM_LUN_NOT_FOUND)
2874 rc = VINF_SUCCESS;
2875 AssertReleaseRC (rc);
2876 break; /* we're toast */
2877 }
2878 pIMount = NULL;
2879
2880 /*
2881 * Construct a new driver configuration.
2882 */
2883 PCFGMNODE pInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2884 AssertRelease (pInst);
2885 /* nuke anything which might have been left behind. */
2886 CFGMR3RemoveNode (CFGMR3GetChildF (pInst, "LUN#%d", uLun));
2887
2888 /* create a new block driver config */
2889 PCFGMNODE pLunL0;
2890 PCFGMNODE pCfg;
2891 if ( VBOX_SUCCESS (rc = CFGMR3InsertNodeF (pInst, &pLunL0, "LUN#%u", uLun))
2892 && VBOX_SUCCESS (rc = CFGMR3InsertString (pLunL0, "Driver", !strcmp (pszDevice, "i82078") ? "HostFloppy" : "HostDVD"))
2893 && VBOX_SUCCESS (rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg))
2894 && VBOX_SUCCESS (rc = CFGMR3InsertString (pCfg, "Path", pszPath))
2895 && VBOX_SUCCESS (rc = !strcmp (pszDevice, "i82078") ? VINF_SUCCESS : CFGMR3InsertInteger(pCfg, "Passthrough", fPassthrough)))
2896 {
2897 /*
2898 * Attempt to attach the driver.
2899 */
2900 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, NULL);
2901 AssertRC (rc);
2902 }
2903 if (VBOX_FAILURE (rc))
2904 rcRet = rc;
2905 }
2906
2907 /*
2908 * Process the ImageMounted, NotMounted and failed HostDriveCapture cases.
2909 */
2910 rc = VINF_SUCCESS;
2911 switch (eState)
2912 {
2913#define RC_CHECK() do { if (VBOX_FAILURE (rc)) { AssertReleaseRC (rc); break; } } while (0)
2914
2915 case DriveState_HostDriveCaptured:
2916 if (VBOX_SUCCESS (rcRet))
2917 break;
2918 /* fallback: umounted block driver. */
2919 pszPath = NULL;
2920 eState = DriveState_NotMounted;
2921 /* fallthru */
2922 case DriveState_ImageMounted:
2923 case DriveState_NotMounted:
2924 {
2925 /*
2926 * Resolve the drive interface / create the driver.
2927 */
2928 if (!pIMount)
2929 {
2930 PPDMIBASE pBase;
2931 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2932 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2933 {
2934 /*
2935 * We have to create it, so we'll do the full config setup and everything.
2936 */
2937 PCFGMNODE pIdeInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2938 AssertRelease (pIdeInst);
2939
2940 /* nuke anything which might have been left behind. */
2941 CFGMR3RemoveNode (CFGMR3GetChildF (pIdeInst, "LUN#%d", uLun));
2942
2943 /* create a new block driver config */
2944 PCFGMNODE pLunL0;
2945 rc = CFGMR3InsertNodeF (pIdeInst, &pLunL0, "LUN#%d", uLun); RC_CHECK();
2946 rc = CFGMR3InsertString (pLunL0, "Driver", "Block"); RC_CHECK();
2947 PCFGMNODE pCfg;
2948 rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg); RC_CHECK();
2949 rc = CFGMR3InsertString (pCfg, "Type", !strcmp (pszDevice, "i82078") ? "Floppy 1.44" : "DVD");
2950 RC_CHECK();
2951 rc = CFGMR3InsertInteger (pCfg, "Mountable", 1); RC_CHECK();
2952
2953 /*
2954 * Attach the driver.
2955 */
2956 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, &pBase);
2957 RC_CHECK();
2958 }
2959 else if (VBOX_FAILURE(rc))
2960 {
2961 AssertRC (rc);
2962 return rc;
2963 }
2964
2965 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2966 if (!pIMount)
2967 {
2968 AssertFailed();
2969 return rc;
2970 }
2971 }
2972
2973 /*
2974 * If we've got an image, let's mount it.
2975 */
2976 if (pszPath && *pszPath)
2977 {
2978 rc = pIMount->pfnMount (pIMount, pszPath, strcmp (pszDevice, "i82078") ? "MediaISO" : "RawImage");
2979 if (VBOX_FAILURE (rc))
2980 eState = DriveState_NotMounted;
2981 }
2982 break;
2983 }
2984
2985 default:
2986 AssertMsgFailed (("Invalid eState: %d\n", eState));
2987 break;
2988
2989#undef RC_CHECK
2990 }
2991
2992 if (VBOX_FAILURE (rc) && VBOX_SUCCESS (rcRet))
2993 rcRet = rc;
2994
2995 *peState = eState;
2996 }
2997 while (0);
2998
2999 /*
3000 * Resume the VM if necessary.
3001 */
3002 if (fResume)
3003 {
3004 LogFlowFunc (("Resuming the VM...\n"));
3005 /* disable the callback to prevent Console-level state change */
3006 pThis->mVMStateChangeCallbackDisabled = true;
3007 rc = VMR3Resume (pVM);
3008 pThis->mVMStateChangeCallbackDisabled = false;
3009 AssertRC (rc);
3010 if (VBOX_FAILURE (rc))
3011 {
3012 /* too bad, we failed. try to sync the console state with the VMM state */
3013 vmstateChangeCallback (pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
3014 }
3015 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
3016 // error (if any) will be hidden from the caller. For proper reporting
3017 // of such multiple errors to the caller we need to enhance the
3018 // IVurtualBoxError interface. For now, give the first error the higher
3019 // priority.
3020 if (VBOX_SUCCESS (rcRet))
3021 rcRet = rc;
3022 }
3023
3024 LogFlowFunc (("Returning %Vrc\n", rcRet));
3025 return rcRet;
3026}
3027
3028
3029/**
3030 * Called by IInternalSessionControl::OnNetworkAdapterChange().
3031 *
3032 * @note Locks this object for writing.
3033 */
3034HRESULT Console::onNetworkAdapterChange(INetworkAdapter *networkAdapter)
3035{
3036 LogFlowThisFunc (("\n"));
3037
3038 AutoCaller autoCaller (this);
3039 AssertComRCReturnRC (autoCaller.rc());
3040
3041 AutoLock alock (this);
3042
3043 /* Don't do anything if the VM isn't running */
3044 if (!mpVM)
3045 return S_OK;
3046
3047 /* protect mpVM */
3048 AutoVMCaller autoVMCaller (this);
3049 CheckComRCReturnRC (autoVMCaller.rc());
3050
3051 /* Get the properties we need from the adapter */
3052 BOOL fCableConnected;
3053 HRESULT rc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected);
3054 AssertComRC(rc);
3055 if (SUCCEEDED(rc))
3056 {
3057 ULONG ulInstance;
3058 rc = networkAdapter->COMGETTER(Slot)(&ulInstance);
3059 AssertComRC(rc);
3060 if (SUCCEEDED(rc))
3061 {
3062 /*
3063 * Find the pcnet instance, get the config interface and update the link state.
3064 */
3065 PPDMIBASE pBase;
3066 int rcVBox = PDMR3QueryDeviceLun(mpVM, "pcnet", (unsigned)ulInstance, 0, &pBase);
3067 ComAssertRC(rcVBox);
3068 if (VBOX_SUCCESS(rcVBox))
3069 {
3070 Assert(pBase);
3071 PPDMINETWORKCONFIG pINetCfg = (PPDMINETWORKCONFIG)pBase->pfnQueryInterface(pBase, PDMINTERFACE_NETWORK_CONFIG);
3072 if (pINetCfg)
3073 {
3074 Log(("Console::onNetworkAdapterChange: setting link state to %d\n", fCableConnected));
3075 rcVBox = pINetCfg->pfnSetLinkState(pINetCfg, fCableConnected ? PDMNETWORKLINKSTATE_UP : PDMNETWORKLINKSTATE_DOWN);
3076 ComAssertRC(rcVBox);
3077 }
3078 }
3079 }
3080 }
3081
3082 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3083 return rc;
3084}
3085
3086/**
3087 * Called by IInternalSessionControl::OnVRDPServerChange().
3088 *
3089 * @note Locks this object for writing.
3090 */
3091HRESULT Console::onVRDPServerChange()
3092{
3093 AutoCaller autoCaller (this);
3094 AssertComRCReturnRC (autoCaller.rc());
3095
3096 AutoLock alock (this);
3097
3098 HRESULT rc = S_OK;
3099
3100 if (mVRDPServer && mMachineState == MachineState_Running)
3101 {
3102 BOOL vrdpEnabled = FALSE;
3103
3104 rc = mVRDPServer->COMGETTER(Enabled) (&vrdpEnabled);
3105 ComAssertComRCRetRC (rc);
3106
3107 if (vrdpEnabled)
3108 {
3109 // If there was no VRDP server started the 'stop' will do nothing.
3110 // However if a server was started and this notification was called,
3111 // we have to restart the server.
3112 mConsoleVRDPServer->Stop ();
3113
3114 if (VBOX_FAILURE(mConsoleVRDPServer->Launch ()))
3115 {
3116 rc = E_FAIL;
3117 }
3118 else
3119 {
3120 mConsoleVRDPServer->SetCallback ();
3121 }
3122 }
3123 else
3124 {
3125 mConsoleVRDPServer->Stop ();
3126 }
3127 }
3128
3129 return rc;
3130}
3131
3132/**
3133 * Called by IInternalSessionControl::OnUSBControllerChange().
3134 *
3135 * @note Locks this object for writing.
3136 */
3137HRESULT Console::onUSBControllerChange()
3138{
3139 LogFlowThisFunc (("\n"));
3140
3141 AutoCaller autoCaller (this);
3142 AssertComRCReturnRC (autoCaller.rc());
3143
3144 AutoLock alock (this);
3145
3146 /* Ignore if no VM is running yet. */
3147 if (!mpVM)
3148 return S_OK;
3149
3150/// @todo (dmik)
3151// check for the Enabled state and disable virtual USB controller??
3152// Anyway, if we want to query the machine's USB Controller we need to cache
3153// it to to mUSBController in #init() (as it is done with mDVDDrive).
3154//
3155// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
3156//
3157// /* protect mpVM */
3158// AutoVMCaller autoVMCaller (this);
3159// CheckComRCReturnRC (autoVMCaller.rc());
3160
3161 return S_OK;
3162}
3163
3164/**
3165 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
3166 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
3167 * returns TRUE for a given remote USB device.
3168 *
3169 * @return S_OK if the device was attached to the VM.
3170 * @return failure if not attached.
3171 *
3172 * @param aDevice
3173 * The device in question.
3174 *
3175 * @note Locks this object for writing.
3176 */
3177HRESULT Console::onUSBDeviceAttach (IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError)
3178{
3179 LogFlowThisFunc (("aDevice=%p aError=%p\n", aDevice, aError));
3180
3181 AutoCaller autoCaller (this);
3182 ComAssertComRCRetRC (autoCaller.rc());
3183
3184 AutoLock alock (this);
3185
3186 /* VM might have been stopped when this message arrives */
3187 if (mMachineState < MachineState_Running)
3188 {
3189 LogFlowThisFunc (("Attach request ignored (mMachineState=%d).\n",
3190 mMachineState));
3191 return E_FAIL;
3192 }
3193
3194 if (aError != NULL)
3195 {
3196 /* notify callback about an error */
3197 onUSBDeviceStateChange (aDevice, true /* aAttached */, aError);
3198 return S_OK;
3199 }
3200
3201 /* protect mpVM */
3202 AutoVMCaller autoVMCaller (this);
3203 CheckComRCReturnRC (autoVMCaller.rc());
3204
3205 /* Don't proceed unless we've found the usb controller. */
3206 PPDMIBASE pBase = NULL;
3207 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3208 if (VBOX_FAILURE (vrc))
3209 {
3210 LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
3211 return E_FAIL;
3212 }
3213
3214 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
3215 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
3216 ComAssertRet (pRhConfig, E_FAIL);
3217
3218 /// @todo notify listeners of IConsoleCallback in case of error
3219 return attachUSBDevice (aDevice, pRhConfig);
3220}
3221
3222/**
3223 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
3224 * processRemoteUSBDevices().
3225 *
3226 * @note Locks this object for writing.
3227 */
3228HRESULT Console::onUSBDeviceDetach (INPTR GUIDPARAM aId,
3229 IVirtualBoxErrorInfo *aError)
3230{
3231 Guid Uuid (aId);
3232 LogFlowThisFunc (("aId={%Vuuid} aError=%p\n", Uuid.raw(), aError));
3233
3234 AutoCaller autoCaller (this);
3235 AssertComRCReturnRC (autoCaller.rc());
3236
3237 AutoLock alock (this);
3238
3239 /* Find the device. */
3240 ComObjPtr <OUSBDevice> device;
3241 USBDeviceList::iterator it = mUSBDevices.begin();
3242 while (it != mUSBDevices.end())
3243 {
3244 LogFlowThisFunc (("it={%Vuuid}\n", (*it)->id().raw()));
3245 if ((*it)->id() == Uuid)
3246 {
3247 device = *it;
3248 break;
3249 }
3250 ++ it;
3251 }
3252
3253 /* VM might have been stopped when this message arrives */
3254 if (device.isNull())
3255 {
3256 LogFlowThisFunc (("Device not found.\n"));
3257 if (mMachineState < MachineState_Running)
3258 {
3259 LogFlowThisFunc (("Detach request ignored (mMachineState=%d).\n",
3260 mMachineState));
3261 return E_FAIL;
3262 }
3263 /* the device must be in the list */
3264 AssertFailedReturn (E_FAIL);
3265 }
3266
3267 if (aError != NULL)
3268 {
3269 /* notify callback about an error */
3270 onUSBDeviceStateChange (device, false /* aAttached */, aError);
3271 return S_OK;
3272 }
3273
3274 /* protect mpVM */
3275 AutoVMCaller autoVMCaller (this);
3276 CheckComRCReturnRC (autoVMCaller.rc());
3277
3278 PPDMIBASE pBase = NULL;
3279 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3280
3281 /* if the device is attached, then there must be a USB controller */
3282 AssertRCReturn (vrc, E_FAIL);
3283
3284 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
3285 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
3286 AssertReturn (pRhConfig, E_FAIL);
3287
3288 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n", Uuid.raw()));
3289
3290 /* leave the lock before a VMR3* call (EMT will call us back)! */
3291 alock.leave();
3292
3293 PVMREQ pReq;
3294 vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
3295 (PFNRT) usbDetachCallback, 5,
3296 this, &it, pRhConfig, Uuid.raw());
3297 if (VBOX_SUCCESS (vrc))
3298 vrc = pReq->iStatus;
3299 VMR3ReqFree (pReq);
3300
3301 AssertRC (vrc);
3302
3303 /// @todo notify listeners of IConsoleCallback in case of error
3304 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
3305}
3306
3307/**
3308 * Gets called by Session::UpdateMachineState()
3309 * (IInternalSessionControl::updateMachineState()).
3310 *
3311 * Must be called only in certain cases (see the implementation).
3312 *
3313 * @note Locks this object for writing.
3314 */
3315HRESULT Console::updateMachineState (MachineState_T aMachineState)
3316{
3317 AutoCaller autoCaller (this);
3318 AssertComRCReturnRC (autoCaller.rc());
3319
3320 AutoLock alock (this);
3321
3322 AssertReturn (mMachineState == MachineState_Saving ||
3323 mMachineState == MachineState_Discarding,
3324 E_FAIL);
3325
3326 return setMachineStateLocally (aMachineState);
3327}
3328
3329/**
3330 * @note Locks this object for writing.
3331 */
3332void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3333 uint32_t xHot, uint32_t yHot,
3334 uint32_t width, uint32_t height,
3335 void *pShape)
3336{
3337 LogFlowThisFuncEnter();
3338 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3339 "height=%d, shape=%p\n",
3340 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3341
3342 AutoCaller autoCaller (this);
3343 AssertComRCReturnVoid (autoCaller.rc());
3344
3345 /* We need a write lock because we alter the cached callback data */
3346 AutoLock alock (this);
3347
3348 /* Save the callback arguments */
3349 mCallbackData.mpsc.visible = fVisible;
3350 mCallbackData.mpsc.alpha = fAlpha;
3351 mCallbackData.mpsc.xHot = xHot;
3352 mCallbackData.mpsc.yHot = yHot;
3353 mCallbackData.mpsc.width = width;
3354 mCallbackData.mpsc.height = height;
3355
3356 /* start with not valid */
3357 bool wasValid = mCallbackData.mpsc.valid;
3358 mCallbackData.mpsc.valid = false;
3359
3360 if (pShape != NULL)
3361 {
3362 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3363 cb += ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3364 /* try to reuse the old shape buffer if the size is the same */
3365 if (!wasValid)
3366 mCallbackData.mpsc.shape = NULL;
3367 else
3368 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3369 {
3370 RTMemFree (mCallbackData.mpsc.shape);
3371 mCallbackData.mpsc.shape = NULL;
3372 }
3373 if (mCallbackData.mpsc.shape == NULL)
3374 {
3375 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3376 AssertReturnVoid (mCallbackData.mpsc.shape);
3377 }
3378 mCallbackData.mpsc.shapeSize = cb;
3379 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3380 }
3381 else
3382 {
3383 if (wasValid && mCallbackData.mpsc.shape != NULL)
3384 RTMemFree (mCallbackData.mpsc.shape);
3385 mCallbackData.mpsc.shape = NULL;
3386 mCallbackData.mpsc.shapeSize = 0;
3387 }
3388
3389 mCallbackData.mpsc.valid = true;
3390
3391 CallbackList::iterator it = mCallbacks.begin();
3392 while (it != mCallbacks.end())
3393 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3394 width, height, (BYTE *) pShape);
3395
3396 LogFlowThisFuncLeave();
3397}
3398
3399/**
3400 * @note Locks this object for writing.
3401 */
3402void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3403{
3404 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3405 supportsAbsolute, needsHostCursor));
3406
3407 AutoCaller autoCaller (this);
3408 AssertComRCReturnVoid (autoCaller.rc());
3409
3410 /* We need a write lock because we alter the cached callback data */
3411 AutoLock alock (this);
3412
3413 /* save the callback arguments */
3414 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3415 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3416 mCallbackData.mcc.valid = true;
3417
3418 CallbackList::iterator it = mCallbacks.begin();
3419 while (it != mCallbacks.end())
3420 {
3421 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3422 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3423 }
3424}
3425
3426/**
3427 * @note Locks this object for reading.
3428 */
3429void Console::onStateChange (MachineState_T machineState)
3430{
3431 AutoCaller autoCaller (this);
3432 AssertComRCReturnVoid (autoCaller.rc());
3433
3434 AutoReaderLock alock (this);
3435
3436 CallbackList::iterator it = mCallbacks.begin();
3437 while (it != mCallbacks.end())
3438 (*it++)->OnStateChange (machineState);
3439}
3440
3441/**
3442 * @note Locks this object for reading.
3443 */
3444void Console::onAdditionsStateChange()
3445{
3446 AutoCaller autoCaller (this);
3447 AssertComRCReturnVoid (autoCaller.rc());
3448
3449 AutoReaderLock alock (this);
3450
3451 CallbackList::iterator it = mCallbacks.begin();
3452 while (it != mCallbacks.end())
3453 (*it++)->OnAdditionsStateChange();
3454}
3455
3456/**
3457 * @note Locks this object for reading.
3458 */
3459void Console::onAdditionsOutdated()
3460{
3461 AutoCaller autoCaller (this);
3462 AssertComRCReturnVoid (autoCaller.rc());
3463
3464 AutoReaderLock alock (this);
3465
3466 /** @todo Use the On-Screen Display feature to report the fact.
3467 * The user should be told to install additions that are
3468 * provided with the current VBox build:
3469 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3470 */
3471}
3472
3473/**
3474 * @note Locks this object for writing.
3475 */
3476void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3477{
3478 AutoCaller autoCaller (this);
3479 AssertComRCReturnVoid (autoCaller.rc());
3480
3481 /* We need a write lock because we alter the cached callback data */
3482 AutoLock alock (this);
3483
3484 /* save the callback arguments */
3485 mCallbackData.klc.numLock = fNumLock;
3486 mCallbackData.klc.capsLock = fCapsLock;
3487 mCallbackData.klc.scrollLock = fScrollLock;
3488 mCallbackData.klc.valid = true;
3489
3490 CallbackList::iterator it = mCallbacks.begin();
3491 while (it != mCallbacks.end())
3492 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3493}
3494
3495/**
3496 * @note Locks this object for reading.
3497 */
3498void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
3499 IVirtualBoxErrorInfo *aError)
3500{
3501 AutoCaller autoCaller (this);
3502 AssertComRCReturnVoid (autoCaller.rc());
3503
3504 AutoReaderLock alock (this);
3505
3506 CallbackList::iterator it = mCallbacks.begin();
3507 while (it != mCallbacks.end())
3508 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
3509}
3510
3511/**
3512 * @note Locks this object for reading.
3513 */
3514void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3515{
3516 AutoCaller autoCaller (this);
3517 AssertComRCReturnVoid (autoCaller.rc());
3518
3519 AutoReaderLock alock (this);
3520
3521 CallbackList::iterator it = mCallbacks.begin();
3522 while (it != mCallbacks.end())
3523 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3524}
3525
3526/**
3527 * @note Locks this object for reading.
3528 */
3529HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
3530{
3531 AssertReturn (aCanShow, E_POINTER);
3532 AssertReturn (aWinId, E_POINTER);
3533
3534 *aCanShow = FALSE;
3535 *aWinId = 0;
3536
3537 AutoCaller autoCaller (this);
3538 AssertComRCReturnRC (autoCaller.rc());
3539
3540 AutoReaderLock alock (this);
3541
3542 HRESULT rc = S_OK;
3543 CallbackList::iterator it = mCallbacks.begin();
3544
3545 if (aCheck)
3546 {
3547 while (it != mCallbacks.end())
3548 {
3549 BOOL canShow = FALSE;
3550 rc = (*it++)->OnCanShowWindow (&canShow);
3551 AssertComRC (rc);
3552 if (FAILED (rc) || !canShow)
3553 return rc;
3554 }
3555 *aCanShow = TRUE;
3556 }
3557 else
3558 {
3559 while (it != mCallbacks.end())
3560 {
3561 ULONG64 winId = 0;
3562 rc = (*it++)->OnShowWindow (&winId);
3563 AssertComRC (rc);
3564 if (FAILED (rc))
3565 return rc;
3566 /* only one callback may return non-null winId */
3567 Assert (*aWinId == 0 || winId == 0);
3568 if (*aWinId == 0)
3569 *aWinId = winId;
3570 }
3571 }
3572
3573 return S_OK;
3574}
3575
3576// private mehtods
3577////////////////////////////////////////////////////////////////////////////////
3578
3579/**
3580 * Increases the usage counter of the mpVM pointer. Guarantees that
3581 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
3582 * is called.
3583 *
3584 * If this method returns a failure, the caller is not allowed to use mpVM
3585 * and may return the failed result code to the upper level. This method sets
3586 * the extended error info on failure if \a aQuiet is false.
3587 *
3588 * Setting \a aQuiet to true is useful for methods that don't want to return
3589 * the failed result code to the caller when this method fails (e.g. need to
3590 * silently check for the mpVM avaliability).
3591 *
3592 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
3593 * returned instead of asserting. Having it false is intended as a sanity check
3594 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
3595 *
3596 * @param aQuiet true to suppress setting error info
3597 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
3598 * (otherwise this method will assert if mpVM is NULL)
3599 *
3600 * @note Locks this object for writing.
3601 */
3602HRESULT Console::addVMCaller (bool aQuiet /* = false */,
3603 bool aAllowNullVM /* = false */)
3604{
3605 AutoCaller autoCaller (this);
3606 AssertComRCReturnRC (autoCaller.rc());
3607
3608 AutoLock alock (this);
3609
3610 if (mVMDestroying)
3611 {
3612 /* powerDown() is waiting for all callers to finish */
3613 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3614 tr ("Virtual machine is being powered down"));
3615 }
3616
3617 if (mpVM == NULL)
3618 {
3619 Assert (aAllowNullVM == true);
3620
3621 /* The machine is not powered up */
3622 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3623 tr ("Virtual machine is not powered up"));
3624 }
3625
3626 ++ mVMCallers;
3627
3628 return S_OK;
3629}
3630
3631/**
3632 * Decreases the usage counter of the mpVM pointer. Must always complete
3633 * the addVMCaller() call after the mpVM pointer is no more necessary.
3634 *
3635 * @note Locks this object for writing.
3636 */
3637void Console::releaseVMCaller()
3638{
3639 AutoCaller autoCaller (this);
3640 AssertComRCReturnVoid (autoCaller.rc());
3641
3642 AutoLock alock (this);
3643
3644 AssertReturnVoid (mpVM != NULL);
3645
3646 Assert (mVMCallers > 0);
3647 -- mVMCallers;
3648
3649 if (mVMCallers == 0 && mVMDestroying)
3650 {
3651 /* inform powerDown() there are no more callers */
3652 RTSemEventSignal (mVMZeroCallersSem);
3653 }
3654}
3655
3656/**
3657 * Internal power off worker routine.
3658 *
3659 * This method may be called only at certain places with the folliwing meaning
3660 * as shown below:
3661 *
3662 * - if the machine state is either Running or Paused, a normal
3663 * Console-initiated powerdown takes place (e.g. PowerDown());
3664 * - if the machine state is Saving, saveStateThread() has successfully
3665 * done its job;
3666 * - if the machine state is Starting or Restoring, powerUpThread() has
3667 * failed to start/load the VM;
3668 * - if the machine state is Stopping, the VM has powered itself off
3669 * (i.e. not as a result of the powerDown() call).
3670 *
3671 * Calling it in situations other than the above will cause unexpected
3672 * behavior.
3673 *
3674 * Note that this method should be the only one that destroys mpVM and sets
3675 * it to NULL.
3676 *
3677 * @note Locks this object for writing.
3678 *
3679 * @note Never call this method from a thread that called addVMCaller() or
3680 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
3681 * release(). Otherwise it will deadlock.
3682 */
3683HRESULT Console::powerDown()
3684{
3685 LogFlowThisFuncEnter();
3686
3687 AutoCaller autoCaller (this);
3688 AssertComRCReturnRC (autoCaller.rc());
3689
3690 AutoLock alock (this);
3691
3692 /* sanity */
3693 AssertReturn (mVMDestroying == false, E_FAIL);
3694
3695 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
3696 "(mMachineState=%d, InUninit=%d)\n",
3697 mMachineState, autoCaller.state() == InUninit));
3698
3699 /* First, wait for all mpVM callers to finish their work if necessary */
3700 if (mVMCallers > 0)
3701 {
3702 /* go to the destroying state to prevent from adding new callers */
3703 mVMDestroying = true;
3704
3705 /* lazy creation */
3706 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
3707 RTSemEventCreate (&mVMZeroCallersSem);
3708
3709 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
3710 mVMCallers));
3711
3712 alock.leave();
3713
3714 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
3715
3716 alock.enter();
3717 }
3718
3719 AssertReturn (mpVM, E_FAIL);
3720
3721 AssertMsg (mMachineState == MachineState_Running ||
3722 mMachineState == MachineState_Paused ||
3723 mMachineState == MachineState_Saving ||
3724 mMachineState == MachineState_Starting ||
3725 mMachineState == MachineState_Restoring ||
3726 mMachineState == MachineState_Stopping,
3727 ("Invalid machine state: %d\n", mMachineState));
3728
3729 HRESULT rc = S_OK;
3730 int vrc = VINF_SUCCESS;
3731
3732 /*
3733 * Power off the VM if not already done that. In case of Stopping, the VM
3734 * has powered itself off and notified Console in vmstateChangeCallback().
3735 * In case of Starting or Restoring, powerUpThread() is calling us on
3736 * failure, so the VM is already off at that point.
3737 */
3738 if (mMachineState != MachineState_Stopping &&
3739 mMachineState != MachineState_Starting &&
3740 mMachineState != MachineState_Restoring)
3741 {
3742 /*
3743 * don't go from Saving to Stopping, vmstateChangeCallback needs it
3744 * to set the state to Saved on VMSTATE_TERMINATED.
3745 */
3746 if (mMachineState != MachineState_Saving)
3747 setMachineState (MachineState_Stopping);
3748
3749 LogFlowThisFunc (("Powering off the VM...\n"));
3750
3751 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
3752 alock.leave();
3753
3754 vrc = VMR3PowerOff (mpVM);
3755 /*
3756 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
3757 * VM-(guest-)initiated power off happened in parallel a ms before
3758 * this call. So far, we let this error pop up on the user's side.
3759 */
3760
3761 alock.enter();
3762 }
3763
3764 LogFlowThisFunc (("Ready for VM destruction\n"));
3765
3766 /*
3767 * If we are called from Console::uninit(), then try to destroy the VM
3768 * even on failure (this will most likely fail too, but what to do?..)
3769 */
3770 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
3771 {
3772 /*
3773 * Stop the VRDP server and release all USB device.
3774 * (When called from uninit mConsoleVRDPServer is already destroyed.)
3775 */
3776 if (mConsoleVRDPServer)
3777 {
3778 LogFlowThisFunc (("Stopping VRDP server...\n"));
3779
3780 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
3781 alock.leave();
3782
3783 mConsoleVRDPServer->Stop();
3784
3785 alock.enter();
3786 }
3787
3788 /* If the machine has an USB comtroller, release all USB devices
3789 * (symmectric to the code in captureUSBDevices()) */
3790 {
3791 PPDMIBASE pBase;
3792 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3793 if (VBOX_SUCCESS (vrc))
3794 releaseAllUSBDevices();
3795 }
3796
3797 /*
3798 * Now we've got to destroy the VM as well. (mpVM is not valid
3799 * beyond this point). We leave the lock before calling VMR3Destroy()
3800 * because it will result into calling destructors of drivers
3801 * associated with Console children which may in turn try to lock
3802 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
3803 * here because mVMDestroying is set which should prevent any activity.
3804 */
3805
3806 /*
3807 * Set mpVM to NULL early just in case if some old code is not using
3808 * addVMCaller()/releaseVMCaller().
3809 */
3810 PVM pVM = mpVM;
3811 mpVM = NULL;
3812
3813 LogFlowThisFunc (("Destroying the VM...\n"));
3814
3815 alock.leave();
3816
3817 vrc = VMR3Destroy (pVM);
3818
3819 /* take the lock again */
3820 alock.enter();
3821
3822 if (VBOX_SUCCESS (vrc))
3823 {
3824 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
3825 mMachineState));
3826 /*
3827 * Note: the Console-level machine state change happens on the
3828 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
3829 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
3830 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
3831 * occured yet. This is okay, because mMachineState is already
3832 * Stopping in this case, so any other attempt to call PowerDown()
3833 * will be rejected.
3834 */
3835 }
3836 else
3837 {
3838 /* bad bad bad, but what to do? */
3839 mpVM = pVM;
3840 rc = setError (E_FAIL,
3841 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
3842 }
3843 }
3844 else
3845 {
3846 rc = setError (E_FAIL,
3847 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
3848 }
3849
3850 /*
3851 * Finished with destruction. Note that if something impossible happened
3852 * and we've failed to destroy the VM, mVMDestroying will remain false and
3853 * mMachineState will be something like Stopping, so most Console methods
3854 * will return an error to the caller.
3855 */
3856 if (mpVM == NULL)
3857 mVMDestroying = false;
3858
3859 if (SUCCEEDED (rc))
3860 {
3861 /* uninit dynamically allocated members of mCallbackData */
3862 if (mCallbackData.mpsc.valid)
3863 {
3864 if (mCallbackData.mpsc.shape != NULL)
3865 RTMemFree (mCallbackData.mpsc.shape);
3866 }
3867 memset (&mCallbackData, 0, sizeof (mCallbackData));
3868 }
3869
3870 LogFlowThisFuncLeave();
3871 return rc;
3872}
3873
3874/**
3875 * @note Locks this object for writing.
3876 */
3877HRESULT Console::setMachineState (MachineState_T aMachineState,
3878 bool aUpdateServer /* = true */)
3879{
3880 AutoCaller autoCaller (this);
3881 AssertComRCReturnRC (autoCaller.rc());
3882
3883 AutoLock alock (this);
3884
3885 HRESULT rc = S_OK;
3886
3887 if (mMachineState != aMachineState)
3888 {
3889 LogFlowThisFunc (("machineState=%d\n", aMachineState));
3890 mMachineState = aMachineState;
3891
3892 /// @todo (dmik)
3893 // possibly, we need to redo onStateChange() using the dedicated
3894 // Event thread, like it is done in VirtualBox. This will make it
3895 // much safer (no deadlocks possible if someone tries to use the
3896 // console from the callback), however, listeners will lose the
3897 // ability to synchronously react to state changes (is it really
3898 // necessary??)
3899 LogFlowThisFunc (("Doing onStateChange()...\n"));
3900 onStateChange (aMachineState);
3901 LogFlowThisFunc (("Done onStateChange()\n"));
3902
3903 if (aUpdateServer)
3904 {
3905 /*
3906 * Server notification MUST be done from under the lock; otherwise
3907 * the machine state here and on the server might go out of sync, that
3908 * can lead to various unexpected results (like the machine state being
3909 * >= MachineState_Running on the server, while the session state is
3910 * already SessionState_SessionClosed at the same time there).
3911 *
3912 * Cross-lock conditions should be carefully watched out: calling
3913 * UpdateState we will require Machine and SessionMachine locks
3914 * (remember that here we're holding the Console lock here, and
3915 * also all locks that have been entered by the thread before calling
3916 * this method).
3917 */
3918 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
3919 rc = mControl->UpdateState (aMachineState);
3920 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
3921 }
3922 }
3923
3924 return rc;
3925}
3926
3927/**
3928 * Searches for a shared folder with the given logical name
3929 * in the collection of shared folders.
3930 *
3931 * @param aName logical name of the shared folder
3932 * @param aSharedFolder where to return the found object
3933 * @param aSetError whether to set the error info if the folder is
3934 * not found
3935 * @return
3936 * S_OK when found or E_INVALIDARG when not found
3937 *
3938 * @note The caller must lock this object for writing.
3939 */
3940HRESULT Console::findSharedFolder (const BSTR aName,
3941 ComObjPtr <SharedFolder> &aSharedFolder,
3942 bool aSetError /* = false */)
3943{
3944 /* sanity check */
3945 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
3946
3947 bool found = false;
3948 for (SharedFolderList::const_iterator it = mSharedFolders.begin();
3949 !found && it != mSharedFolders.end();
3950 ++ it)
3951 {
3952 AutoLock alock (*it);
3953 found = (*it)->name() == aName;
3954 if (found)
3955 aSharedFolder = *it;
3956 }
3957
3958 HRESULT rc = found ? S_OK : E_INVALIDARG;
3959
3960 if (aSetError && !found)
3961 setError (rc, tr ("Could not find a shared folder named '%ls'."), aName);
3962
3963 return rc;
3964}
3965
3966/**
3967 * VM state callback function. Called by the VMM
3968 * using its state machine states.
3969 *
3970 * Primarily used to handle VM initiated power off, suspend and state saving,
3971 * but also for doing termination completed work (VMSTATE_TERMINATE).
3972 *
3973 * In general this function is called in the context of the EMT.
3974 *
3975 * @param aVM The VM handle.
3976 * @param aState The new state.
3977 * @param aOldState The old state.
3978 * @param aUser The user argument (pointer to the Console object).
3979 *
3980 * @note Locks the Console object for writing.
3981 */
3982DECLCALLBACK(void)
3983Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
3984 void *aUser)
3985{
3986 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
3987 aOldState, aState, aVM));
3988
3989 Console *that = static_cast <Console *> (aUser);
3990 AssertReturnVoid (that);
3991
3992 AutoCaller autoCaller (that);
3993 /*
3994 * Note that we must let this method proceed even if Console::uninit() has
3995 * been already called. In such case this VMSTATE change is a result of:
3996 * 1) powerDown() called from uninit() itself, or
3997 * 2) VM-(guest-)initiated power off.
3998 */
3999 AssertReturnVoid (autoCaller.isOk() ||
4000 autoCaller.state() == InUninit);
4001
4002 switch (aState)
4003 {
4004 /*
4005 * The VM has terminated
4006 */
4007 case VMSTATE_OFF:
4008 {
4009 AutoLock alock (that);
4010
4011 if (that->mVMStateChangeCallbackDisabled)
4012 break;
4013
4014 /*
4015 * Do we still think that it is running? It may happen if this is
4016 * a VM-(guest-)initiated shutdown/poweroff.
4017 */
4018 if (that->mMachineState != MachineState_Stopping &&
4019 that->mMachineState != MachineState_Saving &&
4020 that->mMachineState != MachineState_Restoring)
4021 {
4022 LogFlowFunc (("VM has powered itself off but Console still "
4023 "thinks it is running. Notifying.\n"));
4024
4025 /* prevent powerDown() from calling VMR3PowerOff() again */
4026 that->setMachineState (MachineState_Stopping);
4027
4028 /*
4029 * Setup task object and thread to carry out the operation
4030 * asynchronously (if we call powerDown() right here but there
4031 * is one or more mpVM callers (added with addVMCaller()) we'll
4032 * deadlock.
4033 */
4034 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
4035 /*
4036 * If creating a task is falied, this can currently mean one
4037 * of two: either Console::uninit() has been called just a ms
4038 * before (so a powerDown() call is already on the way), or
4039 * powerDown() itself is being already executed. Just do
4040 * nothing .
4041 */
4042 if (!task->isOk())
4043 {
4044 LogFlowFunc (("Console is already being uninitialized.\n"));
4045 break;
4046 }
4047
4048 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
4049 (void *) task.get(), 0,
4050 RTTHREADTYPE_MAIN_WORKER, 0,
4051 "VMPowerDowm");
4052
4053 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
4054 if (VBOX_FAILURE (vrc))
4055 break;
4056
4057 /* task is now owned by powerDownThread(), so release it */
4058 task.release();
4059 }
4060 break;
4061 }
4062
4063 /*
4064 * The VM has been completely destroyed.
4065 *
4066 * Note: This state change can happen at two points:
4067 * 1) At the end of VMR3Destroy() if it was not called from EMT.
4068 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
4069 * called by EMT.
4070 */
4071 case VMSTATE_TERMINATED:
4072 {
4073 AutoLock alock (that);
4074
4075 if (that->mVMStateChangeCallbackDisabled)
4076 break;
4077
4078 /*
4079 * Terminate host interface networking. If aVM is NULL, we've been
4080 * manually called from powerUpThread() either before calling
4081 * VMR3Create() or after VMR3Create() failed, so no need to touch
4082 * networking.
4083 */
4084 if (aVM)
4085 that->powerDownHostInterfaces();
4086
4087 /*
4088 * From now on the machine is officially powered down or
4089 * remains in the Saved state.
4090 */
4091 switch (that->mMachineState)
4092 {
4093 default:
4094 AssertFailed();
4095 /* fall through */
4096 case MachineState_Stopping:
4097 /* successfully powered down */
4098 that->setMachineState (MachineState_PoweredOff);
4099 break;
4100 case MachineState_Saving:
4101 /*
4102 * successfully saved (note that the machine is already
4103 * in the Saved state on the server due to EndSavingState()
4104 * called from saveStateThread(), so only change the local
4105 * state)
4106 */
4107 that->setMachineStateLocally (MachineState_Saved);
4108 break;
4109 case MachineState_Starting:
4110 /*
4111 * failed to start, but be patient: set back to PoweredOff
4112 * (for similarity with the below)
4113 */
4114 that->setMachineState (MachineState_PoweredOff);
4115 break;
4116 case MachineState_Restoring:
4117 /*
4118 * failed to load the saved state file, but be patient:
4119 * set back to Saved (to preserve the saved state file)
4120 */
4121 that->setMachineState (MachineState_Saved);
4122 break;
4123 }
4124
4125 break;
4126 }
4127
4128 case VMSTATE_SUSPENDED:
4129 {
4130 if (aOldState == VMSTATE_RUNNING)
4131 {
4132 AutoLock alock (that);
4133
4134 if (that->mVMStateChangeCallbackDisabled)
4135 break;
4136
4137 /* Change the machine state from Running to Paused */
4138 Assert (that->mMachineState == MachineState_Running);
4139 that->setMachineState (MachineState_Paused);
4140 }
4141 }
4142
4143 case VMSTATE_RUNNING:
4144 {
4145 if (aOldState == VMSTATE_CREATED ||
4146 aOldState == VMSTATE_SUSPENDED)
4147 {
4148 AutoLock alock (that);
4149
4150 if (that->mVMStateChangeCallbackDisabled)
4151 break;
4152
4153 /*
4154 * Change the machine state from Starting, Restoring or Paused
4155 * to Running
4156 */
4157 Assert ((that->mMachineState == MachineState_Starting &&
4158 aOldState == VMSTATE_CREATED) ||
4159 ((that->mMachineState == MachineState_Restoring ||
4160 that->mMachineState == MachineState_Paused) &&
4161 aOldState == VMSTATE_SUSPENDED));
4162
4163 that->setMachineState (MachineState_Running);
4164 }
4165 }
4166
4167 default: /* shut up gcc */
4168 break;
4169 }
4170}
4171
4172/**
4173 * Sends a request to VMM to attach the given host device.
4174 * After this method succeeds, the attached device will appear in the
4175 * mUSBDevices collection.
4176 *
4177 * @param aHostDevice device to attach
4178 *
4179 * @note Locks this object for writing.
4180 * @note Synchronously calls EMT.
4181 */
4182HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, PVUSBIRHCONFIG aConfig)
4183{
4184 AssertReturn (aHostDevice && aConfig, E_FAIL);
4185
4186 AutoLock alock (this);
4187
4188 HRESULT hrc;
4189
4190 /*
4191 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
4192 * method in EMT (using usbAttachCallback()).
4193 */
4194 Bstr BstrAddress;
4195 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
4196 ComAssertComRCRetRC (hrc);
4197
4198 Utf8Str Address (BstrAddress);
4199
4200 Guid Uuid;
4201 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
4202 ComAssertComRCRetRC (hrc);
4203
4204 BOOL fRemote = FALSE;
4205 void *pvRemote = NULL;
4206
4207 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
4208 ComAssertComRCRetRC (hrc);
4209
4210#ifndef VRDP_MC
4211 if (fRemote)
4212 {
4213 pvRemote = mConsoleVRDPServer->GetUSBBackendPointer ();
4214 ComAssertRet (pvRemote, E_FAIL);
4215 }
4216#endif /* !VRDP_MC */
4217
4218 /* protect mpVM */
4219 AutoVMCaller autoVMCaller (this);
4220 CheckComRCReturnRC (autoVMCaller.rc());
4221
4222 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
4223 Address.raw(), Uuid.ptr()));
4224
4225 /* leave the lock before a VMR3* call (EMT will call us back)! */
4226 alock.leave();
4227
4228 PVMREQ pReq = NULL;
4229 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4230 (PFNRT) usbAttachCallback, 7,
4231 this, aHostDevice,
4232 aConfig, Uuid.ptr(), fRemote, Address.raw(), pvRemote);
4233 if (VBOX_SUCCESS (vrc))
4234 vrc = pReq->iStatus;
4235 VMR3ReqFree (pReq);
4236
4237 /* restore the lock */
4238 alock.enter();
4239
4240 /* hrc is S_OK here */
4241
4242 if (VBOX_FAILURE (vrc))
4243 {
4244 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
4245 Address.raw(), Uuid.ptr(), vrc));
4246
4247 switch (vrc)
4248 {
4249 case VERR_VUSB_NO_PORTS:
4250 hrc = setError (E_FAIL,
4251 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
4252 break;
4253 case VERR_VUSB_USBFS_PERMISSION:
4254 hrc = setError (E_FAIL,
4255 tr ("Not permitted to open the USB device, check usbfs options"));
4256 break;
4257 default:
4258 hrc = setError (E_FAIL,
4259 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
4260 break;
4261 }
4262 }
4263
4264 return hrc;
4265}
4266
4267/**
4268 * USB device attach callback used by AttachUSBDevice().
4269 * Note that AttachUSBDevice() doesn't return until this callback is executed,
4270 * so we don't use AutoCaller and don't care about reference counters of
4271 * interface pointers passed in.
4272 *
4273 * @thread EMT
4274 * @note Locks the console object for writing.
4275 */
4276//static
4277DECLCALLBACK(int)
4278Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice,
4279 PVUSBIRHCONFIG aConfig, PCRTUUID aUuid, bool aRemote,
4280 const char *aAddress, void *aRemoteBackend)
4281{
4282 LogFlowFuncEnter();
4283 LogFlowFunc (("that={%p}\n", that));
4284
4285 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4286
4287#ifdef VRDP_MC
4288 if (aRemote)
4289 {
4290 /* @todo aRemoteBackend input parameter is not needed. */
4291 Assert (aRemoteBackend == NULL);
4292
4293 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
4294
4295 Guid guid (*aUuid);
4296
4297 aRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
4298
4299 if (aRemoteBackend == NULL)
4300 {
4301 /* The clientId is invalid then. */
4302 return VERR_INVALID_PARAMETER;
4303 }
4304 }
4305#endif /* VRDP_MC */
4306
4307 int vrc = aConfig->pfnCreateProxyDevice (aConfig, aUuid, aRemote, aAddress,
4308 aRemoteBackend);
4309
4310 if (VBOX_SUCCESS (vrc))
4311 {
4312 /* Create a OUSBDevice and add it to the device list */
4313 ComObjPtr <OUSBDevice> device;
4314 device.createObject();
4315 HRESULT hrc = device->init (aHostDevice);
4316 AssertComRC (hrc);
4317
4318 AutoLock alock (that);
4319 that->mUSBDevices.push_back (device);
4320 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
4321
4322 /* notify callbacks */
4323 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
4324 }
4325
4326 LogFlowFunc (("vrc=%Vrc\n", vrc));
4327 LogFlowFuncLeave();
4328 return vrc;
4329}
4330
4331/**
4332 * USB device detach callback used by DetachUSBDevice().
4333 * Note that DetachUSBDevice() doesn't return until this callback is executed,
4334 * so we don't use AutoCaller and don't care about reference counters of
4335 * interface pointers passed in.
4336 *
4337 * @thread EMT
4338 * @note Locks the console object for writing.
4339 */
4340//static
4341DECLCALLBACK(int)
4342Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt,
4343 PVUSBIRHCONFIG aConfig, PCRTUUID aUuid)
4344{
4345 LogFlowFuncEnter();
4346 LogFlowFunc (("that={%p}\n", that));
4347
4348 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4349
4350#ifdef VRDP_MC
4351 /*
4352 * If that was a remote device, release the backend pointer.
4353 * The pointer was requested in usbAttachCallback.
4354 */
4355 BOOL fRemote = FALSE;
4356
4357 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
4358 ComAssertComRC (hrc2);
4359
4360 if (fRemote)
4361 {
4362 Guid guid (*aUuid);
4363 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
4364 }
4365#endif /* VRDP_MC */
4366
4367 int vrc = aConfig->pfnDestroyProxyDevice (aConfig, aUuid);
4368
4369 if (VBOX_SUCCESS (vrc))
4370 {
4371 AutoLock alock (that);
4372
4373 /* Remove the device from the collection */
4374 that->mUSBDevices.erase (*aIt);
4375 LogFlowFunc (("Detached device {%Vuuid}\n", (**aIt)->id().raw()));
4376
4377 /* notify callbacks */
4378 that->onUSBDeviceStateChange (**aIt, false /* aAttached */, NULL);
4379 }
4380
4381 LogFlowFunc (("vrc=%Vrc\n", vrc));
4382 LogFlowFuncLeave();
4383 return vrc;
4384}
4385
4386/**
4387 * Construct the VM configuration tree (CFGM).
4388 *
4389 * This is a callback for VMR3Create() call. It is called from CFGMR3Init()
4390 * in the emulation thread (EMT). Any per thread COM/XPCOM initialization
4391 * is done here.
4392 *
4393 * @param pVM VM handle.
4394 * @param pvTask Pointer to the VMPowerUpTask object.
4395 * @return VBox status code.
4396 *
4397 * @note Locks the Console object for writing.
4398 */
4399DECLCALLBACK(int) Console::configConstructor(PVM pVM, void *pvTask)
4400{
4401 LogFlowFuncEnter();
4402
4403 /* Note: the task pointer is owned by powerUpThread() */
4404 VMPowerUpTask *task = static_cast <VMPowerUpTask *> (pvTask);
4405 AssertReturn (task, VERR_GENERAL_FAILURE);
4406
4407#if defined(__WIN__)
4408 {
4409 /* initialize COM */
4410 HRESULT hrc = CoInitializeEx(NULL,
4411 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
4412 COINIT_SPEED_OVER_MEMORY);
4413 LogFlow (("Console::configConstructor(): CoInitializeEx()=%08X\n", hrc));
4414 AssertComRCReturn (hrc, VERR_GENERAL_FAILURE);
4415 }
4416#endif
4417
4418 ComObjPtr <Console> pConsole = task->mConsole;
4419
4420 AutoCaller autoCaller (pConsole);
4421 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
4422
4423 /* lock the console because we widely use internal fields and methods */
4424 AutoLock alock (pConsole);
4425
4426 ComPtr <IMachine> pMachine = pConsole->machine();
4427
4428 int rc;
4429 HRESULT hrc;
4430 char *psz = NULL;
4431 BSTR str = NULL;
4432 ULONG cRamMBs;
4433 ULONG cMonitors;
4434 unsigned i;
4435
4436#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
4437#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
4438#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
4439#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); return VERR_GENERAL_FAILURE; } } while (0)
4440
4441 /* Get necessary objects */
4442
4443 ComPtr<IVirtualBox> virtualBox;
4444 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
4445
4446 ComPtr<IHost> host;
4447 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
4448
4449 ComPtr <ISystemProperties> systemProperties;
4450 hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam()); H();
4451
4452 ComPtr<IBIOSSettings> biosSettings;
4453 hrc = pMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam()); H();
4454
4455
4456 /*
4457 * Get root node first.
4458 * This is the only node in the tree.
4459 */
4460 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4461 Assert(pRoot);
4462
4463 /*
4464 * Set the root level values.
4465 */
4466 hrc = pMachine->COMGETTER(Name)(&str); H();
4467 STR_CONV();
4468 rc = CFGMR3InsertString(pRoot, "Name", psz); RC_CHECK();
4469 STR_FREE();
4470 hrc = pMachine->COMGETTER(MemorySize)(&cRamMBs); H();
4471 rc = CFGMR3InsertInteger(pRoot, "RamSize", cRamMBs * _1M); RC_CHECK();
4472 rc = CFGMR3InsertInteger(pRoot, "TimerMillies", 10); RC_CHECK();
4473 rc = CFGMR3InsertInteger(pRoot, "RawR3Enabled", 1); /* boolean */ RC_CHECK();
4474 rc = CFGMR3InsertInteger(pRoot, "RawR0Enabled", 1); /* boolean */ RC_CHECK();
4475 /** @todo Config: RawR0, PATMEnabled and CASMEnabled needs attention later. */
4476 rc = CFGMR3InsertInteger(pRoot, "PATMEnabled", 1); /* boolean */ RC_CHECK();
4477 rc = CFGMR3InsertInteger(pRoot, "CSAMEnabled", 1); /* boolean */ RC_CHECK();
4478
4479 /* hardware virtualization extensions */
4480 TriStateBool_T hwVirtExEnabled;
4481 BOOL fHWVirtExEnabled;
4482 hrc = pMachine->COMGETTER(HWVirtExEnabled)(&hwVirtExEnabled); H();
4483 if (hwVirtExEnabled == TriStateBool_Default)
4484 {
4485 /* check the default value */
4486 hrc = systemProperties->COMGETTER(HWVirtExEnabled)(&fHWVirtExEnabled); H();
4487 }
4488 else
4489 fHWVirtExEnabled = (hwVirtExEnabled == TriStateBool_True);
4490 if (fHWVirtExEnabled)
4491 {
4492 PCFGMNODE pHWVirtExt;
4493 rc = CFGMR3InsertNode(pRoot, "HWVirtExt", &pHWVirtExt); RC_CHECK();
4494 rc = CFGMR3InsertInteger(pHWVirtExt, "Enabled", 1); RC_CHECK();
4495 }
4496
4497 BOOL fIOAPIC;
4498 hrc = biosSettings->COMGETTER(IOAPICEnabled)(&fIOAPIC); H();
4499
4500 /*
4501 * PDM config.
4502 * Load drivers in VBoxC.[so|dll]
4503 */
4504 PCFGMNODE pPDM;
4505 PCFGMNODE pDrivers;
4506 PCFGMNODE pMod;
4507 rc = CFGMR3InsertNode(pRoot, "PDM", &pPDM); RC_CHECK();
4508 rc = CFGMR3InsertNode(pPDM, "Drivers", &pDrivers); RC_CHECK();
4509 rc = CFGMR3InsertNode(pDrivers, "VBoxC", &pMod); RC_CHECK();
4510#ifdef VBOX_WITH_XPCOM
4511 // VBoxC is located in the components subdirectory
4512 char szPathProgram[RTPATH_MAX + sizeof("/components/VBoxC")];
4513 rc = RTPathProgram(szPathProgram, RTPATH_MAX); AssertRC(rc);
4514 strcat(szPathProgram, "/components/VBoxC");
4515 rc = CFGMR3InsertString(pMod, "Path", szPathProgram); RC_CHECK();
4516#else
4517 rc = CFGMR3InsertString(pMod, "Path", "VBoxC"); RC_CHECK();
4518#endif
4519
4520 /*
4521 * Devices
4522 */
4523 PCFGMNODE pDevices = NULL; /* /Devices */
4524 PCFGMNODE pDev = NULL; /* /Devices/Dev/ */
4525 PCFGMNODE pInst = NULL; /* /Devices/Dev/0/ */
4526 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
4527 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
4528 PCFGMNODE pLunL1 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
4529 rc = CFGMR3InsertNode(pRoot, "Devices", &pDevices); RC_CHECK();
4530
4531 /*
4532 * PC Arch.
4533 */
4534 rc = CFGMR3InsertNode(pDevices, "pcarch", &pDev); RC_CHECK();
4535 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4536 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4537 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4538
4539 /*
4540 * PC Bios.
4541 */
4542 rc = CFGMR3InsertNode(pDevices, "pcbios", &pDev); RC_CHECK();
4543 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4544 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4545 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4546 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
4547 rc = CFGMR3InsertString(pCfg, "HardDiskDevice", "piix3ide"); RC_CHECK();
4548 rc = CFGMR3InsertString(pCfg, "FloppyDevice", "i82078"); RC_CHECK();
4549 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4550
4551 DeviceType_T bootDevice;
4552 if (SchemaDefs::MaxBootPosition > 9)
4553 {
4554 AssertMsgFailed (("Too many boot devices %d\n",
4555 SchemaDefs::MaxBootPosition));
4556 return VERR_INVALID_PARAMETER;
4557 }
4558
4559 for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; pos ++)
4560 {
4561 hrc = pMachine->GetBootOrder(pos, &bootDevice); H();
4562
4563 char szParamName[] = "BootDeviceX";
4564 szParamName[sizeof (szParamName) - 2] = ((char (pos - 1)) + '0');
4565
4566 const char *pszBootDevice;
4567 switch (bootDevice)
4568 {
4569 case DeviceType_NoDevice:
4570 pszBootDevice = "NONE";
4571 break;
4572 case DeviceType_HardDiskDevice:
4573 pszBootDevice = "IDE";
4574 break;
4575 case DeviceType_DVDDevice:
4576 pszBootDevice = "DVD";
4577 break;
4578 case DeviceType_FloppyDevice:
4579 pszBootDevice = "FLOPPY";
4580 break;
4581 case DeviceType_NetworkDevice:
4582 pszBootDevice = "LAN";
4583 break;
4584 default:
4585 AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
4586 return VERR_INVALID_PARAMETER;
4587 }
4588 rc = CFGMR3InsertString(pCfg, szParamName, pszBootDevice); RC_CHECK();
4589 }
4590
4591 /*
4592 * BIOS logo
4593 */
4594 BOOL fFadeIn;
4595 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
4596 rc = CFGMR3InsertInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0); RC_CHECK();
4597 BOOL fFadeOut;
4598 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
4599 rc = CFGMR3InsertInteger(pCfg, "FadeOut", fFadeOut ? 1: 0); RC_CHECK();
4600 ULONG logoDisplayTime;
4601 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
4602 rc = CFGMR3InsertInteger(pCfg, "LogoTime", logoDisplayTime); RC_CHECK();
4603 Bstr logoImagePath;
4604 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
4605 rc = CFGMR3InsertString(pCfg, "LogoFile", logoImagePath ? Utf8Str(logoImagePath) : ""); RC_CHECK();
4606
4607 /*
4608 * Boot menu
4609 */
4610 BIOSBootMenuMode_T bootMenuMode;
4611 int value;
4612 biosSettings->COMGETTER(BootMenuMode)(&bootMenuMode);
4613 switch (bootMenuMode)
4614 {
4615 case BIOSBootMenuMode_Disabled:
4616 value = 0;
4617 break;
4618 case BIOSBootMenuMode_MenuOnly:
4619 value = 1;
4620 break;
4621 default:
4622 value = 2;
4623 }
4624 rc = CFGMR3InsertInteger(pCfg, "ShowBootMenu", value); RC_CHECK();
4625
4626 /*
4627 * The time offset
4628 */
4629 LONG64 timeOffset;
4630 hrc = biosSettings->COMGETTER(TimeOffset)(&timeOffset); H();
4631 PCFGMNODE pTMNode;
4632 rc = CFGMR3InsertNode(pRoot, "TM", &pTMNode); RC_CHECK();
4633 rc = CFGMR3InsertInteger(pTMNode, "UTCOffset", timeOffset * 1000000); RC_CHECK();
4634
4635 /*
4636 * ACPI
4637 */
4638 BOOL fACPI;
4639 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
4640 if (fACPI)
4641 {
4642 rc = CFGMR3InsertNode(pDevices, "acpi", &pDev); RC_CHECK();
4643 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4644 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4645 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4646 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
4647 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4648 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 7); RC_CHECK();
4649 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
4650
4651 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4652 rc = CFGMR3InsertString(pLunL0, "Driver", "ACPIHost"); RC_CHECK();
4653 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4654 }
4655
4656 /*
4657 * DMA
4658 */
4659 rc = CFGMR3InsertNode(pDevices, "8237A", &pDev); RC_CHECK();
4660 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4661 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4662
4663 /*
4664 * PCI bus.
4665 */
4666 rc = CFGMR3InsertNode(pDevices, "pci", &pDev); /* piix3 */ RC_CHECK();
4667 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4668 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4669 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4670 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4671
4672 /*
4673 * PS/2 keyboard & mouse.
4674 */
4675 rc = CFGMR3InsertNode(pDevices, "pckbd", &pDev); RC_CHECK();
4676 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4677 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4678 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4679
4680 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4681 rc = CFGMR3InsertString(pLunL0, "Driver", "KeyboardQueue"); RC_CHECK();
4682 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4683 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 64); RC_CHECK();
4684
4685 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4686 rc = CFGMR3InsertString(pLunL1, "Driver", "MainKeyboard"); RC_CHECK();
4687 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4688 Keyboard *pKeyboard = pConsole->mKeyboard;
4689 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pKeyboard); RC_CHECK();
4690
4691 rc = CFGMR3InsertNode(pInst, "LUN#1", &pLunL0); RC_CHECK();
4692 rc = CFGMR3InsertString(pLunL0, "Driver", "MouseQueue"); RC_CHECK();
4693 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4694 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 128); RC_CHECK();
4695
4696 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4697 rc = CFGMR3InsertString(pLunL1, "Driver", "MainMouse"); RC_CHECK();
4698 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4699 Mouse *pMouse = pConsole->mMouse;
4700 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pMouse); RC_CHECK();
4701
4702 /*
4703 * i82078 Floppy drive controller
4704 */
4705 ComPtr<IFloppyDrive> floppyDrive;
4706 hrc = pMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam()); H();
4707 BOOL fFloppyEnabled;
4708 hrc = floppyDrive->COMGETTER(Enabled)(&fFloppyEnabled); H();
4709 if (fFloppyEnabled)
4710 {
4711 rc = CFGMR3InsertNode(pDevices, "i82078", &pDev); RC_CHECK();
4712 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4713 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); RC_CHECK();
4714 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4715 rc = CFGMR3InsertInteger(pCfg, "IRQ", 6); RC_CHECK();
4716 rc = CFGMR3InsertInteger(pCfg, "DMA", 2); RC_CHECK();
4717 rc = CFGMR3InsertInteger(pCfg, "MemMapped", 0 ); RC_CHECK();
4718 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x3f0); RC_CHECK();
4719
4720 /* Attach the status driver */
4721 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
4722 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
4723 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4724 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapFDLeds[0]); RC_CHECK();
4725 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
4726 rc = CFGMR3InsertInteger(pCfg, "Last", 0); RC_CHECK();
4727
4728 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4729
4730 ComPtr<IFloppyImage> floppyImage;
4731 hrc = floppyDrive->GetImage(floppyImage.asOutParam()); H();
4732 if (floppyImage)
4733 {
4734 pConsole->meFloppyState = DriveState_ImageMounted;
4735 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4736 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4737 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
4738 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4739
4740 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4741 rc = CFGMR3InsertString(pLunL1, "Driver", "RawImage"); RC_CHECK();
4742 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4743 hrc = floppyImage->COMGETTER(FilePath)(&str); H();
4744 STR_CONV();
4745 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4746 STR_FREE();
4747 }
4748 else
4749 {
4750 ComPtr<IHostFloppyDrive> hostFloppyDrive;
4751 hrc = floppyDrive->GetHostDrive(hostFloppyDrive.asOutParam()); H();
4752 if (hostFloppyDrive)
4753 {
4754 pConsole->meFloppyState = DriveState_HostDriveCaptured;
4755 rc = CFGMR3InsertString(pLunL0, "Driver", "HostFloppy"); RC_CHECK();
4756 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4757 hrc = hostFloppyDrive->COMGETTER(Name)(&str); H();
4758 STR_CONV();
4759 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4760 STR_FREE();
4761 }
4762 else
4763 {
4764 pConsole->meFloppyState = DriveState_NotMounted;
4765 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4766 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4767 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
4768 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
4769 }
4770 }
4771 }
4772
4773 /*
4774 * i8254 Programmable Interval Timer And Dummy Speaker
4775 */
4776 rc = CFGMR3InsertNode(pDevices, "i8254", &pDev); RC_CHECK();
4777 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4778 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4779#ifdef DEBUG
4780 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4781#endif
4782
4783 /*
4784 * i8259 Programmable Interrupt Controller.
4785 */
4786 rc = CFGMR3InsertNode(pDevices, "i8259", &pDev); RC_CHECK();
4787 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4788 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4789 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4790
4791 /*
4792 * Advanced Programmable Interrupt Controller.
4793 */
4794 rc = CFGMR3InsertNode(pDevices, "apic", &pDev); RC_CHECK();
4795 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4796 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4797 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4798 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
4799
4800 if (fIOAPIC)
4801 {
4802 /*
4803 * I/O Advanced Programmable Interrupt Controller.
4804 */
4805 rc = CFGMR3InsertNode(pDevices, "ioapic", &pDev); RC_CHECK();
4806 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4807 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4808 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4809 }
4810
4811 /*
4812 * RTC MC146818.
4813 */
4814 rc = CFGMR3InsertNode(pDevices, "mc146818", &pDev); RC_CHECK();
4815 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4816 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4817
4818#if 0
4819 /*
4820 * Serial ports
4821 */
4822 rc = CFGMR3InsertNode(pDevices, "serial", &pDev); RC_CHECK();
4823 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4824 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4825 rc = CFGMR3InsertInteger(pCfg, "IRQ", 4); RC_CHECK();
4826 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x3f8); RC_CHECK();
4827
4828 rc = CFGMR3InsertNode(pDev, "1", &pInst); RC_CHECK();
4829 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4830 rc = CFGMR3InsertInteger(pCfg, "IRQ", 3); RC_CHECK();
4831 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x2f8); RC_CHECK();
4832#endif
4833
4834 /*
4835 * VGA.
4836 */
4837 rc = CFGMR3InsertNode(pDevices, "vga", &pDev); RC_CHECK();
4838 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4839 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4840 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 2); RC_CHECK();
4841 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
4842 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4843 hrc = pMachine->COMGETTER(VRAMSize)(&cRamMBs); H();
4844 rc = CFGMR3InsertInteger(pCfg, "VRamSize", cRamMBs * _1M); RC_CHECK();
4845 hrc = pMachine->COMGETTER(MonitorCount)(&cMonitors); H();
4846 rc = CFGMR3InsertInteger(pCfg, "MonitorCount", cMonitors); RC_CHECK();
4847
4848 /* Custom VESA mode list */
4849 unsigned cModes = 0;
4850 for (unsigned iMode = 1; iMode <= 16; iMode++)
4851 {
4852 char szExtraDataKey[sizeof("CustomVideoModeXX")];
4853 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%d", iMode);
4854 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey), &str); H();
4855 if (!str || !*str)
4856 break;
4857 STR_CONV();
4858 rc = CFGMR3InsertString(pCfg, szExtraDataKey, psz);
4859 STR_FREE();
4860 cModes++;
4861 }
4862 rc = CFGMR3InsertInteger(pCfg, "CustomVideoModes", cModes);
4863
4864 /* VESA height reduction */
4865 ULONG ulHeightReduction;
4866 IFramebuffer *pFramebuffer = pConsole->getDisplay()->getFramebuffer();
4867 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
4868 rc = CFGMR3InsertInteger(pCfg, "HeightReduction", ulHeightReduction); RC_CHECK();
4869
4870 /* Attach the display. */
4871 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
4872 rc = CFGMR3InsertString(pLunL0, "Driver", "MainDisplay"); RC_CHECK();
4873 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4874 Display *pDisplay = pConsole->mDisplay;
4875 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pDisplay); RC_CHECK();
4876
4877 /*
4878 * IDE (update this when the main interface changes)
4879 */
4880 rc = CFGMR3InsertNode(pDevices, "piix3ide", &pDev); /* piix3 */ RC_CHECK();
4881 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
4882 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
4883 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 1); RC_CHECK();
4884 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 1); RC_CHECK();
4885 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
4886
4887 /* Attach the status driver */
4888 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
4889 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
4890 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4891 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapIDELeds[0]);RC_CHECK();
4892 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
4893 rc = CFGMR3InsertInteger(pCfg, "Last", 3); RC_CHECK();
4894
4895 /* Attach the harddisks */
4896 ComPtr<IHardDiskAttachmentCollection> hdaColl;
4897 hrc = pMachine->COMGETTER(HardDiskAttachments)(hdaColl.asOutParam()); H();
4898 ComPtr<IHardDiskAttachmentEnumerator> hdaEnum;
4899 hrc = hdaColl->Enumerate(hdaEnum.asOutParam()); H();
4900
4901 BOOL fMore = FALSE;
4902 while ( SUCCEEDED(hrc = hdaEnum->HasMore(&fMore))
4903 && fMore)
4904 {
4905 ComPtr<IHardDiskAttachment> hda;
4906 hrc = hdaEnum->GetNext(hda.asOutParam()); H();
4907 ComPtr<IHardDisk> hardDisk;
4908 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
4909 DiskControllerType_T enmCtl;
4910 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
4911 LONG lDev;
4912 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
4913
4914 switch (enmCtl)
4915 {
4916 case DiskControllerType_IDE0Controller:
4917 i = 0;
4918 break;
4919 case DiskControllerType_IDE1Controller:
4920 i = 2;
4921 break;
4922 default:
4923 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
4924 return VERR_GENERAL_FAILURE;
4925 }
4926
4927 if (lDev < 0 || lDev >= 2)
4928 {
4929 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
4930 return VERR_GENERAL_FAILURE;
4931 }
4932
4933 i = i + lDev;
4934
4935 char szLUN[16];
4936 RTStrPrintf(szLUN, sizeof(szLUN), "LUN#%d", i);
4937 rc = CFGMR3InsertNode(pInst, szLUN, &pLunL0); RC_CHECK();
4938 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
4939 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
4940 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
4941 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
4942
4943 HardDiskStorageType_T hddType;
4944 hardDisk->COMGETTER(StorageType)(&hddType);
4945 if (hddType == HardDiskStorageType_VirtualDiskImage)
4946 {
4947 ComPtr<IVirtualDiskImage> vdiDisk = hardDisk;
4948 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
4949
4950 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4951 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
4952 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4953 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
4954 STR_CONV();
4955 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
4956 STR_FREE();
4957
4958 /* Create an inversed tree of parents. */
4959 ComPtr<IHardDisk> parentHardDisk = hardDisk;
4960 for (PCFGMNODE pParent = pCfg;;)
4961 {
4962 ComPtr<IHardDisk> curHardDisk;
4963 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
4964 if (!curHardDisk)
4965 break;
4966
4967 vdiDisk = curHardDisk;
4968 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
4969
4970 PCFGMNODE pCur;
4971 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
4972 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
4973 STR_CONV();
4974 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
4975 STR_FREE();
4976 rc = CFGMR3InsertInteger(pCur, "ReadOnly", 1); RC_CHECK();
4977
4978 /* next */
4979 pParent = pCur;
4980 parentHardDisk = curHardDisk;
4981 }
4982 }
4983 else if (hddType == HardDiskStorageType_ISCSIHardDisk)
4984 {
4985 ComPtr<IISCSIHardDisk> iSCSIDisk = hardDisk;
4986 AssertBreak (!iSCSIDisk.isNull(), hrc = E_FAIL);
4987
4988 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
4989 rc = CFGMR3InsertString(pLunL1, "Driver", "iSCSI"); RC_CHECK();
4990 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
4991
4992 /* Set up the iSCSI initiator driver configuration. */
4993 hrc = iSCSIDisk->COMGETTER(Target)(&str); H();
4994 STR_CONV();
4995 rc = CFGMR3InsertString(pCfg, "TargetName", psz); RC_CHECK();
4996 STR_FREE();
4997
4998 // @todo currently there is no Initiator name config.
4999 rc = CFGMR3InsertString(pCfg, "InitiatorName", "iqn.2006-02.de.innotek.initiator"); RC_CHECK();
5000
5001 ULONG64 lun;
5002 hrc = iSCSIDisk->COMGETTER(Lun)(&lun); H();
5003 rc = CFGMR3InsertInteger(pCfg, "LUN", lun); RC_CHECK();
5004
5005 hrc = iSCSIDisk->COMGETTER(Server)(&str); H();
5006 STR_CONV();
5007 USHORT port;
5008 hrc = iSCSIDisk->COMGETTER(Port)(&port); H();
5009 if (port != 0)
5010 {
5011 char *pszTN;
5012 RTStrAPrintf(&pszTN, "%s:%u", psz, port);
5013 rc = CFGMR3InsertString(pCfg, "TargetAddress", pszTN); RC_CHECK();
5014 RTStrFree(pszTN);
5015 }
5016 else
5017 {
5018 rc = CFGMR3InsertString(pCfg, "TargetAddress", psz); RC_CHECK();
5019 }
5020 STR_FREE();
5021
5022 hrc = iSCSIDisk->COMGETTER(UserName)(&str); H();
5023 if (str)
5024 {
5025 STR_CONV();
5026 rc = CFGMR3InsertString(pCfg, "InitiatorUsername", psz); RC_CHECK();
5027 STR_FREE();
5028 }
5029
5030 hrc = iSCSIDisk->COMGETTER(Password)(&str); H();
5031 if (str)
5032 {
5033 STR_CONV();
5034 rc = CFGMR3InsertString(pCfg, "InitiatorSecret", psz); RC_CHECK();
5035 STR_FREE();
5036 }
5037
5038 // @todo currently there is no target username config.
5039 //rc = CFGMR3InsertString(pCfg, "TargetUsername", ""); RC_CHECK();
5040
5041 // @todo currently there is no target password config.
5042 //rc = CFGMR3InsertString(pCfg, "TargetSecret", ""); RC_CHECK();
5043
5044 /* The iSCSI initiator needs an attached iSCSI transport driver. */
5045 PCFGMNODE pLunL2 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/AttachedDriver */
5046 rc = CFGMR3InsertNode(pLunL1, "AttachedDriver", &pLunL2); RC_CHECK();
5047 rc = CFGMR3InsertString(pLunL2, "Driver", "iSCSITCP"); RC_CHECK();
5048 /* Currently the transport driver has no config options. */
5049 }
5050 else if (hddType == HardDiskStorageType_VMDKImage)
5051 {
5052 ComPtr<IVMDKImage> vmdkDisk = hardDisk;
5053 AssertBreak (!vmdkDisk.isNull(), hrc = E_FAIL);
5054
5055 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5056#if 1 /* Enable new VD container code (and new VMDK), as the bugs are fixed. */
5057 rc = CFGMR3InsertString(pLunL1, "Driver", "VD"); RC_CHECK();
5058#else
5059 rc = CFGMR3InsertString(pLunL1, "Driver", "VmdkHDD"); RC_CHECK();
5060#endif
5061 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5062 hrc = vmdkDisk->COMGETTER(FilePath)(&str); H();
5063 STR_CONV();
5064 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5065 STR_FREE();
5066 }
5067 else
5068 AssertFailed();
5069 }
5070 H();
5071
5072 ComPtr<IDVDDrive> dvdDrive;
5073 hrc = pMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam()); H();
5074 if (dvdDrive)
5075 {
5076 // ASSUME: DVD drive is always attached to LUN#2 (i.e. secondary IDE master)
5077 rc = CFGMR3InsertNode(pInst, "LUN#2", &pLunL0); RC_CHECK();
5078 ComPtr<IHostDVDDrive> hostDvdDrive;
5079 hrc = dvdDrive->GetHostDrive(hostDvdDrive.asOutParam()); H();
5080 if (hostDvdDrive)
5081 {
5082 pConsole->meDVDState = DriveState_HostDriveCaptured;
5083 rc = CFGMR3InsertString(pLunL0, "Driver", "HostDVD"); RC_CHECK();
5084 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5085 hrc = hostDvdDrive->COMGETTER(Name)(&str); H();
5086 STR_CONV();
5087 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5088 STR_FREE();
5089 BOOL fPassthrough;
5090 hrc = dvdDrive->COMGETTER(Passthrough)(&fPassthrough); H();
5091 rc = CFGMR3InsertInteger(pCfg, "Passthrough", !!fPassthrough); RC_CHECK();
5092 }
5093 else
5094 {
5095 pConsole->meDVDState = DriveState_NotMounted;
5096 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
5097 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5098 rc = CFGMR3InsertString(pCfg, "Type", "DVD"); RC_CHECK();
5099 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
5100
5101 ComPtr<IDVDImage> dvdImage;
5102 hrc = dvdDrive->GetImage(dvdImage.asOutParam()); H();
5103 if (dvdImage)
5104 {
5105 pConsole->meDVDState = DriveState_ImageMounted;
5106 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5107 rc = CFGMR3InsertString(pLunL1, "Driver", "MediaISO"); RC_CHECK();
5108 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5109 hrc = dvdImage->COMGETTER(FilePath)(&str); H();
5110 STR_CONV();
5111 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5112 STR_FREE();
5113 }
5114 }
5115 }
5116
5117 /*
5118 * Network adapters
5119 */
5120 rc = CFGMR3InsertNode(pDevices, "pcnet", &pDev); RC_CHECK();
5121 //rc = CFGMR3InsertNode(pDevices, "ne2000", &pDev); RC_CHECK();
5122 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::NetworkAdapterCount; ulInstance++)
5123 {
5124 ComPtr<INetworkAdapter> networkAdapter;
5125 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
5126 BOOL fEnabled = FALSE;
5127 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabled); H();
5128 if (!fEnabled)
5129 continue;
5130
5131 char szInstance[4]; Assert(ulInstance <= 999);
5132 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5133 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5134 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5135 /* the first network card gets the PCI ID 3, the followings starting from 8 */
5136 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", !ulInstance ? 3 : ulInstance - 1 + 8); RC_CHECK();
5137 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5138 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5139
5140 /*
5141 * The virtual hardware type.
5142 */
5143 NetworkAdapterType_T adapterType;
5144 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
5145 switch (adapterType)
5146 {
5147 case NetworkAdapterType_NetworkAdapterAm79C970A:
5148 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 0); RC_CHECK();
5149 break;
5150 case NetworkAdapterType_NetworkAdapterAm79C973:
5151 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 1); RC_CHECK();
5152 break;
5153 default:
5154 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
5155 adapterType, ulInstance));
5156 return VERR_GENERAL_FAILURE;
5157 }
5158
5159 /*
5160 * Get the MAC address and convert it to binary representation
5161 */
5162 Bstr macAddr;
5163 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
5164 Assert(macAddr);
5165 Utf8Str macAddrUtf8 = macAddr;
5166 char *macStr = (char*)macAddrUtf8.raw();
5167 Assert(strlen(macStr) == 12);
5168 PDMMAC Mac;
5169 memset(&Mac, 0, sizeof(Mac));
5170 char *pMac = (char*)&Mac;
5171 for (uint32_t i = 0; i < 6; i++)
5172 {
5173 char c1 = *macStr++ - '0';
5174 if (c1 > 9)
5175 c1 -= 7;
5176 char c2 = *macStr++ - '0';
5177 if (c2 > 9)
5178 c2 -= 7;
5179 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
5180 }
5181 rc = CFGMR3InsertBytes(pCfg, "MAC", &Mac, sizeof(Mac)); RC_CHECK();
5182
5183 /*
5184 * Check if the cable is supposed to be unplugged
5185 */
5186 BOOL fCableConnected;
5187 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
5188 rc = CFGMR3InsertInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0); RC_CHECK();
5189
5190 /*
5191 * Attach the status driver.
5192 */
5193 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5194 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5195 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5196 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapNetworkLeds[ulInstance]); RC_CHECK();
5197
5198 /*
5199 * Enable the packet sniffer if requested.
5200 */
5201 BOOL fSniffer;
5202 hrc = networkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
5203 if (fSniffer)
5204 {
5205 /* insert the sniffer filter driver. */
5206 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5207 rc = CFGMR3InsertString(pLunL0, "Driver", "NetSniffer"); RC_CHECK();
5208 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5209 hrc = networkAdapter->COMGETTER(TraceFile)(&str); H();
5210 if (str) /* check convention for indicating default file. */
5211 {
5212 STR_CONV();
5213 rc = CFGMR3InsertString(pCfg, "File", psz); RC_CHECK();
5214 STR_FREE();
5215 }
5216 }
5217
5218 NetworkAttachmentType_T networkAttachment;
5219 hrc = networkAdapter->COMGETTER(AttachmentType)(&networkAttachment); H();
5220 switch (networkAttachment)
5221 {
5222 case NetworkAttachmentType_NoNetworkAttachment:
5223 break;
5224
5225 case NetworkAttachmentType_NATNetworkAttachment:
5226 {
5227 if (fSniffer)
5228 {
5229 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5230 }
5231 else
5232 {
5233 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5234 }
5235 rc = CFGMR3InsertString(pLunL0, "Driver", "NAT"); RC_CHECK();
5236 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5237 /* (Port forwarding goes here.) */
5238 break;
5239 }
5240
5241 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
5242 {
5243 /*
5244 * Perform the attachment if required (don't return on error!)
5245 */
5246 hrc = pConsole->attachToHostInterface(networkAdapter);
5247 if (SUCCEEDED(hrc))
5248 {
5249#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5250 Assert (pConsole->maTapFD[ulInstance] >= 0);
5251 if (pConsole->maTapFD[ulInstance] >= 0)
5252 {
5253 if (fSniffer)
5254 {
5255 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5256 }
5257 else
5258 {
5259 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5260 }
5261 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5262 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5263 rc = CFGMR3InsertInteger(pCfg, "FileHandle", pConsole->maTapFD[ulInstance]); RC_CHECK();
5264 }
5265#elif defined(__WIN__)
5266 if (fSniffer)
5267 {
5268 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5269 }
5270 else
5271 {
5272 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5273 }
5274 Bstr hostInterfaceName;
5275 hrc = networkAdapter->COMGETTER(HostInterface)(hostInterfaceName.asOutParam()); H();
5276 ComPtr<IHostNetworkInterfaceCollection> coll;
5277 hrc = host->COMGETTER(NetworkInterfaces)(coll.asOutParam()); H();
5278 ComPtr<IHostNetworkInterface> hostInterface;
5279 rc = coll->FindByName(hostInterfaceName, hostInterface.asOutParam());
5280 if (!SUCCEEDED(rc))
5281 {
5282 AssertMsgFailed(("Cannot get GUID for host interface '%ls'\n", hostInterfaceName));
5283 hrc = networkAdapter->Detach(); H();
5284 }
5285 else
5286 {
5287 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5288 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5289 rc = CFGMR3InsertString(pCfg, "HostInterfaceName", Utf8Str(hostInterfaceName)); RC_CHECK();
5290 Guid hostIFGuid;
5291 hrc = hostInterface->COMGETTER(Id)(hostIFGuid.asOutParam()); H();
5292 char szDriverGUID[256] = {0};
5293 /* add curly brackets */
5294 szDriverGUID[0] = '{';
5295 strcpy(szDriverGUID + 1, hostIFGuid.toString().raw());
5296 strcat(szDriverGUID, "}");
5297 rc = CFGMR3InsertBytes(pCfg, "GUID", szDriverGUID, sizeof(szDriverGUID)); RC_CHECK();
5298 }
5299#else
5300# error "Port me"
5301#endif
5302 }
5303 else
5304 {
5305 switch (hrc)
5306 {
5307#ifdef __LINUX__
5308 case VERR_ACCESS_DENIED:
5309 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5310 "Failed to open '/dev/net/tun' for read/write access. Please check the "
5311 "permissions of that node. Either do 'chmod 0666 /dev/net/tun' or "
5312 "change the group of that node and get member of that group. Make "
5313 "sure that these changes are permanently in particular if you are "
5314 "using udev"));
5315#endif /* __LINUX__ */
5316 default:
5317 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
5318 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5319 "Failed to initialize Host Interface Networking"));
5320 }
5321 }
5322 break;
5323 }
5324
5325 case NetworkAttachmentType_InternalNetworkAttachment:
5326 {
5327 hrc = networkAdapter->COMGETTER(InternalNetwork)(&str); H();
5328 STR_CONV();
5329 if (psz && *psz)
5330 {
5331 if (fSniffer)
5332 {
5333 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5334 }
5335 else
5336 {
5337 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5338 }
5339 rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet"); RC_CHECK();
5340 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5341 rc = CFGMR3InsertString(pCfg, "Network", psz); RC_CHECK();
5342 }
5343 STR_FREE();
5344 break;
5345 }
5346
5347 default:
5348 AssertMsgFailed(("should not get here!\n"));
5349 break;
5350 }
5351 }
5352
5353 /*
5354 * VMM Device
5355 */
5356 rc = CFGMR3InsertNode(pDevices, "VMMDev", &pDev); RC_CHECK();
5357 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5358 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5359 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5360 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 4); RC_CHECK();
5361 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5362
5363 /* the VMM device's Main driver */
5364 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5365 rc = CFGMR3InsertString(pLunL0, "Driver", "MainVMMDev"); RC_CHECK();
5366 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5367 VMMDev *pVMMDev = pConsole->mVMMDev;
5368 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pVMMDev); RC_CHECK();
5369
5370 /*
5371 * Audio Sniffer Device
5372 */
5373 rc = CFGMR3InsertNode(pDevices, "AudioSniffer", &pDev); RC_CHECK();
5374 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5375 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5376
5377 /* the Audio Sniffer device's Main driver */
5378 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5379 rc = CFGMR3InsertString(pLunL0, "Driver", "MainAudioSniffer"); RC_CHECK();
5380 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5381 AudioSniffer *pAudioSniffer = pConsole->mAudioSniffer;
5382 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pAudioSniffer); RC_CHECK();
5383
5384 /*
5385 * AC'97 ICH audio
5386 */
5387 ComPtr<IAudioAdapter> audioAdapter;
5388 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
5389 BOOL enabled = FALSE;
5390 if (audioAdapter)
5391 {
5392 hrc = audioAdapter->COMGETTER(Enabled)(&enabled); H();
5393 }
5394 if (enabled)
5395 {
5396 rc = CFGMR3InsertNode(pDevices, "ichac97", &pDev); /* ichac97 */
5397 rc = CFGMR3InsertNode(pDev, "0", &pInst);
5398 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5399 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 5); RC_CHECK();
5400 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5401 rc = CFGMR3InsertNode(pInst, "Config", &pCfg);
5402
5403 /* the Audio driver */
5404 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5405 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
5406 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5407 AudioDriverType_T audioDriver;
5408 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
5409 switch (audioDriver)
5410 {
5411 case AudioDriverType_NullAudioDriver:
5412 {
5413 rc = CFGMR3InsertString(pCfg, "AudioDriver", "null"); RC_CHECK();
5414 break;
5415 }
5416#ifdef __WIN__
5417#ifdef VBOX_WITH_WINMM
5418 case AudioDriverType_WINMMAudioDriver:
5419 {
5420 rc = CFGMR3InsertString(pCfg, "AudioDriver", "winmm"); RC_CHECK();
5421 break;
5422 }
5423#endif
5424 case AudioDriverType_DSOUNDAudioDriver:
5425 {
5426 rc = CFGMR3InsertString(pCfg, "AudioDriver", "dsound"); RC_CHECK();
5427 break;
5428 }
5429#endif /* __WIN__ */
5430#ifdef __LINUX__
5431 case AudioDriverType_OSSAudioDriver:
5432 {
5433 rc = CFGMR3InsertString(pCfg, "AudioDriver", "oss"); RC_CHECK();
5434 break;
5435 }
5436# ifdef VBOX_WITH_ALSA
5437 case AudioDriverType_ALSAAudioDriver:
5438 {
5439 rc = CFGMR3InsertString(pCfg, "AudioDriver", "alsa"); RC_CHECK();
5440 break;
5441 }
5442# endif
5443#endif /* __LINUX__ */
5444#ifdef __DARWIN__
5445 case AudioDriverType_CoreAudioDriver:
5446 {
5447 rc = CFGMR3InsertString(pCfg, "AudioDriver", "coreaudio"); RC_CHECK();
5448 break;
5449 }
5450#endif
5451 }
5452 }
5453
5454 /*
5455 * The USB Controller.
5456 */
5457 ComPtr<IUSBController> USBCtlPtr;
5458 hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
5459 if (USBCtlPtr)
5460 {
5461 BOOL fEnabled;
5462 hrc = USBCtlPtr->COMGETTER(Enabled)(&fEnabled); H();
5463 if (fEnabled)
5464 {
5465 rc = CFGMR3InsertNode(pDevices, "usb-ohci", &pDev); RC_CHECK();
5466 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5467 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5468 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5469 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 6); RC_CHECK();
5470 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5471
5472 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5473 rc = CFGMR3InsertString(pLunL0, "Driver", "VUSBRootHub"); RC_CHECK();
5474 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5475 }
5476 }
5477
5478 /*
5479 * Clipboard
5480 */
5481 {
5482 ClipboardMode_T mode = ClipboardMode_ClipDisabled;
5483 hrc = pMachine->COMGETTER(ClipboardMode) (&mode); H();
5484
5485 if (mode != ClipboardMode_ClipDisabled)
5486 {
5487 /* Load the service */
5488 rc = pConsole->mVMMDev->hgcmLoadService ("VBoxSharedClipboard", "VBoxSharedClipboard");
5489
5490 if (VBOX_FAILURE (rc))
5491 {
5492 LogRel(("VBoxSharedClipboard is not available. rc = %Vrc\n", rc));
5493 /* That is not a fatal failure. */
5494 rc = VINF_SUCCESS;
5495 }
5496 else
5497 {
5498 /* Setup the service. */
5499 VBOXHGCMSVCPARM parm;
5500
5501 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
5502
5503 switch (mode)
5504 {
5505 default:
5506 case ClipboardMode_ClipDisabled:
5507 {
5508 LogRel(("VBoxSharedClipboard mode: Off\n"));
5509 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
5510 break;
5511 }
5512 case ClipboardMode_ClipGuestToHost:
5513 {
5514 LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
5515 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
5516 break;
5517 }
5518 case ClipboardMode_ClipHostToGuest:
5519 {
5520 LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
5521 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
5522 break;
5523 }
5524 case ClipboardMode_ClipBidirectional:
5525 {
5526 LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
5527 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
5528 break;
5529 }
5530 }
5531
5532 pConsole->mVMMDev->hgcmHostCall ("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
5533
5534 Log(("Set VBoxSharedClipboard mode\n"));
5535 }
5536 }
5537 }
5538
5539 /*
5540 * CFGM overlay handling.
5541 *
5542 * Here we check the extra data entries for CFGM values
5543 * and create the nodes and insert the values on the fly. Existing
5544 * values will be removed and reinserted. If a value is a valid number,
5545 * it will be inserted as a number, otherwise as a string.
5546 *
5547 * We first perform a run on global extra data, then on the machine
5548 * extra data to support global settings with local overrides.
5549 *
5550 */
5551 Bstr strExtraDataKey;
5552 bool fGlobalExtraData = true;
5553 for (;;)
5554 {
5555 Bstr strNextExtraDataKey;
5556 Bstr strExtraDataValue;
5557
5558 /* get the next key */
5559 if (fGlobalExtraData)
5560 hrc = virtualBox->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5561 strExtraDataValue.asOutParam());
5562 else
5563 hrc = pMachine->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
5564 strExtraDataValue.asOutParam());
5565
5566 /* stop if for some reason there's nothing more to request */
5567 if (FAILED(hrc) || !strNextExtraDataKey)
5568 {
5569 /* if we're out of global keys, continue with machine, otherwise we're done */
5570 if (fGlobalExtraData)
5571 {
5572 fGlobalExtraData = false;
5573 strExtraDataKey.setNull();
5574 continue;
5575 }
5576 break;
5577 }
5578
5579 strExtraDataKey = strNextExtraDataKey;
5580 Utf8Str strExtraDataKeyUtf8 = Utf8Str(strExtraDataKey);
5581
5582 /* we only care about keys starting with "VBoxInternal/" */
5583 if (strncmp(strExtraDataKeyUtf8.raw(), "VBoxInternal/", 13) != 0)
5584 continue;
5585 char *pszExtraDataKey = (char*)strExtraDataKeyUtf8.raw() + 13;
5586
5587 /* the key will be in the format "Node1/Node2/Value" or simply "Value". */
5588 PCFGMNODE pNode;
5589 char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
5590 if (pszCFGMValueName)
5591 {
5592 /* terminate the node and advance to the value */
5593 *pszCFGMValueName = '\0';
5594 pszCFGMValueName++;
5595
5596 /* does the node already exist? */
5597 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
5598 if (pNode)
5599 {
5600 /* the value might already exist, remove it to be safe */
5601 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5602 }
5603 else
5604 {
5605 /* create the node */
5606 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
5607 AssertMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
5608 if (VBOX_FAILURE(rc) || !pNode)
5609 continue;
5610 }
5611 }
5612 else
5613 {
5614 pNode = pRoot;
5615 pszCFGMValueName = pszExtraDataKey;
5616 pszExtraDataKey--;
5617
5618 /* the value might already exist, remove it to be safe */
5619 CFGMR3RemoveValue(pNode, pszCFGMValueName);
5620 }
5621
5622 /* now let's have a look at the value */
5623 Utf8Str strCFGMValueUtf8 = Utf8Str(strExtraDataValue);
5624 const char *pszCFGMValue = strCFGMValueUtf8.raw();
5625 /* empty value means remove value which we've already done */
5626 if (pszCFGMValue && *pszCFGMValue)
5627 {
5628 /* if it's a valid number, we'll insert it as such, otherwise string */
5629 uint64_t u64Value;
5630 if (RTStrToUInt64Ex(pszCFGMValue, NULL, 0, &u64Value) == VINF_SUCCESS)
5631 {
5632 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
5633 }
5634 else
5635 {
5636 rc = CFGMR3InsertString(pNode, pszCFGMValueName, pszCFGMValue);
5637 }
5638 AssertMsgRC(rc, ("failed to insert CFGM value '%s' to key '%s'\n", pszCFGMValue, pszExtraDataKey));
5639 }
5640 }
5641
5642#undef H
5643#undef RC_CHECK
5644#undef STR_FREE
5645#undef STR_CONV
5646
5647 /* Register VM state change handler */
5648 int rc2 = VMR3AtStateRegister (pVM, Console::vmstateChangeCallback, pConsole);
5649 AssertRC (rc2);
5650 if (VBOX_SUCCESS (rc))
5651 rc = rc2;
5652
5653 /* Register VM runtime error handler */
5654 rc2 = VMR3AtRuntimeErrorRegister (pVM, Console::setVMRuntimeErrorCallback, pConsole);
5655 AssertRC (rc2);
5656 if (VBOX_SUCCESS (rc))
5657 rc = rc2;
5658
5659 /* Save the VM pointer in the machine object */
5660 pConsole->mpVM = pVM;
5661
5662 LogFlowFunc (("vrc = %Vrc\n", rc));
5663 LogFlowFuncLeave();
5664
5665 return rc;
5666}
5667
5668/**
5669 * Call the initialisation script for a dynamic TAP interface.
5670 *
5671 * The initialisation script should create a TAP interface, set it up and write its name to
5672 * standard output followed by a carriage return. Anything further written to standard
5673 * output will be ignored. If it returns a non-zero exit code, or does not write an
5674 * intelligable interface name to standard output, it will be treated as having failed.
5675 * For now, this method only works on Linux.
5676 *
5677 * @returns COM status code
5678 * @param tapDevice string to store the name of the tap device created to
5679 * @param tapSetupApplication the name of the setup script
5680 */
5681HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5682 Bstr &tapSetupApplication)
5683{
5684 LogFlowThisFunc(("\n"));
5685#ifdef __LINUX__
5686 /* Command line to start the script with. */
5687 char szCommand[4096];
5688 /* Result code */
5689 int rc;
5690
5691 /* Get the script name. */
5692 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5693 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5694 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5695 /*
5696 * Create the process and read its output.
5697 */
5698 Log2(("About to start the TAP setup script with the following command line: %s\n",
5699 szCommand));
5700 FILE *pfScriptHandle = popen(szCommand, "r");
5701 if (pfScriptHandle == 0)
5702 {
5703 int iErr = errno;
5704 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5705 szCommand, strerror(iErr)));
5706 LogFlowThisFunc(("rc=E_FAIL\n"));
5707 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5708 szCommand, strerror(iErr));
5709 }
5710 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5711 if (!isStatic)
5712 {
5713 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5714 interested in the first few (normally 5 or 6) bytes. */
5715 char acBuffer[64];
5716 /* The length of the string returned by the application. We only accept strings of 63
5717 characters or less. */
5718 size_t cBufSize;
5719
5720 /* Read the name of the device from the application. */
5721 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5722 cBufSize = strlen(acBuffer);
5723 /* The script must return the name of the interface followed by a carriage return as the
5724 first line of its output. We need a null-terminated string. */
5725 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5726 {
5727 pclose(pfScriptHandle);
5728 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5729 LogFlowThisFunc(("rc=E_FAIL\n"));
5730 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5731 }
5732 /* Overwrite the terminating newline character. */
5733 acBuffer[cBufSize - 1] = 0;
5734 tapDevice = acBuffer;
5735 }
5736 rc = pclose(pfScriptHandle);
5737 if (!WIFEXITED(rc))
5738 {
5739 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5740 LogFlowThisFunc(("rc=E_FAIL\n"));
5741 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5742 }
5743 if (WEXITSTATUS(rc) != 0)
5744 {
5745 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5746 LogFlowThisFunc(("rc=E_FAIL\n"));
5747 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5748 }
5749 LogFlowThisFunc(("rc=S_OK\n"));
5750 return S_OK;
5751#else /* __LINUX__ not defined */
5752 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5753 return E_NOTIMPL; /* not yet supported */
5754#endif
5755}
5756
5757/**
5758 * Helper function to handle host interface device creation and attachment.
5759 *
5760 * @param networkAdapter the network adapter which attachment should be reset
5761 * @return COM status code
5762 *
5763 * @note The caller must lock this object for writing.
5764 */
5765HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5766{
5767 LogFlowThisFunc(("\n"));
5768 /* sanity check */
5769 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5770
5771#ifdef DEBUG
5772 /* paranoia */
5773 NetworkAttachmentType_T attachment;
5774 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5775 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5776#endif /* DEBUG */
5777
5778 HRESULT rc = S_OK;
5779
5780#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5781 ULONG slot = 0;
5782 rc = networkAdapter->COMGETTER(Slot)(&slot);
5783 AssertComRC(rc);
5784
5785 /*
5786 * Try get the FD.
5787 */
5788 LONG ltapFD;
5789 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5790 if (SUCCEEDED(rc))
5791 maTapFD[slot] = (RTFILE)ltapFD;
5792 else
5793 maTapFD[slot] = NIL_RTFILE;
5794
5795 /*
5796 * Are we supposed to use an existing TAP interface?
5797 */
5798 if (maTapFD[slot] != NIL_RTFILE)
5799 {
5800 /* nothing to do */
5801 Assert(ltapFD >= 0);
5802 Assert((LONG)maTapFD[slot] == ltapFD);
5803 rc = S_OK;
5804 }
5805 else
5806#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5807 {
5808 /*
5809 * Allocate a host interface device
5810 */
5811#ifdef __WIN__
5812 /* nothing to do */
5813 int rcVBox = VINF_SUCCESS;
5814#elif defined(__LINUX__)
5815 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5816 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5817 if (VBOX_SUCCESS(rcVBox))
5818 {
5819 /*
5820 * Set/obtain the tap interface.
5821 */
5822 bool isStatic = false;
5823 struct ifreq IfReq;
5824 memset(&IfReq, 0, sizeof(IfReq));
5825 /* The name of the TAP interface we are using and the TAP setup script resp. */
5826 Bstr tapDeviceName, tapSetupApplication;
5827 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5828 if (FAILED(rc))
5829 {
5830 tapDeviceName.setNull(); /* Is this necessary? */
5831 }
5832 else if (!tapDeviceName.isEmpty())
5833 {
5834 isStatic = true;
5835 /* If we are using a static TAP device then try to open it. */
5836 Utf8Str str(tapDeviceName);
5837 if (str.length() <= sizeof(IfReq.ifr_name))
5838 strcpy(IfReq.ifr_name, str.raw());
5839 else
5840 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5841 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5842 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5843 if (rcVBox != 0)
5844 {
5845 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5846 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5847 tapDeviceName.raw());
5848 }
5849 }
5850 if (SUCCEEDED(rc))
5851 {
5852 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5853 if (tapSetupApplication.isEmpty())
5854 {
5855 if (tapDeviceName.isEmpty())
5856 {
5857 LogRel(("No setup application was supplied for the TAP interface.\n"));
5858 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5859 }
5860 }
5861 else
5862 {
5863 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5864 tapSetupApplication);
5865 }
5866 }
5867 if (SUCCEEDED(rc))
5868 {
5869 if (!isStatic)
5870 {
5871 Utf8Str str(tapDeviceName);
5872 if (str.length() <= sizeof(IfReq.ifr_name))
5873 strcpy(IfReq.ifr_name, str.raw());
5874 else
5875 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5876 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5877 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5878 if (rcVBox != 0)
5879 {
5880 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5881 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5882 }
5883 }
5884 if (SUCCEEDED(rc))
5885 {
5886 /*
5887 * Make it pollable.
5888 */
5889 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5890 {
5891 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5892
5893 /*
5894 * Here is the right place to communicate the TAP file descriptor and
5895 * the host interface name to the server if/when it becomes really
5896 * necessary.
5897 */
5898 maTAPDeviceName[slot] = tapDeviceName;
5899 rcVBox = VINF_SUCCESS;
5900 }
5901 else
5902 {
5903 int iErr = errno;
5904
5905 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5906 rcVBox = VERR_HOSTIF_BLOCKING;
5907 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5908 strerror(errno));
5909 }
5910 }
5911 }
5912 }
5913 else
5914 {
5915 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5916 switch (rcVBox)
5917 {
5918 case VERR_ACCESS_DENIED:
5919 /* will be handled by our caller */
5920 rc = rcVBox;
5921 break;
5922 default:
5923 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
5924 break;
5925 }
5926 }
5927#elif defined(__DARWIN__)
5928 /** @todo Implement tap networking for Darwin. */
5929 int rcVBox = VERR_NOT_IMPLEMENTED;
5930#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
5931# error "PORTME: Implement OS specific TAP interface open/creation."
5932#else
5933# error "Unknown host OS"
5934#endif
5935 /* in case of failure, cleanup. */
5936 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5937 {
5938 LogRel(("General failure attaching to host interface\n"));
5939 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5940 }
5941 }
5942 LogFlowThisFunc(("rc=%d\n", rc));
5943 return rc;
5944}
5945
5946/**
5947 * Helper function to handle detachment from a host interface
5948 *
5949 * @param networkAdapter the network adapter which attachment should be reset
5950 * @return COM status code
5951 *
5952 * @note The caller must lock this object for writing.
5953 */
5954HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5955{
5956 /* sanity check */
5957 LogFlowThisFunc(("\n"));
5958 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5959
5960 HRESULT rc = S_OK;
5961#ifdef DEBUG
5962 /* paranoia */
5963 NetworkAttachmentType_T attachment;
5964 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5965 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
5966#endif /* DEBUG */
5967
5968#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5969
5970 ULONG slot = 0;
5971 rc = networkAdapter->COMGETTER(Slot)(&slot);
5972 AssertComRC(rc);
5973
5974 /* is there an open TAP device? */
5975 if (maTapFD[slot] != NIL_RTFILE)
5976 {
5977 /*
5978 * Close the file handle.
5979 */
5980 Bstr tapDeviceName, tapTerminateApplication;
5981 bool isStatic = true;
5982 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5983 if (FAILED(rc) || tapDeviceName.isEmpty())
5984 {
5985 /* If the name is not empty, this is a dynamic TAP device, so close it now,
5986 so that the termination script can remove the interface. Otherwise we still
5987 need the FD to pass to the termination script. */
5988 isStatic = false;
5989 int rcVBox = RTFileClose(maTapFD[slot]);
5990 AssertRC(rcVBox);
5991 maTapFD[slot] = NIL_RTFILE;
5992 }
5993 /*
5994 * Execute the termination command.
5995 */
5996 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5997 if (tapTerminateApplication)
5998 {
5999 /* Get the program name. */
6000 Utf8Str tapTermAppUtf8(tapTerminateApplication);
6001
6002 /* Build the command line. */
6003 char szCommand[4096];
6004 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
6005 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
6006
6007 /*
6008 * Create the process and wait for it to complete.
6009 */
6010 Log(("Calling the termination command: %s\n", szCommand));
6011 int rcCommand = system(szCommand);
6012 if (rcCommand == -1)
6013 {
6014 LogRel(("Failed to execute the clean up script for the TAP interface"));
6015 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
6016 }
6017 if (!WIFEXITED(rc))
6018 {
6019 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
6020 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
6021 }
6022 if (WEXITSTATUS(rc) != 0)
6023 {
6024 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
6025 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
6026 }
6027 }
6028
6029 if (isStatic)
6030 {
6031 /* If we are using a static TAP device, we close it now, after having called the
6032 termination script. */
6033 int rcVBox = RTFileClose(maTapFD[slot]);
6034 AssertRC(rcVBox);
6035 }
6036 /* the TAP device name and handle are no longer valid */
6037 maTapFD[slot] = NIL_RTFILE;
6038 maTAPDeviceName[slot] = "";
6039 }
6040#endif
6041 LogFlowThisFunc(("returning %d\n", rc));
6042 return rc;
6043}
6044
6045
6046/**
6047 * Called at power down to terminate host interface networking.
6048 *
6049 * @note The caller must lock this object for writing.
6050 */
6051HRESULT Console::powerDownHostInterfaces()
6052{
6053 LogFlowThisFunc (("\n"));
6054
6055 /* sanity check */
6056 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
6057
6058 /*
6059 * host interface termination handling
6060 */
6061 HRESULT rc;
6062 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
6063 {
6064 ComPtr<INetworkAdapter> networkAdapter;
6065 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
6066 CheckComRCBreakRC (rc);
6067
6068 BOOL enabled = FALSE;
6069 networkAdapter->COMGETTER(Enabled) (&enabled);
6070 if (!enabled)
6071 continue;
6072
6073 NetworkAttachmentType_T attachment;
6074 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6075 if (attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment)
6076 {
6077 HRESULT rc2 = detachFromHostInterface(networkAdapter);
6078 if (FAILED(rc2) && SUCCEEDED(rc))
6079 rc = rc2;
6080 }
6081 }
6082
6083 return rc;
6084}
6085
6086
6087/**
6088 * Process callback handler for VMR3Load and VMR3Save.
6089 *
6090 * @param pVM The VM handle.
6091 * @param uPercent Completetion precentage (0-100).
6092 * @param pvUser Pointer to the VMProgressTask structure.
6093 * @return VINF_SUCCESS.
6094 */
6095/*static*/ DECLCALLBACK (int)
6096Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
6097{
6098 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6099 AssertReturn (task, VERR_INVALID_PARAMETER);
6100
6101 /* update the progress object */
6102 if (task->mProgress)
6103 task->mProgress->notifyProgress (uPercent);
6104
6105 return VINF_SUCCESS;
6106}
6107
6108/**
6109 * VM error callback function. Called by the various VM components.
6110 *
6111 * @param pVM The VM handle. Can be NULL if an error occurred before
6112 * successfully creating a VM.
6113 * @param pvUser Pointer to the VMProgressTask structure.
6114 * @param rc VBox status code.
6115 * @param pszFormat The error message.
6116 * @thread EMT.
6117 */
6118/* static */ DECLCALLBACK (void)
6119Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
6120 const char *pszFormat, va_list args)
6121{
6122 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6123 AssertReturnVoid (task);
6124
6125 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
6126 HRESULT hrc = setError (E_FAIL, tr ("%N.\n"
6127 "VBox status code: %d (%Vrc)"),
6128 tr (pszFormat), &args,
6129 rc, rc);
6130 task->mProgress->notifyComplete (hrc);
6131}
6132
6133/**
6134 * VM runtime error callback function.
6135 * See VMSetRuntimeError for the detailed description of parameters.
6136 *
6137 * @param pVM The VM handle.
6138 * @param pvUser The user argument.
6139 * @param fFatal Whether it is a fatal error or not.
6140 * @param pszErrorID Error ID string.
6141 * @param pszFormat Error message format string.
6142 * @param args Error message arguments.
6143 * @thread EMT.
6144 */
6145/* static */ DECLCALLBACK(void)
6146Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
6147 const char *pszErrorID,
6148 const char *pszFormat, va_list args)
6149{
6150 LogFlowFuncEnter();
6151
6152 Console *that = static_cast <Console *> (pvUser);
6153 AssertReturnVoid (that);
6154
6155 Utf8Str message = Utf8StrFmt (pszFormat, args);
6156
6157 LogRel (("Console: VM runtime error: fatal=%RTbool, "
6158 "errorID=%s message=\"%s\"\n",
6159 fFatal, pszErrorID, message.raw()));
6160
6161 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
6162
6163 LogFlowFuncLeave();
6164}
6165
6166/**
6167 * Captures USB devices that match filters of the VM.
6168 * Called at VM startup.
6169 *
6170 * @param pVM The VM handle.
6171 *
6172 * @note The caller must lock this object for writing.
6173 */
6174HRESULT Console::captureUSBDevices (PVM pVM)
6175{
6176 LogFlowThisFunc (("\n"));
6177
6178 /* sanity check */
6179 ComAssertRet (isLockedOnCurrentThread(), E_FAIL);
6180
6181 /* If the machine has an USB controller, ask the USB proxy service to
6182 * capture devices */
6183 PPDMIBASE pBase;
6184 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
6185 if (VBOX_SUCCESS (vrc))
6186 {
6187 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6188 ComAssertComRCRetRC (hrc);
6189 }
6190 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6191 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6192 vrc = VINF_SUCCESS;
6193 else
6194 AssertRC (vrc);
6195
6196 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
6197}
6198
6199
6200/**
6201 * Releases all USB device which is attached to the VM for the
6202 * purpose of clean up and such like.
6203 *
6204 * @note The caller must lock this object for writing.
6205 */
6206void Console::releaseAllUSBDevices (void)
6207{
6208 LogFlowThisFunc (("\n"));
6209
6210 /* sanity check */
6211 AssertReturnVoid (isLockedOnCurrentThread());
6212
6213 mControl->ReleaseAllUSBDevices();
6214 mUSBDevices.clear();
6215}
6216
6217/**
6218 * @note Locks this object for writing.
6219 */
6220#ifdef VRDP_MC
6221void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6222#else
6223void Console::processRemoteUSBDevices (VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6224#endif /* VRDP_MC */
6225{
6226 LogFlowThisFuncEnter();
6227#ifdef VRDP_MC
6228 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6229#else
6230 LogFlowThisFunc (("pDevList=%p, cbDevList = %d\n", pDevList, cbDevList));
6231#endif /* VRDP_MC */
6232
6233 AutoCaller autoCaller (this);
6234 if (!autoCaller.isOk())
6235 {
6236 /* Console has been already uninitialized, deny request */
6237 AssertMsgFailed (("Temporary assertion to prove that it happens, "
6238 "please report to dmik\n"));
6239 LogFlowThisFunc (("Console is already uninitialized\n"));
6240 LogFlowThisFuncLeave();
6241 return;
6242 }
6243
6244 AutoLock alock (this);
6245
6246 /*
6247 * Mark all existing remote USB devices as dirty.
6248 */
6249 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6250 while (it != mRemoteUSBDevices.end())
6251 {
6252 (*it)->dirty (true);
6253 ++ it;
6254 }
6255
6256 /*
6257 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6258 */
6259 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6260 VRDPUSBDEVICEDESC *e = pDevList;
6261
6262 /* The cbDevList condition must be checked first, because the function can
6263 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6264 */
6265 while (cbDevList >= 2 && e->oNext)
6266 {
6267 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6268 e->idVendor, e->idProduct,
6269 e->oProduct? (char *)e + e->oProduct: ""));
6270
6271 bool fNewDevice = true;
6272
6273 it = mRemoteUSBDevices.begin();
6274 while (it != mRemoteUSBDevices.end())
6275 {
6276#ifdef VRDP_MC
6277 if ((*it)->devId () == e->id
6278 && (*it)->clientId () == u32ClientId)
6279#else
6280 if ((*it)->devId () == e->id)
6281#endif /* VRDP_MC */
6282 {
6283 /* The device is already in the list. */
6284 (*it)->dirty (false);
6285 fNewDevice = false;
6286 break;
6287 }
6288
6289 ++ it;
6290 }
6291
6292 if (fNewDevice)
6293 {
6294 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6295 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6296 ));
6297
6298 /* Create the device object and add the new device to list. */
6299 ComObjPtr <RemoteUSBDevice> device;
6300 device.createObject();
6301#ifdef VRDP_MC
6302 device->init (u32ClientId, e);
6303#else
6304 device->init (e);
6305#endif /* VRDP_MC */
6306
6307 mRemoteUSBDevices.push_back (device);
6308
6309 /* Check if the device is ok for current USB filters. */
6310 BOOL fMatched = FALSE;
6311
6312 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched);
6313
6314 AssertComRC (hrc);
6315
6316 LogFlowThisFunc (("USB filters return %d\n", fMatched));
6317
6318 if (fMatched)
6319 {
6320 hrc = onUSBDeviceAttach (device, NULL);
6321
6322 /// @todo (r=dmik) warning reporting subsystem
6323
6324 if (hrc == S_OK)
6325 {
6326 LogFlowThisFunc (("Device attached\n"));
6327 device->captured (true);
6328 }
6329 }
6330 }
6331
6332 if (cbDevList < e->oNext)
6333 {
6334 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6335 cbDevList, e->oNext));
6336 break;
6337 }
6338
6339 cbDevList -= e->oNext;
6340
6341 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6342 }
6343
6344 /*
6345 * Remove dirty devices, that is those which are not reported by the server anymore.
6346 */
6347 for (;;)
6348 {
6349 ComObjPtr <RemoteUSBDevice> device;
6350
6351 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6352 while (it != mRemoteUSBDevices.end())
6353 {
6354 if ((*it)->dirty ())
6355 {
6356 device = *it;
6357 break;
6358 }
6359
6360 ++ it;
6361 }
6362
6363 if (!device)
6364 {
6365 break;
6366 }
6367
6368 USHORT vendorId = 0;
6369 device->COMGETTER(VendorId) (&vendorId);
6370
6371 USHORT productId = 0;
6372 device->COMGETTER(ProductId) (&productId);
6373
6374 Bstr product;
6375 device->COMGETTER(Product) (product.asOutParam());
6376
6377 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6378 vendorId, productId, product.raw ()
6379 ));
6380
6381 /* Detach the device from VM. */
6382 if (device->captured ())
6383 {
6384 Guid uuid;
6385 device->COMGETTER (Id) (uuid.asOutParam());
6386 onUSBDeviceDetach (uuid, NULL);
6387 }
6388
6389 /* And remove it from the list. */
6390 mRemoteUSBDevices.erase (it);
6391 }
6392
6393 LogFlowThisFuncLeave();
6394}
6395
6396
6397
6398/**
6399 * Thread function which starts the VM (also from saved state) and
6400 * track progress.
6401 *
6402 * @param Thread The thread id.
6403 * @param pvUser Pointer to a VMPowerUpTask structure.
6404 * @return VINF_SUCCESS (ignored).
6405 *
6406 * @note Locks the Console object for writing.
6407 */
6408/*static*/
6409DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6410{
6411 LogFlowFuncEnter();
6412
6413 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6414 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6415
6416 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6417 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6418
6419#if defined(__WIN__)
6420 {
6421 /* initialize COM */
6422 HRESULT hrc = CoInitializeEx (NULL,
6423 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6424 COINIT_SPEED_OVER_MEMORY);
6425 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6426 }
6427#endif
6428
6429 HRESULT hrc = S_OK;
6430 int vrc = VINF_SUCCESS;
6431
6432 ComObjPtr <Console> console = task->mConsole;
6433
6434 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6435
6436 AutoLock alock (console);
6437
6438 /* sanity */
6439 Assert (console->mpVM == NULL);
6440
6441 do
6442 {
6443 /*
6444 * Initialize the release logging facility. In case something
6445 * goes wrong, there will be no release logging. Maybe in the future
6446 * we can add some logic to use different file names in this case.
6447 * Note that the logic must be in sync with Machine::DeleteSettings().
6448 */
6449
6450 Bstr logFolder;
6451 hrc = console->mMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
6452 CheckComRCBreakRC (hrc);
6453
6454 Utf8Str logDir = logFolder;
6455
6456 /* make sure the Logs folder exists */
6457 Assert (!logDir.isEmpty());
6458 if (!RTDirExists (logDir))
6459 RTDirCreateFullPath (logDir, 0777);
6460
6461 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
6462 logDir.raw(), RTPATH_DELIMITER);
6463
6464 /*
6465 * Age the old log files
6466 * Rename .2 to .3, .1 to .2 and the last log file to .1
6467 * Overwrite target files in case they exist;
6468 */
6469 for (int i = 2; i >= 0; i--)
6470 {
6471 Utf8Str oldName;
6472 if (i > 0)
6473 oldName = Utf8StrFmt ("%s.%d", logFile.raw(), i);
6474 else
6475 oldName = logFile;
6476 Utf8Str newName = Utf8StrFmt ("%s.%d", logFile.raw(), i + 1);
6477 RTFileRename(oldName.raw(), newName.raw(), RTFILEMOVE_FLAGS_REPLACE);
6478 }
6479
6480 PRTLOGGER loggerRelease;
6481 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
6482 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
6483#ifdef __WIN__
6484 fFlags |= RTLOGFLAGS_USECRLF;
6485#endif /* __WIN__ */
6486 vrc = RTLogCreate(&loggerRelease, fFlags, "all",
6487 "VBOX_RELEASE_LOG", ELEMENTS(s_apszGroups), s_apszGroups,
6488 RTLOGDEST_FILE, logFile.raw());
6489 if (VBOX_SUCCESS(vrc))
6490 {
6491 /* some introductory information */
6492 RTTIMESPEC timeSpec;
6493 char nowUct[64];
6494 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
6495 RTLogRelLogger(loggerRelease, 0, ~0U,
6496 "VirtualBox %s (%s %s) release log\n"
6497 "Log opened %s\n",
6498 VBOX_VERSION_STRING, __DATE__, __TIME__,
6499 nowUct);
6500
6501 /* register this logger as the release logger */
6502 RTLogRelSetDefaultInstance(loggerRelease);
6503 }
6504 else
6505 {
6506 hrc = setError (E_FAIL,
6507 tr ("Failed to open release log file '%s' (%Vrc)"),
6508 logFile.raw(), vrc);
6509 break;
6510 }
6511
6512#ifdef VBOX_VRDP
6513 if (VBOX_SUCCESS (vrc))
6514 {
6515 /* Create the VRDP server. In case of headless operation, this will
6516 * also create the framebuffer, required at VM creation.
6517 */
6518 ConsoleVRDPServer *server = console->consoleVRDPServer();
6519 Assert (server);
6520 /// @todo (dmik)
6521 // does VRDP server call Console from the other thread?
6522 // Not sure, so leave the lock just in case
6523 alock.leave();
6524 vrc = server->Launch();
6525 alock.enter();
6526 if (VBOX_FAILURE (vrc))
6527 {
6528 Utf8Str errMsg;
6529 switch (vrc)
6530 {
6531 case VERR_NET_ADDRESS_IN_USE:
6532 {
6533 ULONG port = 0;
6534 console->mVRDPServer->COMGETTER(Port) (&port);
6535 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6536 port);
6537 break;
6538 }
6539 default:
6540 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6541 vrc);
6542 }
6543 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6544 vrc, errMsg.raw()));
6545 hrc = setError (E_FAIL, errMsg);
6546 break;
6547 }
6548 }
6549#endif /* VBOX_VRDP */
6550
6551 /*
6552 * Create the VM
6553 */
6554 PVM pVM;
6555 /*
6556 * leave the lock since EMT will call Console. It's safe because
6557 * mMachineState is either Starting or Restoring state here.
6558 */
6559 alock.leave();
6560
6561 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6562 task->mConfigConstructor, task.get(),
6563 &pVM);
6564
6565 alock.enter();
6566
6567#ifdef VBOX_VRDP
6568 {
6569 /* Enable client connections to the server. */
6570 ConsoleVRDPServer *server = console->consoleVRDPServer();
6571 server->SetCallback ();
6572 }
6573#endif /* VBOX_VRDP */
6574
6575 if (VBOX_SUCCESS (vrc))
6576 {
6577 do
6578 {
6579 /*
6580 * Register our load/save state file handlers
6581 */
6582 vrc = SSMR3RegisterExternal (pVM,
6583 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6584 0 /* cbGuess */,
6585 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6586 static_cast <Console *> (console));
6587 AssertRC (vrc);
6588 if (VBOX_FAILURE (vrc))
6589 break;
6590
6591 /*
6592 * Synchronize debugger settings
6593 */
6594 MachineDebugger *machineDebugger = console->getMachineDebugger();
6595 if (machineDebugger)
6596 {
6597 machineDebugger->flushQueuedSettings();
6598 }
6599
6600 if (console->getVMMDev()->isShFlActive())
6601 {
6602 /// @todo (dmik)
6603 // does the code below call Console from the other thread?
6604 // Not sure, so leave the lock just in case
6605 alock.leave();
6606
6607 /*
6608 * Shared Folders
6609 */
6610 for (std::map <Bstr, ComPtr <ISharedFolder> >::const_iterator
6611 it = task->mSharedFolders.begin();
6612 it != task->mSharedFolders.end();
6613 ++ it)
6614 {
6615 Bstr name = (*it).first;
6616 ComPtr <ISharedFolder> folder = (*it).second;
6617
6618 Bstr hostPath;
6619 hrc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
6620 CheckComRCBreakRC (hrc);
6621
6622 LogFlowFunc (("Adding shared folder '%ls' -> '%ls'\n",
6623 name.raw(), hostPath.raw()));
6624 ComAssertBreak (!name.isEmpty() && !hostPath.isEmpty(),
6625 hrc = E_FAIL);
6626
6627 /** @todo should move this into the shared folder class */
6628 VBOXHGCMSVCPARM parms[2];
6629 SHFLSTRING *pFolderName, *pMapName;
6630 int cbString;
6631
6632 cbString = (hostPath.length() + 1) * sizeof(RTUCS2);
6633 pFolderName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6634 Assert(pFolderName);
6635 memcpy(pFolderName->String.ucs2, hostPath.raw(), cbString);
6636
6637 pFolderName->u16Size = cbString;
6638 pFolderName->u16Length = cbString - sizeof(RTUCS2);
6639
6640 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
6641 parms[0].u.pointer.addr = pFolderName;
6642 parms[0].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6643
6644 cbString = (name.length() + 1) * sizeof(RTUCS2);
6645 pMapName = (SHFLSTRING *)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
6646 Assert(pMapName);
6647 memcpy(pMapName->String.ucs2, name.raw(), cbString);
6648
6649 pMapName->u16Size = cbString;
6650 pMapName->u16Length = cbString - sizeof(RTUCS2);
6651
6652 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
6653 parms[1].u.pointer.addr = pMapName;
6654 parms[1].u.pointer.size = sizeof(SHFLSTRING) + cbString;
6655
6656 vrc = console->getVMMDev()->hgcmHostCall("VBoxSharedFolders",
6657 SHFL_FN_ADD_MAPPING, 2, &parms[0]);
6658
6659 RTMemFree(pFolderName);
6660 RTMemFree(pMapName);
6661
6662 if (VBOX_FAILURE (vrc))
6663 {
6664 hrc = setError (E_FAIL,
6665 tr ("Unable to add mapping '%ls' to '%ls' (%Vrc)"),
6666 hostPath.raw(), name.raw(), vrc);
6667 break;
6668 }
6669 }
6670
6671 /* enter the lock again */
6672 alock.enter();
6673
6674 CheckComRCBreakRC (hrc);
6675 }
6676
6677 /*
6678 * Capture USB devices.
6679 */
6680 hrc = console->captureUSBDevices (pVM);
6681 CheckComRCBreakRC (hrc);
6682
6683 /* leave the lock before a lengthy operation */
6684 alock.leave();
6685
6686 /* Load saved state? */
6687 if (!!task->mSavedStateFile)
6688 {
6689 LogFlowFunc (("Restoring saved state from '%s'...\n",
6690 task->mSavedStateFile.raw()));
6691
6692 vrc = VMR3Load (pVM, task->mSavedStateFile,
6693 Console::stateProgressCallback,
6694 static_cast <VMProgressTask *> (task.get()));
6695
6696 /* Start/Resume the VM execution */
6697 if (VBOX_SUCCESS (vrc))
6698 {
6699 vrc = VMR3Resume (pVM);
6700 AssertRC (vrc);
6701 }
6702
6703 /* Power off in case we failed loading or resuming the VM */
6704 if (VBOX_FAILURE (vrc))
6705 {
6706 int vrc2 = VMR3PowerOff (pVM);
6707 AssertRC (vrc2);
6708 }
6709 }
6710 else
6711 {
6712 /* Power on the VM (i.e. start executing) */
6713 vrc = VMR3PowerOn(pVM);
6714 AssertRC (vrc);
6715 }
6716
6717 /* enter the lock again */
6718 alock.enter();
6719 }
6720 while (0);
6721
6722 /* On failure, destroy the VM */
6723 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6724 {
6725 /* preserve existing error info */
6726 ErrorInfoKeeper eik;
6727
6728 /*
6729 * powerDown() will call VMR3Destroy() and do all necessary
6730 * cleanup (VRDP, USB devices)
6731 */
6732 HRESULT hrc2 = console->powerDown();
6733 AssertComRC (hrc2);
6734 }
6735 }
6736 else
6737 {
6738 /*
6739 * If VMR3Create() failed it has released the VM memory.
6740 */
6741 console->mpVM = NULL;
6742 }
6743
6744 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6745 {
6746 /*
6747 * If VMR3Create() or one of the other calls in this function fail,
6748 * an appropriate error message has been already set. However since
6749 * that happens via a callback, the status code in this function is
6750 * not updated.
6751 */
6752 if (!task->mProgress->completed())
6753 {
6754 /*
6755 * If the COM error info is not yet set but we've got a
6756 * failure, convert the VBox status code into a meaningful
6757 * error message. This becomes unused once all the sources of
6758 * errors set the appropriate error message themselves.
6759 * Note that we don't use VMSetError() below because pVM is
6760 * either invalid or NULL here.
6761 */
6762 AssertMsgFailed (("Missing error message during powerup for "
6763 "status code %Vrc\n", vrc));
6764 hrc = setError (E_FAIL,
6765 tr ("Failed to start VM execution (%Vrc)"), vrc);
6766 }
6767 else
6768 hrc = task->mProgress->resultCode();
6769
6770 Assert (FAILED (hrc));
6771 break;
6772 }
6773 }
6774 while (0);
6775
6776 if (console->mMachineState == MachineState_Starting ||
6777 console->mMachineState == MachineState_Restoring)
6778 {
6779 /*
6780 * We are still in the Starting/Restoring state. This means one of:
6781 * 1) we failed before VMR3Create() was called;
6782 * 2) VMR3Create() failed.
6783 * In both cases, there is no need to call powerDown(), but we still
6784 * need to go back to the PoweredOff/Saved state. Reuse
6785 * vmstateChangeCallback() for that purpose.
6786 */
6787
6788 /* preserve existing error info */
6789 ErrorInfoKeeper eik;
6790
6791 Assert (console->mpVM == NULL);
6792 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6793 console);
6794 }
6795
6796 /*
6797 * Evaluate the final result.
6798 * Note that the appropriate mMachineState value is already set by
6799 * vmstateChangeCallback() in all cases.
6800 */
6801
6802 /* leave the lock, don't need it any more */
6803 alock.leave();
6804
6805 if (SUCCEEDED (hrc))
6806 {
6807 /* Notify the progress object of the success */
6808 task->mProgress->notifyComplete (S_OK);
6809 }
6810 else
6811 {
6812 if (!task->mProgress->completed())
6813 {
6814 /* The progress object will fetch the current error info. This
6815 * gets the errors signalled by using setError(). The ones
6816 * signalled via VMSetError() immediately notify the progress
6817 * object that the operation is completed. */
6818 task->mProgress->notifyComplete (hrc);
6819 }
6820
6821 LogRel (("Power up failed (vrc=%Vrc, hrc=0x%08X)\n", vrc, hrc));
6822 }
6823
6824#if defined(__WIN__)
6825 /* uninitialize COM */
6826 CoUninitialize();
6827#endif
6828
6829 LogFlowFuncLeave();
6830
6831 return VINF_SUCCESS;
6832}
6833
6834
6835/**
6836 * Reconfigures a VDI.
6837 *
6838 * @param pVM The VM handle.
6839 * @param hda The harddisk attachment.
6840 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6841 * @return VBox status code.
6842 */
6843static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6844{
6845 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6846
6847 int rc;
6848 HRESULT hrc;
6849 char *psz = NULL;
6850 BSTR str = NULL;
6851 *phrc = S_OK;
6852#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
6853#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6854#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6855#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6856
6857 /*
6858 * Figure out which IDE device this is.
6859 */
6860 ComPtr<IHardDisk> hardDisk;
6861 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6862 DiskControllerType_T enmCtl;
6863 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
6864 LONG lDev;
6865 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
6866
6867 int i;
6868 switch (enmCtl)
6869 {
6870 case DiskControllerType_IDE0Controller:
6871 i = 0;
6872 break;
6873 case DiskControllerType_IDE1Controller:
6874 i = 2;
6875 break;
6876 default:
6877 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
6878 return VERR_GENERAL_FAILURE;
6879 }
6880
6881 if (lDev < 0 || lDev >= 2)
6882 {
6883 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6884 return VERR_GENERAL_FAILURE;
6885 }
6886
6887 i = i + lDev;
6888
6889 /*
6890 * Is there an existing LUN? If not create it.
6891 * We ASSUME that this will NEVER collide with the DVD.
6892 */
6893 PCFGMNODE pCfg;
6894 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", i);
6895 if (!pLunL1)
6896 {
6897 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6898 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6899
6900 PCFGMNODE pLunL0;
6901 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", i); RC_CHECK();
6902 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6903 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6904 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6905 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6906
6907 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6908 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6909 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6910 }
6911 else
6912 {
6913#ifdef VBOX_STRICT
6914 char *pszDriver;
6915 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6916 Assert(!strcmp(pszDriver, "VBoxHDD"));
6917 MMR3HeapFree(pszDriver);
6918#endif
6919
6920 /*
6921 * Check if things has changed.
6922 */
6923 pCfg = CFGMR3GetChild(pLunL1, "Config");
6924 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6925
6926 /* the image */
6927 /// @todo (dmik) we temporarily use the location property to
6928 // determine the image file name. This is subject to change
6929 // when iSCSI disks are here (we should either query a
6930 // storage-specific interface from IHardDisk, or "standardize"
6931 // the location property)
6932 hrc = hardDisk->COMGETTER(Location)(&str); H();
6933 STR_CONV();
6934 char *pszPath;
6935 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6936 if (!strcmp(psz, pszPath))
6937 {
6938 /* parent images. */
6939 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6940 for (PCFGMNODE pParent = pCfg;;)
6941 {
6942 MMR3HeapFree(pszPath);
6943 pszPath = NULL;
6944 STR_FREE();
6945
6946 /* get parent */
6947 ComPtr<IHardDisk> curHardDisk;
6948 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6949 PCFGMNODE pCur;
6950 pCur = CFGMR3GetChild(pParent, "Parent");
6951 if (!pCur && !curHardDisk)
6952 {
6953 /* no change */
6954 LogFlowFunc (("No change!\n"));
6955 return VINF_SUCCESS;
6956 }
6957 if (!pCur || !curHardDisk)
6958 break;
6959
6960 /* compare paths. */
6961 /// @todo (dmik) we temporarily use the location property to
6962 // determine the image file name. This is subject to change
6963 // when iSCSI disks are here (we should either query a
6964 // storage-specific interface from IHardDisk, or "standardize"
6965 // the location property)
6966 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6967 STR_CONV();
6968 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6969 if (strcmp(psz, pszPath))
6970 break;
6971
6972 /* next */
6973 pParent = pCur;
6974 parentHardDisk = curHardDisk;
6975 }
6976
6977 }
6978 else
6979 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", i, pszPath));
6980
6981 MMR3HeapFree(pszPath);
6982 STR_FREE();
6983
6984 /*
6985 * Detach the driver and replace the config node.
6986 */
6987 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, i); RC_CHECK();
6988 CFGMR3RemoveNode(pCfg);
6989 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6990 }
6991
6992 /*
6993 * Create the driver configuration.
6994 */
6995 /// @todo (dmik) we temporarily use the location property to
6996 // determine the image file name. This is subject to change
6997 // when iSCSI disks are here (we should either query a
6998 // storage-specific interface from IHardDisk, or "standardize"
6999 // the location property)
7000 hrc = hardDisk->COMGETTER(Location)(&str); H();
7001 STR_CONV();
7002 LogFlowFunc (("LUN#%d: leaf image '%s'\n", i, psz));
7003 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
7004 STR_FREE();
7005 /* Create an inversed tree of parents. */
7006 ComPtr<IHardDisk> parentHardDisk = hardDisk;
7007 for (PCFGMNODE pParent = pCfg;;)
7008 {
7009 ComPtr<IHardDisk> curHardDisk;
7010 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
7011 if (!curHardDisk)
7012 break;
7013
7014 PCFGMNODE pCur;
7015 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
7016 /// @todo (dmik) we temporarily use the location property to
7017 // determine the image file name. This is subject to change
7018 // when iSCSI disks are here (we should either query a
7019 // storage-specific interface from IHardDisk, or "standardize"
7020 // the location property)
7021 hrc = curHardDisk->COMGETTER(Location)(&str); H();
7022 STR_CONV();
7023 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
7024 STR_FREE();
7025
7026 /* next */
7027 pParent = pCur;
7028 parentHardDisk = curHardDisk;
7029 }
7030
7031 /*
7032 * Attach the new driver.
7033 */
7034 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, i, NULL); RC_CHECK();
7035
7036 LogFlowFunc (("Returns success\n"));
7037 return rc;
7038}
7039
7040
7041/**
7042 * Thread for executing the saved state operation.
7043 *
7044 * @param Thread The thread handle.
7045 * @param pvUser Pointer to a VMSaveTask structure.
7046 * @return VINF_SUCCESS (ignored).
7047 *
7048 * @note Locks the Console object for writing.
7049 */
7050/*static*/
7051DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
7052{
7053 LogFlowFuncEnter();
7054
7055 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
7056 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7057
7058 Assert (!task->mSavedStateFile.isNull());
7059 Assert (!task->mProgress.isNull());
7060
7061 const ComObjPtr <Console> &that = task->mConsole;
7062
7063 /*
7064 * Note: no need to use addCaller() to protect Console or addVMCaller() to
7065 * protect mpVM because VMSaveTask does that
7066 */
7067
7068 Utf8Str errMsg;
7069 HRESULT rc = S_OK;
7070
7071 if (task->mIsSnapshot)
7072 {
7073 Assert (!task->mServerProgress.isNull());
7074 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
7075
7076 rc = task->mServerProgress->WaitForCompletion (-1);
7077 if (SUCCEEDED (rc))
7078 {
7079 HRESULT result = S_OK;
7080 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
7081 if (SUCCEEDED (rc))
7082 rc = result;
7083 }
7084 }
7085
7086 if (SUCCEEDED (rc))
7087 {
7088 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
7089
7090 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
7091 Console::stateProgressCallback,
7092 static_cast <VMProgressTask *> (task.get()));
7093 if (VBOX_FAILURE (vrc))
7094 {
7095 errMsg = Utf8StrFmt (
7096 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
7097 task->mSavedStateFile.raw(), vrc);
7098 rc = E_FAIL;
7099 }
7100 }
7101
7102 /* lock the console sonce we're going to access it */
7103 AutoLock thatLock (that);
7104
7105 if (SUCCEEDED (rc))
7106 {
7107 if (task->mIsSnapshot)
7108 do
7109 {
7110 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
7111
7112 ComPtr <IHardDiskAttachmentCollection> hdaColl;
7113 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
7114 if (FAILED (rc))
7115 break;
7116 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
7117 rc = hdaColl->Enumerate (hdaEn.asOutParam());
7118 if (FAILED (rc))
7119 break;
7120 BOOL more = FALSE;
7121 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
7122 {
7123 ComPtr <IHardDiskAttachment> hda;
7124 rc = hdaEn->GetNext (hda.asOutParam());
7125 if (FAILED (rc))
7126 break;
7127
7128 PVMREQ pReq;
7129 IHardDiskAttachment *pHda = hda;
7130 /*
7131 * don't leave the lock since reconfigureVDI isn't going to
7132 * access Console.
7133 */
7134 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
7135 (PFNRT)reconfigureVDI, 3, that->mpVM,
7136 pHda, &rc);
7137 if (VBOX_SUCCESS (rc))
7138 rc = pReq->iStatus;
7139 VMR3ReqFree (pReq);
7140 if (FAILED (rc))
7141 break;
7142 if (VBOX_FAILURE (vrc))
7143 {
7144 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
7145 rc = E_FAIL;
7146 break;
7147 }
7148 }
7149 }
7150 while (0);
7151 }
7152
7153 /* finalize the procedure regardless of the result */
7154 if (task->mIsSnapshot)
7155 {
7156 /*
7157 * finalize the requested snapshot object.
7158 * This will reset the machine state to the state it had right
7159 * before calling mControl->BeginTakingSnapshot().
7160 */
7161 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
7162 }
7163 else
7164 {
7165 /*
7166 * finalize the requested save state procedure.
7167 * In case of success, the server will set the machine state to Saved;
7168 * in case of failure it will reset the it to the state it had right
7169 * before calling mControl->BeginSavingState().
7170 */
7171 that->mControl->EndSavingState (SUCCEEDED (rc));
7172 }
7173
7174 /* synchronize the state with the server */
7175 if (task->mIsSnapshot || FAILED (rc))
7176 {
7177 if (task->mLastMachineState == MachineState_Running)
7178 {
7179 /* restore the paused state if appropriate */
7180 that->setMachineStateLocally (MachineState_Paused);
7181 /* restore the running state if appropriate */
7182 that->Resume();
7183 }
7184 else
7185 that->setMachineStateLocally (task->mLastMachineState);
7186 }
7187 else
7188 {
7189 /*
7190 * The machine has been successfully saved, so power it down
7191 * (vmstateChangeCallback() will set state to Saved on success).
7192 * Note: we release the task's VM caller, otherwise it will
7193 * deadlock.
7194 */
7195 task->releaseVMCaller();
7196
7197 rc = that->powerDown();
7198 }
7199
7200 /* notify the progress object about operation completion */
7201 if (SUCCEEDED (rc))
7202 task->mProgress->notifyComplete (S_OK);
7203 else
7204 {
7205 if (!errMsg.isNull())
7206 task->mProgress->notifyComplete (rc,
7207 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
7208 else
7209 task->mProgress->notifyComplete (rc);
7210 }
7211
7212 LogFlowFuncLeave();
7213 return VINF_SUCCESS;
7214}
7215
7216/**
7217 * Thread for powering down the Console.
7218 *
7219 * @param Thread The thread handle.
7220 * @param pvUser Pointer to the VMTask structure.
7221 * @return VINF_SUCCESS (ignored).
7222 *
7223 * @note Locks the Console object for writing.
7224 */
7225/*static*/
7226DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
7227{
7228 LogFlowFuncEnter();
7229
7230 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
7231 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7232
7233 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
7234
7235 const ComObjPtr <Console> &that = task->mConsole;
7236
7237 /*
7238 * Note: no need to use addCaller() to protect Console
7239 * because VMTask does that
7240 */
7241
7242 /* release VM caller to let powerDown() proceed */
7243 task->releaseVMCaller();
7244
7245 HRESULT rc = that->powerDown();
7246 AssertComRC (rc);
7247
7248 LogFlowFuncLeave();
7249 return VINF_SUCCESS;
7250}
7251
7252/**
7253 * The Main status driver instance data.
7254 */
7255typedef struct DRVMAINSTATUS
7256{
7257 /** The LED connectors. */
7258 PDMILEDCONNECTORS ILedConnectors;
7259 /** Pointer to the LED ports interface above us. */
7260 PPDMILEDPORTS pLedPorts;
7261 /** Pointer to the array of LED pointers. */
7262 PPDMLED *papLeds;
7263 /** The unit number corresponding to the first entry in the LED array. */
7264 RTUINT iFirstLUN;
7265 /** The unit number corresponding to the last entry in the LED array.
7266 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7267 RTUINT iLastLUN;
7268} DRVMAINSTATUS, *PDRVMAINSTATUS;
7269
7270
7271/**
7272 * Notification about a unit which have been changed.
7273 *
7274 * The driver must discard any pointers to data owned by
7275 * the unit and requery it.
7276 *
7277 * @param pInterface Pointer to the interface structure containing the called function pointer.
7278 * @param iLUN The unit number.
7279 */
7280DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7281{
7282 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7283 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7284 {
7285 PPDMLED pLed;
7286 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7287 if (VBOX_FAILURE(rc))
7288 pLed = NULL;
7289 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7290 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7291 }
7292}
7293
7294
7295/**
7296 * Queries an interface to the driver.
7297 *
7298 * @returns Pointer to interface.
7299 * @returns NULL if the interface was not supported by the driver.
7300 * @param pInterface Pointer to this interface structure.
7301 * @param enmInterface The requested interface identification.
7302 */
7303DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7304{
7305 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7306 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7307 switch (enmInterface)
7308 {
7309 case PDMINTERFACE_BASE:
7310 return &pDrvIns->IBase;
7311 case PDMINTERFACE_LED_CONNECTORS:
7312 return &pDrv->ILedConnectors;
7313 default:
7314 return NULL;
7315 }
7316}
7317
7318
7319/**
7320 * Destruct a status driver instance.
7321 *
7322 * @returns VBox status.
7323 * @param pDrvIns The driver instance data.
7324 */
7325DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7326{
7327 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7328 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7329 if (pData->papLeds)
7330 {
7331 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7332 while (iLed-- > 0)
7333 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7334 }
7335}
7336
7337
7338/**
7339 * Construct a status driver instance.
7340 *
7341 * @returns VBox status.
7342 * @param pDrvIns The driver instance data.
7343 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7344 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7345 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7346 * iInstance it's expected to be used a bit in this function.
7347 */
7348DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7349{
7350 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7351 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7352
7353 /*
7354 * Validate configuration.
7355 */
7356 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7357 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7358 PPDMIBASE pBaseIgnore;
7359 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7360 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7361 {
7362 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7363 return VERR_PDM_DRVINS_NO_ATTACH;
7364 }
7365
7366 /*
7367 * Data.
7368 */
7369 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7370 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7371
7372 /*
7373 * Read config.
7374 */
7375 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7376 if (VBOX_FAILURE(rc))
7377 {
7378 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7379 return rc;
7380 }
7381
7382 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7383 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7384 pData->iFirstLUN = 0;
7385 else if (VBOX_FAILURE(rc))
7386 {
7387 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7388 return rc;
7389 }
7390
7391 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7392 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7393 pData->iLastLUN = 0;
7394 else if (VBOX_FAILURE(rc))
7395 {
7396 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7397 return rc;
7398 }
7399 if (pData->iFirstLUN > pData->iLastLUN)
7400 {
7401 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7402 return VERR_GENERAL_FAILURE;
7403 }
7404
7405 /*
7406 * Get the ILedPorts interface of the above driver/device and
7407 * query the LEDs we want.
7408 */
7409 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7410 if (!pData->pLedPorts)
7411 {
7412 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7413 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7414 }
7415
7416 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7417 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7418
7419 return VINF_SUCCESS;
7420}
7421
7422
7423/**
7424 * Keyboard driver registration record.
7425 */
7426const PDMDRVREG Console::DrvStatusReg =
7427{
7428 /* u32Version */
7429 PDM_DRVREG_VERSION,
7430 /* szDriverName */
7431 "MainStatus",
7432 /* pszDescription */
7433 "Main status driver (Main as in the API).",
7434 /* fFlags */
7435 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7436 /* fClass. */
7437 PDM_DRVREG_CLASS_STATUS,
7438 /* cMaxInstances */
7439 ~0,
7440 /* cbInstance */
7441 sizeof(DRVMAINSTATUS),
7442 /* pfnConstruct */
7443 Console::drvStatus_Construct,
7444 /* pfnDestruct */
7445 Console::drvStatus_Destruct,
7446 /* pfnIOCtl */
7447 NULL,
7448 /* pfnPowerOn */
7449 NULL,
7450 /* pfnReset */
7451 NULL,
7452 /* pfnSuspend */
7453 NULL,
7454 /* pfnResume */
7455 NULL,
7456 /* pfnDetach */
7457 NULL
7458};
7459
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