VirtualBox

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

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

Main: Fixed compiler warnings.

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