VirtualBox

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

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

Moved shared folders status led

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