VirtualBox

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

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

HostServices/GuestProperties and Main: support property flags - the values are not yet checked

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

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