VirtualBox

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

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

Main: Improved serial port API (mostly spelling);
FE/Qt: Improved serial port UI (spelling and duplicate handling).

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

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