VirtualBox

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

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

Main/GUI: Implemented the Stuck state.

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

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