VirtualBox

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

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

#3285: Improve error handling API to include unique error numbers

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