VirtualBox

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

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

Main: Pass inaccessible shared folders to the guest instead of silently ignoring them (#2425).

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

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