VirtualBox

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

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

Some sketchy PDMUsb changes (disabled of course).

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