VirtualBox

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

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

Main: Dont mix iprt rc (int) and COM rc (HRESULT).

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

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