VirtualBox

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

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

Resurrect old VMDK code and make it default.

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

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