VirtualBox

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

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

Fixes to Linux host networking and a manual update

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

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