VirtualBox

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

Last change on this file since 4041 was 4041, checked in by vboxsync, 17 years ago

Main: Shared Folders (#2130):

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