VirtualBox

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

最後變更 在這個檔案從5743是 5743,由 vboxsync 提交於 17 年 前

space

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

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