VirtualBox

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

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

Added USB status led

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

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