VirtualBox

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

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

Main & All Frontends: Prototyped a bunch of Main API changes (IVirtualBoxErrorInfo extension for cascading errors; IMachine/IConsoleCallback extension to properly activate the console window; IVirtualBoxCallback::onExtraDataCanChange() support for error messages; minor IHost::createUSBDeviceFilter/removeUSBDeviceFilter corrections).

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