VirtualBox

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

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

Main: More precise check of whether the VM is running or not when USB attach/detach notifications arrive.

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