VirtualBox

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

Last change on this file since 16250 was 16207, checked in by vboxsync, 16 years ago

Replaced iterations over IHostNetworkInterface array with FindHostNetworkInterfaceById and FindHostNetworkInterfaceByName where appropriate.

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