VirtualBox

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

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

make VBOX_WITH_NETFLT= compile on Linux hosts again

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

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