VirtualBox

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

Last change on this file since 14815 was 14793, checked in by vboxsync, 16 years ago

Add missing space in string literal.

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

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