VirtualBox

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

Last change on this file since 18499 was 18493, checked in by vboxsync, 15 years ago

ConsoleImpl.cpp: size_t warnings.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use