VirtualBox

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

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

E1000: Added support for 82545EM (MT Server)

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