VirtualBox

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

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

Main: Fixed: CD/DVD and Floppy not locked for reading when manually attached at VM runtime (#3504).

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