VirtualBox

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

Last change on this file since 16560 was 16364, checked in by vboxsync, 15 years ago

Main: Fixed: Error text is lost if the error happened in the middle of Console::powerUp() or later (e.g. a failure to create the release log file).

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

© 2023 Oracle
ContactPrivacy policyTerms of Use