VirtualBox

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

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

Main: Ported latest dmik/exp branch changes (r21219:21226) into the trunk.

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