VirtualBox

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

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

Main: use the HGCM guest property change notification interface and do some clean ups

  • 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 szPropFlags[0] = '\0'; /* default */
4497 vrc = CFGMR3GetValueName (pValue, szPropName, sizeof(szPropName));
4498 if (RT_SUCCESS(vrc))
4499 vrc = CFGMR3QueryString (pValues, szPropName, szPropValue, sizeof(szPropValue));
4500 if (RT_SUCCESS(vrc))
4501 {
4502 CFGMR3QueryString (pFlags, szPropName, szPropFlags, sizeof(szPropFlags));
4503 CFGMR3QueryU64 (pTimestamps, szPropName, &u64Timestamp);
4504 Bstr(szPropName).cloneTo(&names[iProp]);
4505 Bstr(szPropValue).cloneTo(&values[iProp]);
4506 timestamps[iProp] = u64Timestamp;
4507 Bstr(szPropFlags).cloneTo(&flags[iProp]);
4508 pValue = CFGMR3GetNextValue (pValue);
4509 ++iProp;
4510 if (iProp >= cValues)
4511 vrc = VERR_TOO_MUCH_DATA;
4512 }
4513 }
4514 if (RT_SUCCESS(vrc) || (VERR_TOO_MUCH_DATA == vrc))
4515 {
4516 /* PushGuestProperties() calls DiscardSettings(), which calls us back */
4517 alock.leave();
4518 mControl->PushGuestProperties(ComSafeArrayAsInParam (names),
4519 ComSafeArrayAsInParam (values),
4520 ComSafeArrayAsInParam (timestamps),
4521 ComSafeArrayAsInParam (flags));
4522 alock.enter();
4523 }
4524# endif /* VBOX_WITH_GUEST_PROPS defined */
4525#endif /* VBOX_WITH_HGCM */
4526
4527 /* First, wait for all mpVM callers to finish their work if necessary */
4528 if (mVMCallers > 0)
4529 {
4530 /* go to the destroying state to prevent from adding new callers */
4531 mVMDestroying = true;
4532
4533 /* lazy creation */
4534 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
4535 RTSemEventCreate (&mVMZeroCallersSem);
4536
4537 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
4538 mVMCallers));
4539
4540 alock.leave();
4541
4542 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
4543
4544 alock.enter();
4545 }
4546
4547 AssertReturn (mpVM, E_FAIL);
4548
4549 AssertMsg (mMachineState == MachineState_Running ||
4550 mMachineState == MachineState_Paused ||
4551 mMachineState == MachineState_Stuck ||
4552 mMachineState == MachineState_Saving ||
4553 mMachineState == MachineState_Starting ||
4554 mMachineState == MachineState_Restoring ||
4555 mMachineState == MachineState_Stopping,
4556 ("Invalid machine state: %d\n", mMachineState));
4557
4558 HRESULT rc = S_OK;
4559 vrc = VINF_SUCCESS;
4560
4561 /*
4562 * Power off the VM if not already done that. In case of Stopping, the VM
4563 * has powered itself off and notified Console in vmstateChangeCallback().
4564 * In case of Starting or Restoring, powerUpThread() is calling us on
4565 * failure, so the VM is already off at that point.
4566 */
4567 if (mMachineState != MachineState_Stopping &&
4568 mMachineState != MachineState_Starting &&
4569 mMachineState != MachineState_Restoring)
4570 {
4571 /*
4572 * don't go from Saving to Stopping, vmstateChangeCallback needs it
4573 * to set the state to Saved on VMSTATE_TERMINATED.
4574 */
4575 if (mMachineState != MachineState_Saving)
4576 setMachineState (MachineState_Stopping);
4577
4578 LogFlowThisFunc (("Powering off the VM...\n"));
4579
4580 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
4581 alock.leave();
4582
4583 vrc = VMR3PowerOff (mpVM);
4584 /*
4585 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
4586 * VM-(guest-)initiated power off happened in parallel a ms before
4587 * this call. So far, we let this error pop up on the user's side.
4588 */
4589
4590 alock.enter();
4591 }
4592
4593 LogFlowThisFunc (("Ready for VM destruction\n"));
4594
4595 /*
4596 * If we are called from Console::uninit(), then try to destroy the VM
4597 * even on failure (this will most likely fail too, but what to do?..)
4598 */
4599 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
4600 {
4601 /* If the machine has an USB comtroller, release all USB devices
4602 * (symmetric to the code in captureUSBDevices()) */
4603 bool fHasUSBController = false;
4604 {
4605 PPDMIBASE pBase;
4606 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4607 if (VBOX_SUCCESS (vrc))
4608 {
4609 fHasUSBController = true;
4610 detachAllUSBDevices (false /* aDone */);
4611 }
4612 }
4613
4614 /*
4615 * Now we've got to destroy the VM as well. (mpVM is not valid
4616 * beyond this point). We leave the lock before calling VMR3Destroy()
4617 * because it will result into calling destructors of drivers
4618 * associated with Console children which may in turn try to lock
4619 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
4620 * here because mVMDestroying is set which should prevent any activity.
4621 */
4622
4623 /*
4624 * Set mpVM to NULL early just in case if some old code is not using
4625 * addVMCaller()/releaseVMCaller().
4626 */
4627 PVM pVM = mpVM;
4628 mpVM = NULL;
4629
4630 LogFlowThisFunc (("Destroying the VM...\n"));
4631
4632 alock.leave();
4633
4634 vrc = VMR3Destroy (pVM);
4635
4636 /* take the lock again */
4637 alock.enter();
4638
4639 if (VBOX_SUCCESS (vrc))
4640 {
4641 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
4642 mMachineState));
4643 /*
4644 * Note: the Console-level machine state change happens on the
4645 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
4646 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
4647 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
4648 * occured yet. This is okay, because mMachineState is already
4649 * Stopping in this case, so any other attempt to call PowerDown()
4650 * will be rejected.
4651 */
4652 }
4653 else
4654 {
4655 /* bad bad bad, but what to do? */
4656 mpVM = pVM;
4657 rc = setError (E_FAIL,
4658 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
4659 }
4660
4661 /*
4662 * Complete the detaching of the USB devices.
4663 */
4664 if (fHasUSBController)
4665 detachAllUSBDevices (true /* aDone */);
4666 }
4667 else
4668 {
4669 rc = setError (E_FAIL,
4670 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
4671 }
4672
4673 /*
4674 * Finished with destruction. Note that if something impossible happened
4675 * and we've failed to destroy the VM, mVMDestroying will remain false and
4676 * mMachineState will be something like Stopping, so most Console methods
4677 * will return an error to the caller.
4678 */
4679 if (mpVM == NULL)
4680 mVMDestroying = false;
4681
4682 if (SUCCEEDED (rc))
4683 {
4684 /* uninit dynamically allocated members of mCallbackData */
4685 if (mCallbackData.mpsc.valid)
4686 {
4687 if (mCallbackData.mpsc.shape != NULL)
4688 RTMemFree (mCallbackData.mpsc.shape);
4689 }
4690 memset (&mCallbackData, 0, sizeof (mCallbackData));
4691 }
4692
4693 LogFlowThisFuncLeave();
4694 return rc;
4695}
4696
4697/**
4698 * @note Locks this object for writing.
4699 */
4700HRESULT Console::setMachineState (MachineState_T aMachineState,
4701 bool aUpdateServer /* = true */)
4702{
4703 AutoCaller autoCaller (this);
4704 AssertComRCReturnRC (autoCaller.rc());
4705
4706 AutoWriteLock alock (this);
4707
4708 HRESULT rc = S_OK;
4709
4710 if (mMachineState != aMachineState)
4711 {
4712 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4713 mMachineState = aMachineState;
4714
4715 /// @todo (dmik)
4716 // possibly, we need to redo onStateChange() using the dedicated
4717 // Event thread, like it is done in VirtualBox. This will make it
4718 // much safer (no deadlocks possible if someone tries to use the
4719 // console from the callback), however, listeners will lose the
4720 // ability to synchronously react to state changes (is it really
4721 // necessary??)
4722 LogFlowThisFunc (("Doing onStateChange()...\n"));
4723 onStateChange (aMachineState);
4724 LogFlowThisFunc (("Done onStateChange()\n"));
4725
4726 if (aUpdateServer)
4727 {
4728 /*
4729 * Server notification MUST be done from under the lock; otherwise
4730 * the machine state here and on the server might go out of sync, that
4731 * can lead to various unexpected results (like the machine state being
4732 * >= MachineState_Running on the server, while the session state is
4733 * already SessionState_Closed at the same time there).
4734 *
4735 * Cross-lock conditions should be carefully watched out: calling
4736 * UpdateState we will require Machine and SessionMachine locks
4737 * (remember that here we're holding the Console lock here, and
4738 * also all locks that have been entered by the thread before calling
4739 * this method).
4740 */
4741 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4742 rc = mControl->UpdateState (aMachineState);
4743 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4744 }
4745 }
4746
4747 return rc;
4748}
4749
4750/**
4751 * Searches for a shared folder with the given logical name
4752 * in the collection of shared folders.
4753 *
4754 * @param aName logical name of the shared folder
4755 * @param aSharedFolder where to return the found object
4756 * @param aSetError whether to set the error info if the folder is
4757 * not found
4758 * @return
4759 * S_OK when found or E_INVALIDARG when not found
4760 *
4761 * @note The caller must lock this object for writing.
4762 */
4763HRESULT Console::findSharedFolder (const BSTR aName,
4764 ComObjPtr <SharedFolder> &aSharedFolder,
4765 bool aSetError /* = false */)
4766{
4767 /* sanity check */
4768 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4769
4770 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4771 if (it != mSharedFolders.end())
4772 {
4773 aSharedFolder = it->second;
4774 return S_OK;
4775 }
4776
4777 if (aSetError)
4778 setError (E_INVALIDARG,
4779 tr ("Could not find a shared folder named '%ls'."), aName);
4780
4781 return E_INVALIDARG;
4782}
4783
4784/**
4785 * Fetches the list of global or machine shared folders from the server.
4786 *
4787 * @param aGlobal true to fetch global folders.
4788 *
4789 * @note The caller must lock this object for writing.
4790 */
4791HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4792{
4793 /* sanity check */
4794 AssertReturn (AutoCaller (this).state() == InInit ||
4795 isWriteLockOnCurrentThread(), E_FAIL);
4796
4797 /* protect mpVM (if not NULL) */
4798 AutoVMCallerQuietWeak autoVMCaller (this);
4799
4800 HRESULT rc = S_OK;
4801
4802 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4803
4804 if (aGlobal)
4805 {
4806 /// @todo grab & process global folders when they are done
4807 }
4808 else
4809 {
4810 SharedFolderDataMap oldFolders;
4811 if (online)
4812 oldFolders = mMachineSharedFolders;
4813
4814 mMachineSharedFolders.clear();
4815
4816 ComPtr <ISharedFolderCollection> coll;
4817 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
4818 AssertComRCReturnRC (rc);
4819
4820 ComPtr <ISharedFolderEnumerator> en;
4821 rc = coll->Enumerate (en.asOutParam());
4822 AssertComRCReturnRC (rc);
4823
4824 BOOL hasMore = FALSE;
4825 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
4826 {
4827 ComPtr <ISharedFolder> folder;
4828 rc = en->GetNext (folder.asOutParam());
4829 CheckComRCBreakRC (rc);
4830
4831 Bstr name;
4832 Bstr hostPath;
4833 BOOL writable;
4834
4835 rc = folder->COMGETTER(Name) (name.asOutParam());
4836 CheckComRCBreakRC (rc);
4837 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
4838 CheckComRCBreakRC (rc);
4839 rc = folder->COMGETTER(Writable) (&writable);
4840
4841 mMachineSharedFolders.insert (std::make_pair (name, SharedFolderData (hostPath, writable)));
4842
4843 /* send changes to HGCM if the VM is running */
4844 /// @todo report errors as runtime warnings through VMSetError
4845 if (online)
4846 {
4847 SharedFolderDataMap::iterator it = oldFolders.find (name);
4848 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
4849 {
4850 /* a new machine folder is added or
4851 * the existing machine folder is changed */
4852 if (mSharedFolders.find (name) != mSharedFolders.end())
4853 ; /* the console folder exists, nothing to do */
4854 else
4855 {
4856 /* remove the old machhine folder (when changed)
4857 * or the global folder if any (when new) */
4858 if (it != oldFolders.end() ||
4859 mGlobalSharedFolders.find (name) !=
4860 mGlobalSharedFolders.end())
4861 rc = removeSharedFolder (name);
4862 /* create the new machine folder */
4863 rc = createSharedFolder (name, SharedFolderData (hostPath, writable));
4864 }
4865 }
4866 /* forget the processed (or identical) folder */
4867 if (it != oldFolders.end())
4868 oldFolders.erase (it);
4869
4870 rc = S_OK;
4871 }
4872 }
4873
4874 AssertComRCReturnRC (rc);
4875
4876 /* process outdated (removed) folders */
4877 /// @todo report errors as runtime warnings through VMSetError
4878 if (online)
4879 {
4880 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
4881 it != oldFolders.end(); ++ it)
4882 {
4883 if (mSharedFolders.find (it->first) != mSharedFolders.end())
4884 ; /* the console folder exists, nothing to do */
4885 else
4886 {
4887 /* remove the outdated machine folder */
4888 rc = removeSharedFolder (it->first);
4889 /* create the global folder if there is any */
4890 SharedFolderDataMap::const_iterator git =
4891 mGlobalSharedFolders.find (it->first);
4892 if (git != mGlobalSharedFolders.end())
4893 rc = createSharedFolder (git->first, git->second);
4894 }
4895 }
4896
4897 rc = S_OK;
4898 }
4899 }
4900
4901 return rc;
4902}
4903
4904/**
4905 * Searches for a shared folder with the given name in the list of machine
4906 * shared folders and then in the list of the global shared folders.
4907 *
4908 * @param aName Name of the folder to search for.
4909 * @param aIt Where to store the pointer to the found folder.
4910 * @return @c true if the folder was found and @c false otherwise.
4911 *
4912 * @note The caller must lock this object for reading.
4913 */
4914bool Console::findOtherSharedFolder (INPTR BSTR aName,
4915 SharedFolderDataMap::const_iterator &aIt)
4916{
4917 /* sanity check */
4918 AssertReturn (isWriteLockOnCurrentThread(), false);
4919
4920 /* first, search machine folders */
4921 aIt = mMachineSharedFolders.find (aName);
4922 if (aIt != mMachineSharedFolders.end())
4923 return true;
4924
4925 /* second, search machine folders */
4926 aIt = mGlobalSharedFolders.find (aName);
4927 if (aIt != mGlobalSharedFolders.end())
4928 return true;
4929
4930 return false;
4931}
4932
4933/**
4934 * Calls the HGCM service to add a shared folder definition.
4935 *
4936 * @param aName Shared folder name.
4937 * @param aHostPath Shared folder path.
4938 *
4939 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4940 * @note Doesn't lock anything.
4941 */
4942HRESULT Console::createSharedFolder (INPTR BSTR aName, SharedFolderData aData)
4943{
4944 ComAssertRet (aName && *aName, E_FAIL);
4945 ComAssertRet (aData.mHostPath, E_FAIL);
4946
4947 /* sanity checks */
4948 AssertReturn (mpVM, E_FAIL);
4949 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4950
4951 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
4952 SHFLSTRING *pFolderName, *pMapName;
4953 size_t cbString;
4954
4955 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
4956
4957 cbString = (RTUtf16Len (aData.mHostPath) + 1) * sizeof (RTUTF16);
4958 if (cbString >= UINT16_MAX)
4959 return setError (E_INVALIDARG, tr ("The name is too long"));
4960 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4961 Assert (pFolderName);
4962 memcpy (pFolderName->String.ucs2, aData.mHostPath, cbString);
4963
4964 pFolderName->u16Size = (uint16_t)cbString;
4965 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
4966
4967 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4968 parms[0].u.pointer.addr = pFolderName;
4969 parms[0].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4970
4971 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
4972 if (cbString >= UINT16_MAX)
4973 {
4974 RTMemFree (pFolderName);
4975 return setError (E_INVALIDARG, tr ("The host path is too long"));
4976 }
4977 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
4978 Assert (pMapName);
4979 memcpy (pMapName->String.ucs2, aName, cbString);
4980
4981 pMapName->u16Size = (uint16_t)cbString;
4982 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
4983
4984 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4985 parms[1].u.pointer.addr = pMapName;
4986 parms[1].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4987
4988 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
4989 parms[2].u.uint32 = aData.mWritable;
4990
4991 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4992 SHFL_FN_ADD_MAPPING,
4993 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
4994 RTMemFree (pFolderName);
4995 RTMemFree (pMapName);
4996
4997 if (VBOX_FAILURE (vrc))
4998 return setError (E_FAIL,
4999 tr ("Could not create a shared folder '%ls' "
5000 "mapped to '%ls' (%Vrc)"),
5001 aName, aData.mHostPath.raw(), vrc);
5002
5003 return S_OK;
5004}
5005
5006/**
5007 * Calls the HGCM service to remove the shared folder definition.
5008 *
5009 * @param aName Shared folder name.
5010 *
5011 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5012 * @note Doesn't lock anything.
5013 */
5014HRESULT Console::removeSharedFolder (INPTR BSTR aName)
5015{
5016 ComAssertRet (aName && *aName, E_FAIL);
5017
5018 /* sanity checks */
5019 AssertReturn (mpVM, E_FAIL);
5020 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
5021
5022 VBOXHGCMSVCPARM parms;
5023 SHFLSTRING *pMapName;
5024 size_t cbString;
5025
5026 Log (("Removing shared folder '%ls'\n", aName));
5027
5028 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
5029 if (cbString >= UINT16_MAX)
5030 return setError (E_INVALIDARG, tr ("The name is too long"));
5031 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
5032 Assert (pMapName);
5033 memcpy (pMapName->String.ucs2, aName, cbString);
5034
5035 pMapName->u16Size = (uint16_t)cbString;
5036 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
5037
5038 parms.type = VBOX_HGCM_SVC_PARM_PTR;
5039 parms.u.pointer.addr = pMapName;
5040 parms.u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
5041
5042 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
5043 SHFL_FN_REMOVE_MAPPING,
5044 1, &parms);
5045 RTMemFree(pMapName);
5046 if (VBOX_FAILURE (vrc))
5047 return setError (E_FAIL,
5048 tr ("Could not remove the shared folder '%ls' (%Vrc)"),
5049 aName, vrc);
5050
5051 return S_OK;
5052}
5053
5054/**
5055 * VM state callback function. Called by the VMM
5056 * using its state machine states.
5057 *
5058 * Primarily used to handle VM initiated power off, suspend and state saving,
5059 * but also for doing termination completed work (VMSTATE_TERMINATE).
5060 *
5061 * In general this function is called in the context of the EMT.
5062 *
5063 * @param aVM The VM handle.
5064 * @param aState The new state.
5065 * @param aOldState The old state.
5066 * @param aUser The user argument (pointer to the Console object).
5067 *
5068 * @note Locks the Console object for writing.
5069 */
5070DECLCALLBACK(void)
5071Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
5072 void *aUser)
5073{
5074 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
5075 aOldState, aState, aVM));
5076
5077 Console *that = static_cast <Console *> (aUser);
5078 AssertReturnVoid (that);
5079
5080 AutoCaller autoCaller (that);
5081 /*
5082 * Note that we must let this method proceed even if Console::uninit() has
5083 * been already called. In such case this VMSTATE change is a result of:
5084 * 1) powerDown() called from uninit() itself, or
5085 * 2) VM-(guest-)initiated power off.
5086 */
5087 AssertReturnVoid (autoCaller.isOk() ||
5088 autoCaller.state() == InUninit);
5089
5090 switch (aState)
5091 {
5092 /*
5093 * The VM has terminated
5094 */
5095 case VMSTATE_OFF:
5096 {
5097 AutoWriteLock alock (that);
5098
5099 if (that->mVMStateChangeCallbackDisabled)
5100 break;
5101
5102 /*
5103 * Do we still think that it is running? It may happen if this is
5104 * a VM-(guest-)initiated shutdown/poweroff.
5105 */
5106 if (that->mMachineState != MachineState_Stopping &&
5107 that->mMachineState != MachineState_Saving &&
5108 that->mMachineState != MachineState_Restoring)
5109 {
5110 LogFlowFunc (("VM has powered itself off but Console still "
5111 "thinks it is running. Notifying.\n"));
5112
5113 /* prevent powerDown() from calling VMR3PowerOff() again */
5114 that->setMachineState (MachineState_Stopping);
5115
5116 /*
5117 * Setup task object and thread to carry out the operation
5118 * asynchronously (if we call powerDown() right here but there
5119 * is one or more mpVM callers (added with addVMCaller()) we'll
5120 * deadlock.
5121 */
5122 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
5123 /*
5124 * If creating a task is falied, this can currently mean one
5125 * of two: either Console::uninit() has been called just a ms
5126 * before (so a powerDown() call is already on the way), or
5127 * powerDown() itself is being already executed. Just do
5128 * nothing .
5129 */
5130 if (!task->isOk())
5131 {
5132 LogFlowFunc (("Console is already being uninitialized.\n"));
5133 break;
5134 }
5135
5136 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
5137 (void *) task.get(), 0,
5138 RTTHREADTYPE_MAIN_WORKER, 0,
5139 "VMPowerDowm");
5140
5141 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
5142 if (VBOX_FAILURE (vrc))
5143 break;
5144
5145 /* task is now owned by powerDownThread(), so release it */
5146 task.release();
5147 }
5148 break;
5149 }
5150
5151 /*
5152 * The VM has been completely destroyed.
5153 *
5154 * Note: This state change can happen at two points:
5155 * 1) At the end of VMR3Destroy() if it was not called from EMT.
5156 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
5157 * called by EMT.
5158 */
5159 case VMSTATE_TERMINATED:
5160 {
5161 AutoWriteLock alock (that);
5162
5163 if (that->mVMStateChangeCallbackDisabled)
5164 break;
5165
5166 /*
5167 * Terminate host interface networking. If aVM is NULL, we've been
5168 * manually called from powerUpThread() either before calling
5169 * VMR3Create() or after VMR3Create() failed, so no need to touch
5170 * networking.
5171 */
5172 if (aVM)
5173 that->powerDownHostInterfaces();
5174
5175 /*
5176 * From now on the machine is officially powered down or
5177 * remains in the Saved state.
5178 */
5179 switch (that->mMachineState)
5180 {
5181 default:
5182 AssertFailed();
5183 /* fall through */
5184 case MachineState_Stopping:
5185 /* successfully powered down */
5186 that->setMachineState (MachineState_PoweredOff);
5187 break;
5188 case MachineState_Saving:
5189 /*
5190 * successfully saved (note that the machine is already
5191 * in the Saved state on the server due to EndSavingState()
5192 * called from saveStateThread(), so only change the local
5193 * state)
5194 */
5195 that->setMachineStateLocally (MachineState_Saved);
5196 break;
5197 case MachineState_Starting:
5198 /*
5199 * failed to start, but be patient: set back to PoweredOff
5200 * (for similarity with the below)
5201 */
5202 that->setMachineState (MachineState_PoweredOff);
5203 break;
5204 case MachineState_Restoring:
5205 /*
5206 * failed to load the saved state file, but be patient:
5207 * set back to Saved (to preserve the saved state file)
5208 */
5209 that->setMachineState (MachineState_Saved);
5210 break;
5211 }
5212
5213 break;
5214 }
5215
5216 case VMSTATE_SUSPENDED:
5217 {
5218 if (aOldState == VMSTATE_RUNNING)
5219 {
5220 AutoWriteLock alock (that);
5221
5222 if (that->mVMStateChangeCallbackDisabled)
5223 break;
5224
5225 /* Change the machine state from Running to Paused */
5226 Assert (that->mMachineState == MachineState_Running);
5227 that->setMachineState (MachineState_Paused);
5228 }
5229
5230 break;
5231 }
5232
5233 case VMSTATE_RUNNING:
5234 {
5235 if (aOldState == VMSTATE_CREATED ||
5236 aOldState == VMSTATE_SUSPENDED)
5237 {
5238 AutoWriteLock alock (that);
5239
5240 if (that->mVMStateChangeCallbackDisabled)
5241 break;
5242
5243 /*
5244 * Change the machine state from Starting, Restoring or Paused
5245 * to Running
5246 */
5247 Assert ( ( ( that->mMachineState == MachineState_Starting
5248 || that->mMachineState == MachineState_Paused)
5249 && aOldState == VMSTATE_CREATED)
5250 || ( ( that->mMachineState == MachineState_Restoring
5251 || that->mMachineState == MachineState_Paused)
5252 && aOldState == VMSTATE_SUSPENDED));
5253
5254 that->setMachineState (MachineState_Running);
5255 }
5256
5257 break;
5258 }
5259
5260 case VMSTATE_GURU_MEDITATION:
5261 {
5262 AutoWriteLock alock (that);
5263
5264 if (that->mVMStateChangeCallbackDisabled)
5265 break;
5266
5267 /* Guru respects only running VMs */
5268 Assert ((that->mMachineState >= MachineState_Running));
5269
5270 that->setMachineState (MachineState_Stuck);
5271
5272 break;
5273 }
5274
5275 default: /* shut up gcc */
5276 break;
5277 }
5278}
5279
5280#ifdef VBOX_WITH_USB
5281
5282/**
5283 * Sends a request to VMM to attach the given host device.
5284 * After this method succeeds, the attached device will appear in the
5285 * mUSBDevices collection.
5286 *
5287 * @param aHostDevice device to attach
5288 *
5289 * @note Synchronously calls EMT.
5290 * @note Must be called from under this object's lock.
5291 */
5292HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, ULONG aMaskedIfs)
5293{
5294 AssertReturn (aHostDevice, E_FAIL);
5295 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5296
5297 /* still want a lock object because we need to leave it */
5298 AutoWriteLock alock (this);
5299
5300 HRESULT hrc;
5301
5302 /*
5303 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
5304 * method in EMT (using usbAttachCallback()).
5305 */
5306 Bstr BstrAddress;
5307 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
5308 ComAssertComRCRetRC (hrc);
5309
5310 Utf8Str Address (BstrAddress);
5311
5312 Guid Uuid;
5313 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
5314 ComAssertComRCRetRC (hrc);
5315
5316 BOOL fRemote = FALSE;
5317 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
5318 ComAssertComRCRetRC (hrc);
5319
5320 /* protect mpVM */
5321 AutoVMCaller autoVMCaller (this);
5322 CheckComRCReturnRC (autoVMCaller.rc());
5323
5324 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
5325 Address.raw(), Uuid.ptr()));
5326
5327 /* leave the lock before a VMR3* call (EMT will call us back)! */
5328 alock.leave();
5329
5330/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5331 PVMREQ pReq = NULL;
5332 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5333 (PFNRT) usbAttachCallback, 6, this, aHostDevice, Uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
5334 if (VBOX_SUCCESS (vrc))
5335 vrc = pReq->iStatus;
5336 VMR3ReqFree (pReq);
5337
5338 /* restore the lock */
5339 alock.enter();
5340
5341 /* hrc is S_OK here */
5342
5343 if (VBOX_FAILURE (vrc))
5344 {
5345 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
5346 Address.raw(), Uuid.ptr(), vrc));
5347
5348 switch (vrc)
5349 {
5350 case VERR_VUSB_NO_PORTS:
5351 hrc = setError (E_FAIL,
5352 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
5353 break;
5354 case VERR_VUSB_USBFS_PERMISSION:
5355 hrc = setError (E_FAIL,
5356 tr ("Not permitted to open the USB device, check usbfs options"));
5357 break;
5358 default:
5359 hrc = setError (E_FAIL,
5360 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
5361 break;
5362 }
5363 }
5364
5365 return hrc;
5366}
5367
5368/**
5369 * USB device attach callback used by AttachUSBDevice().
5370 * Note that AttachUSBDevice() doesn't return until this callback is executed,
5371 * so we don't use AutoCaller and don't care about reference counters of
5372 * interface pointers passed in.
5373 *
5374 * @thread EMT
5375 * @note Locks the console object for writing.
5376 */
5377//static
5378DECLCALLBACK(int)
5379Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
5380{
5381 LogFlowFuncEnter();
5382 LogFlowFunc (("that={%p}\n", that));
5383
5384 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5385
5386 void *pvRemoteBackend = NULL;
5387 if (aRemote)
5388 {
5389 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
5390 Guid guid (*aUuid);
5391
5392 pvRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
5393 if (!pvRemoteBackend)
5394 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
5395 }
5396
5397 USHORT portVersion = 1;
5398 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
5399 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
5400 Assert(portVersion == 1 || portVersion == 2);
5401
5402 int vrc = PDMR3USBCreateProxyDevice (that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
5403 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
5404 if (VBOX_SUCCESS (vrc))
5405 {
5406 /* Create a OUSBDevice and add it to the device list */
5407 ComObjPtr <OUSBDevice> device;
5408 device.createObject();
5409 HRESULT hrc = device->init (aHostDevice);
5410 AssertComRC (hrc);
5411
5412 AutoWriteLock alock (that);
5413 that->mUSBDevices.push_back (device);
5414 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
5415
5416 /* notify callbacks */
5417 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
5418 }
5419
5420 LogFlowFunc (("vrc=%Vrc\n", vrc));
5421 LogFlowFuncLeave();
5422 return vrc;
5423}
5424
5425/**
5426 * Sends a request to VMM to detach the given host device. After this method
5427 * succeeds, the detached device will disappear from the mUSBDevices
5428 * collection.
5429 *
5430 * @param aIt Iterator pointing to the device to detach.
5431 *
5432 * @note Synchronously calls EMT.
5433 * @note Must be called from under this object's lock.
5434 */
5435HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
5436{
5437 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5438
5439 /* still want a lock object because we need to leave it */
5440 AutoWriteLock alock (this);
5441
5442 /* protect mpVM */
5443 AutoVMCaller autoVMCaller (this);
5444 CheckComRCReturnRC (autoVMCaller.rc());
5445
5446 /* if the device is attached, then there must at least one USB hub. */
5447 AssertReturn (PDMR3USBHasHub (mpVM), E_FAIL);
5448
5449 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
5450 (*aIt)->id().raw()));
5451
5452 /* leave the lock before a VMR3* call (EMT will call us back)! */
5453 alock.leave();
5454
5455 PVMREQ pReq;
5456/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5457 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5458 (PFNRT) usbDetachCallback, 4,
5459 this, &aIt, (*aIt)->id().raw());
5460 if (VBOX_SUCCESS (vrc))
5461 vrc = pReq->iStatus;
5462 VMR3ReqFree (pReq);
5463
5464 ComAssertRCRet (vrc, E_FAIL);
5465
5466 return S_OK;
5467}
5468
5469/**
5470 * USB device detach callback used by DetachUSBDevice().
5471 * Note that DetachUSBDevice() doesn't return until this callback is executed,
5472 * so we don't use AutoCaller and don't care about reference counters of
5473 * interface pointers passed in.
5474 *
5475 * @thread EMT
5476 * @note Locks the console object for writing.
5477 */
5478//static
5479DECLCALLBACK(int)
5480Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
5481{
5482 LogFlowFuncEnter();
5483 LogFlowFunc (("that={%p}\n", that));
5484
5485 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5486 ComObjPtr <OUSBDevice> device = **aIt;
5487
5488 /*
5489 * If that was a remote device, release the backend pointer.
5490 * The pointer was requested in usbAttachCallback.
5491 */
5492 BOOL fRemote = FALSE;
5493
5494 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
5495 ComAssertComRC (hrc2);
5496
5497 if (fRemote)
5498 {
5499 Guid guid (*aUuid);
5500 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
5501 }
5502
5503 int vrc = PDMR3USBDetachDevice (that->mpVM, aUuid);
5504
5505 if (VBOX_SUCCESS (vrc))
5506 {
5507 AutoWriteLock alock (that);
5508
5509 /* Remove the device from the collection */
5510 that->mUSBDevices.erase (*aIt);
5511 LogFlowFunc (("Detached device {%Vuuid}\n", device->id().raw()));
5512
5513 /* notify callbacks */
5514 that->onUSBDeviceStateChange (device, false /* aAttached */, NULL);
5515 }
5516
5517 LogFlowFunc (("vrc=%Vrc\n", vrc));
5518 LogFlowFuncLeave();
5519 return vrc;
5520}
5521
5522#endif /* VBOX_WITH_USB */
5523
5524/**
5525 * Call the initialisation script for a dynamic TAP interface.
5526 *
5527 * The initialisation script should create a TAP interface, set it up and write its name to
5528 * standard output followed by a carriage return. Anything further written to standard
5529 * output will be ignored. If it returns a non-zero exit code, or does not write an
5530 * intelligable interface name to standard output, it will be treated as having failed.
5531 * For now, this method only works on Linux.
5532 *
5533 * @returns COM status code
5534 * @param tapDevice string to store the name of the tap device created to
5535 * @param tapSetupApplication the name of the setup script
5536 */
5537HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5538 Bstr &tapSetupApplication)
5539{
5540 LogFlowThisFunc(("\n"));
5541#ifdef RT_OS_LINUX
5542 /* Command line to start the script with. */
5543 char szCommand[4096];
5544 /* Result code */
5545 int rc;
5546
5547 /* Get the script name. */
5548 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5549 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5550 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5551 /*
5552 * Create the process and read its output.
5553 */
5554 Log2(("About to start the TAP setup script with the following command line: %s\n",
5555 szCommand));
5556 FILE *pfScriptHandle = popen(szCommand, "r");
5557 if (pfScriptHandle == 0)
5558 {
5559 int iErr = errno;
5560 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5561 szCommand, strerror(iErr)));
5562 LogFlowThisFunc(("rc=E_FAIL\n"));
5563 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5564 szCommand, strerror(iErr));
5565 }
5566 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5567 if (!isStatic)
5568 {
5569 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5570 interested in the first few (normally 5 or 6) bytes. */
5571 char acBuffer[64];
5572 /* The length of the string returned by the application. We only accept strings of 63
5573 characters or less. */
5574 size_t cBufSize;
5575
5576 /* Read the name of the device from the application. */
5577 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5578 cBufSize = strlen(acBuffer);
5579 /* The script must return the name of the interface followed by a carriage return as the
5580 first line of its output. We need a null-terminated string. */
5581 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5582 {
5583 pclose(pfScriptHandle);
5584 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5585 LogFlowThisFunc(("rc=E_FAIL\n"));
5586 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5587 }
5588 /* Overwrite the terminating newline character. */
5589 acBuffer[cBufSize - 1] = 0;
5590 tapDevice = acBuffer;
5591 }
5592 rc = pclose(pfScriptHandle);
5593 if (!WIFEXITED(rc))
5594 {
5595 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5596 LogFlowThisFunc(("rc=E_FAIL\n"));
5597 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5598 }
5599 if (WEXITSTATUS(rc) != 0)
5600 {
5601 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5602 LogFlowThisFunc(("rc=E_FAIL\n"));
5603 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5604 }
5605 LogFlowThisFunc(("rc=S_OK\n"));
5606 return S_OK;
5607#else /* RT_OS_LINUX not defined */
5608 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5609 return E_NOTIMPL; /* not yet supported */
5610#endif
5611}
5612
5613/**
5614 * Helper function to handle host interface device creation and attachment.
5615 *
5616 * @param networkAdapter the network adapter which attachment should be reset
5617 * @return COM status code
5618 *
5619 * @note The caller must lock this object for writing.
5620 */
5621HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5622{
5623#if !defined(RT_OS_LINUX)
5624 /*
5625 * Nothing to do here.
5626 *
5627 * Note, the reason for this method in the first place a memory / fork
5628 * bug on linux. All this code belongs in DrvTAP and similar places.
5629 */
5630 NOREF(networkAdapter);
5631 return S_OK;
5632
5633#else /* RT_OS_LINUX */
5634 LogFlowThisFunc(("\n"));
5635 /* sanity check */
5636 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5637
5638# ifdef VBOX_STRICT
5639 /* paranoia */
5640 NetworkAttachmentType_T attachment;
5641 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5642 Assert(attachment == NetworkAttachmentType_HostInterface);
5643# endif /* VBOX_STRICT */
5644
5645 HRESULT rc = S_OK;
5646
5647 ULONG slot = 0;
5648 rc = networkAdapter->COMGETTER(Slot)(&slot);
5649 AssertComRC(rc);
5650
5651 /*
5652 * Try get the FD.
5653 */
5654 LONG ltapFD;
5655 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5656 if (SUCCEEDED(rc))
5657 maTapFD[slot] = (RTFILE)ltapFD;
5658 else
5659 maTapFD[slot] = NIL_RTFILE;
5660
5661 /*
5662 * Are we supposed to use an existing TAP interface?
5663 */
5664 if (maTapFD[slot] != NIL_RTFILE)
5665 {
5666 /* nothing to do */
5667 Assert(ltapFD >= 0);
5668 Assert((LONG)maTapFD[slot] == ltapFD);
5669 rc = S_OK;
5670 }
5671 else
5672 {
5673 /*
5674 * Allocate a host interface device
5675 */
5676 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5677 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5678 if (VBOX_SUCCESS(rcVBox))
5679 {
5680 /*
5681 * Set/obtain the tap interface.
5682 */
5683 bool isStatic = false;
5684 struct ifreq IfReq;
5685 memset(&IfReq, 0, sizeof(IfReq));
5686 /* The name of the TAP interface we are using and the TAP setup script resp. */
5687 Bstr tapDeviceName, tapSetupApplication;
5688 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5689 if (FAILED(rc))
5690 {
5691 tapDeviceName.setNull(); /* Is this necessary? */
5692 }
5693 else if (!tapDeviceName.isEmpty())
5694 {
5695 isStatic = true;
5696 /* If we are using a static TAP device then try to open it. */
5697 Utf8Str str(tapDeviceName);
5698 if (str.length() <= sizeof(IfReq.ifr_name))
5699 strcpy(IfReq.ifr_name, str.raw());
5700 else
5701 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5702 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5703 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5704 if (rcVBox != 0)
5705 {
5706 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5707 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5708 tapDeviceName.raw());
5709 }
5710 }
5711 if (SUCCEEDED(rc))
5712 {
5713 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5714 if (tapSetupApplication.isEmpty())
5715 {
5716 if (tapDeviceName.isEmpty())
5717 {
5718 LogRel(("No setup application was supplied for the TAP interface.\n"));
5719 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5720 }
5721 }
5722 else
5723 {
5724 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5725 tapSetupApplication);
5726 }
5727 }
5728 if (SUCCEEDED(rc))
5729 {
5730 if (!isStatic)
5731 {
5732 Utf8Str str(tapDeviceName);
5733 if (str.length() <= sizeof(IfReq.ifr_name))
5734 strcpy(IfReq.ifr_name, str.raw());
5735 else
5736 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5737 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5738 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5739 if (rcVBox != 0)
5740 {
5741 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5742 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5743 }
5744 }
5745 if (SUCCEEDED(rc))
5746 {
5747 /*
5748 * Make it pollable.
5749 */
5750 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5751 {
5752 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5753
5754 /*
5755 * Here is the right place to communicate the TAP file descriptor and
5756 * the host interface name to the server if/when it becomes really
5757 * necessary.
5758 */
5759 maTAPDeviceName[slot] = tapDeviceName;
5760 rcVBox = VINF_SUCCESS;
5761 }
5762 else
5763 {
5764 int iErr = errno;
5765
5766 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5767 rcVBox = VERR_HOSTIF_BLOCKING;
5768 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5769 strerror(errno));
5770 }
5771 }
5772 }
5773 }
5774 else
5775 {
5776 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5777 switch (rcVBox)
5778 {
5779 case VERR_ACCESS_DENIED:
5780 /* will be handled by our caller */
5781 rc = rcVBox;
5782 break;
5783 default:
5784 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
5785 break;
5786 }
5787 }
5788 /* in case of failure, cleanup. */
5789 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5790 {
5791 LogRel(("General failure attaching to host interface\n"));
5792 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5793 }
5794 }
5795 LogFlowThisFunc(("rc=%d\n", rc));
5796 return rc;
5797#endif /* RT_OS_LINUX */
5798}
5799
5800/**
5801 * Helper function to handle detachment from a host interface
5802 *
5803 * @param networkAdapter the network adapter which attachment should be reset
5804 * @return COM status code
5805 *
5806 * @note The caller must lock this object for writing.
5807 */
5808HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5809{
5810#if !defined(RT_OS_LINUX)
5811
5812 /*
5813 * Nothing to do here.
5814 */
5815 NOREF(networkAdapter);
5816 return S_OK;
5817
5818#else /* RT_OS_LINUX */
5819
5820 /* sanity check */
5821 LogFlowThisFunc(("\n"));
5822 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5823
5824 HRESULT rc = S_OK;
5825# ifdef VBOX_STRICT
5826 /* paranoia */
5827 NetworkAttachmentType_T attachment;
5828 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5829 Assert(attachment == NetworkAttachmentType_HostInterface);
5830# endif /* VBOX_STRICT */
5831
5832 ULONG slot = 0;
5833 rc = networkAdapter->COMGETTER(Slot)(&slot);
5834 AssertComRC(rc);
5835
5836 /* is there an open TAP device? */
5837 if (maTapFD[slot] != NIL_RTFILE)
5838 {
5839 /*
5840 * Close the file handle.
5841 */
5842 Bstr tapDeviceName, tapTerminateApplication;
5843 bool isStatic = true;
5844 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5845 if (FAILED(rc) || tapDeviceName.isEmpty())
5846 {
5847 /* If the name is empty, this is a dynamic TAP device, so close it now,
5848 so that the termination script can remove the interface. Otherwise we still
5849 need the FD to pass to the termination script. */
5850 isStatic = false;
5851 int rcVBox = RTFileClose(maTapFD[slot]);
5852 AssertRC(rcVBox);
5853 maTapFD[slot] = NIL_RTFILE;
5854 }
5855 /*
5856 * Execute the termination command.
5857 */
5858 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5859 if (tapTerminateApplication)
5860 {
5861 /* Get the program name. */
5862 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5863
5864 /* Build the command line. */
5865 char szCommand[4096];
5866 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
5867 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
5868 /** @todo check for overflow or use RTStrAPrintf! */
5869
5870 /*
5871 * Create the process and wait for it to complete.
5872 */
5873 Log(("Calling the termination command: %s\n", szCommand));
5874 int rcCommand = system(szCommand);
5875 if (rcCommand == -1)
5876 {
5877 LogRel(("Failed to execute the clean up script for the TAP interface"));
5878 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
5879 }
5880 if (!WIFEXITED(rc))
5881 {
5882 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
5883 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
5884 }
5885 if (WEXITSTATUS(rc) != 0)
5886 {
5887 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
5888 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
5889 }
5890 }
5891
5892 if (isStatic)
5893 {
5894 /* If we are using a static TAP device, we close it now, after having called the
5895 termination script. */
5896 int rcVBox = RTFileClose(maTapFD[slot]);
5897 AssertRC(rcVBox);
5898 }
5899 /* the TAP device name and handle are no longer valid */
5900 maTapFD[slot] = NIL_RTFILE;
5901 maTAPDeviceName[slot] = "";
5902 }
5903 LogFlowThisFunc(("returning %d\n", rc));
5904 return rc;
5905#endif /* RT_OS_LINUX */
5906
5907}
5908
5909
5910/**
5911 * Called at power down to terminate host interface networking.
5912 *
5913 * @note The caller must lock this object for writing.
5914 */
5915HRESULT Console::powerDownHostInterfaces()
5916{
5917 LogFlowThisFunc (("\n"));
5918
5919 /* sanity check */
5920 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5921
5922 /*
5923 * host interface termination handling
5924 */
5925 HRESULT rc;
5926 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
5927 {
5928 ComPtr<INetworkAdapter> networkAdapter;
5929 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
5930 CheckComRCBreakRC (rc);
5931
5932 BOOL enabled = FALSE;
5933 networkAdapter->COMGETTER(Enabled) (&enabled);
5934 if (!enabled)
5935 continue;
5936
5937 NetworkAttachmentType_T attachment;
5938 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5939 if (attachment == NetworkAttachmentType_HostInterface)
5940 {
5941 HRESULT rc2 = detachFromHostInterface(networkAdapter);
5942 if (FAILED(rc2) && SUCCEEDED(rc))
5943 rc = rc2;
5944 }
5945 }
5946
5947 return rc;
5948}
5949
5950
5951/**
5952 * Process callback handler for VMR3Load and VMR3Save.
5953 *
5954 * @param pVM The VM handle.
5955 * @param uPercent Completetion precentage (0-100).
5956 * @param pvUser Pointer to the VMProgressTask structure.
5957 * @return VINF_SUCCESS.
5958 */
5959/*static*/ DECLCALLBACK (int)
5960Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
5961{
5962 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5963 AssertReturn (task, VERR_INVALID_PARAMETER);
5964
5965 /* update the progress object */
5966 if (task->mProgress)
5967 task->mProgress->notifyProgress (uPercent);
5968
5969 return VINF_SUCCESS;
5970}
5971
5972/**
5973 * VM error callback function. Called by the various VM components.
5974 *
5975 * @param pVM VM handle. Can be NULL if an error occurred before
5976 * successfully creating a VM.
5977 * @param pvUser Pointer to the VMProgressTask structure.
5978 * @param rc VBox status code.
5979 * @param pszFormat Printf-like error message.
5980 * @param args Various number of argumens for the error message.
5981 *
5982 * @thread EMT, VMPowerUp...
5983 *
5984 * @note The VMProgressTask structure modified by this callback is not thread
5985 * safe.
5986 */
5987/* static */ DECLCALLBACK (void)
5988Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
5989 const char *pszFormat, va_list args)
5990{
5991 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5992 AssertReturnVoid (task);
5993
5994 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
5995 va_list va2;
5996 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
5997 Utf8Str errorMsg = Utf8StrFmt (tr ("%N.\n"
5998 "VBox status code: %d (%Vrc)"),
5999 pszFormat, &va2, rc, rc);
6000 va_end(va2);
6001
6002 /* For now, this may be called only once. Ignore subsequent calls. */
6003 if (!task->mErrorMsg.isNull())
6004 {
6005#if !defined(DEBUG_bird)
6006 AssertMsgFailed (("Cannot set error to '%s': it is already set to '%s'",
6007 errorMsg.raw(), task->mErrorMsg.raw()));
6008#endif
6009 return;
6010 }
6011
6012 task->mErrorMsg = errorMsg;
6013}
6014
6015/**
6016 * VM runtime error callback function.
6017 * See VMSetRuntimeError for the detailed description of parameters.
6018 *
6019 * @param pVM The VM handle.
6020 * @param pvUser The user argument.
6021 * @param fFatal Whether it is a fatal error or not.
6022 * @param pszErrorID Error ID string.
6023 * @param pszFormat Error message format string.
6024 * @param args Error message arguments.
6025 * @thread EMT.
6026 */
6027/* static */ DECLCALLBACK(void)
6028Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
6029 const char *pszErrorID,
6030 const char *pszFormat, va_list args)
6031{
6032 LogFlowFuncEnter();
6033
6034 Console *that = static_cast <Console *> (pvUser);
6035 AssertReturnVoid (that);
6036
6037 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
6038
6039 LogRel (("Console: VM runtime error: fatal=%RTbool, "
6040 "errorID=%s message=\"%s\"\n",
6041 fFatal, pszErrorID, message.raw()));
6042
6043 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
6044
6045 LogFlowFuncLeave();
6046}
6047
6048/**
6049 * Captures USB devices that match filters of the VM.
6050 * Called at VM startup.
6051 *
6052 * @param pVM The VM handle.
6053 *
6054 * @note The caller must lock this object for writing.
6055 */
6056HRESULT Console::captureUSBDevices (PVM pVM)
6057{
6058 LogFlowThisFunc (("\n"));
6059
6060 /* sanity check */
6061 ComAssertRet (isWriteLockOnCurrentThread(), E_FAIL);
6062
6063 /* If the machine has an USB controller, ask the USB proxy service to
6064 * capture devices */
6065 PPDMIBASE pBase;
6066 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
6067 if (VBOX_SUCCESS (vrc))
6068 {
6069 /* leave the lock before calling Host in VBoxSVC since Host may call
6070 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6071 * produce an inter-process dead-lock otherwise. */
6072 AutoWriteLock alock (this);
6073 alock.leave();
6074
6075 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6076 ComAssertComRCRetRC (hrc);
6077 }
6078 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6079 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6080 vrc = VINF_SUCCESS;
6081 else
6082 AssertRC (vrc);
6083
6084 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
6085}
6086
6087
6088/**
6089 * Detach all USB device which are attached to the VM for the
6090 * purpose of clean up and such like.
6091 *
6092 * @note The caller must lock this object for writing.
6093 */
6094void Console::detachAllUSBDevices (bool aDone)
6095{
6096 LogFlowThisFunc (("aDone=%RTbool\n", aDone));
6097
6098 /* sanity check */
6099 AssertReturnVoid (isWriteLockOnCurrentThread());
6100
6101 mUSBDevices.clear();
6102
6103 /* leave the lock before calling Host in VBoxSVC since Host may call
6104 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6105 * produce an inter-process dead-lock otherwise. */
6106 AutoWriteLock alock (this);
6107 alock.leave();
6108
6109 mControl->DetachAllUSBDevices (aDone);
6110}
6111
6112/**
6113 * @note Locks this object for writing.
6114 */
6115void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6116{
6117 LogFlowThisFuncEnter();
6118 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6119
6120 AutoCaller autoCaller (this);
6121 if (!autoCaller.isOk())
6122 {
6123 /* Console has been already uninitialized, deny request */
6124 AssertMsgFailed (("Temporary assertion to prove that it happens, "
6125 "please report to dmik\n"));
6126 LogFlowThisFunc (("Console is already uninitialized\n"));
6127 LogFlowThisFuncLeave();
6128 return;
6129 }
6130
6131 AutoWriteLock alock (this);
6132
6133 /*
6134 * Mark all existing remote USB devices as dirty.
6135 */
6136 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6137 while (it != mRemoteUSBDevices.end())
6138 {
6139 (*it)->dirty (true);
6140 ++ it;
6141 }
6142
6143 /*
6144 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6145 */
6146 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6147 VRDPUSBDEVICEDESC *e = pDevList;
6148
6149 /* The cbDevList condition must be checked first, because the function can
6150 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6151 */
6152 while (cbDevList >= 2 && e->oNext)
6153 {
6154 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6155 e->idVendor, e->idProduct,
6156 e->oProduct? (char *)e + e->oProduct: ""));
6157
6158 bool fNewDevice = true;
6159
6160 it = mRemoteUSBDevices.begin();
6161 while (it != mRemoteUSBDevices.end())
6162 {
6163 if ((*it)->devId () == e->id
6164 && (*it)->clientId () == u32ClientId)
6165 {
6166 /* The device is already in the list. */
6167 (*it)->dirty (false);
6168 fNewDevice = false;
6169 break;
6170 }
6171
6172 ++ it;
6173 }
6174
6175 if (fNewDevice)
6176 {
6177 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6178 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6179 ));
6180
6181 /* Create the device object and add the new device to list. */
6182 ComObjPtr <RemoteUSBDevice> device;
6183 device.createObject();
6184 device->init (u32ClientId, e);
6185
6186 mRemoteUSBDevices.push_back (device);
6187
6188 /* Check if the device is ok for current USB filters. */
6189 BOOL fMatched = FALSE;
6190 ULONG fMaskedIfs = 0;
6191
6192 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
6193
6194 AssertComRC (hrc);
6195
6196 LogFlowThisFunc (("USB filters return %d %#x\n", fMatched, fMaskedIfs));
6197
6198 if (fMatched)
6199 {
6200 hrc = onUSBDeviceAttach (device, NULL, fMaskedIfs);
6201
6202 /// @todo (r=dmik) warning reporting subsystem
6203
6204 if (hrc == S_OK)
6205 {
6206 LogFlowThisFunc (("Device attached\n"));
6207 device->captured (true);
6208 }
6209 }
6210 }
6211
6212 if (cbDevList < e->oNext)
6213 {
6214 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6215 cbDevList, e->oNext));
6216 break;
6217 }
6218
6219 cbDevList -= e->oNext;
6220
6221 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6222 }
6223
6224 /*
6225 * Remove dirty devices, that is those which are not reported by the server anymore.
6226 */
6227 for (;;)
6228 {
6229 ComObjPtr <RemoteUSBDevice> device;
6230
6231 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6232 while (it != mRemoteUSBDevices.end())
6233 {
6234 if ((*it)->dirty ())
6235 {
6236 device = *it;
6237 break;
6238 }
6239
6240 ++ it;
6241 }
6242
6243 if (!device)
6244 {
6245 break;
6246 }
6247
6248 USHORT vendorId = 0;
6249 device->COMGETTER(VendorId) (&vendorId);
6250
6251 USHORT productId = 0;
6252 device->COMGETTER(ProductId) (&productId);
6253
6254 Bstr product;
6255 device->COMGETTER(Product) (product.asOutParam());
6256
6257 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6258 vendorId, productId, product.raw ()
6259 ));
6260
6261 /* Detach the device from VM. */
6262 if (device->captured ())
6263 {
6264 Guid uuid;
6265 device->COMGETTER (Id) (uuid.asOutParam());
6266 onUSBDeviceDetach (uuid, NULL);
6267 }
6268
6269 /* And remove it from the list. */
6270 mRemoteUSBDevices.erase (it);
6271 }
6272
6273 LogFlowThisFuncLeave();
6274}
6275
6276
6277
6278/**
6279 * Thread function which starts the VM (also from saved state) and
6280 * track progress.
6281 *
6282 * @param Thread The thread id.
6283 * @param pvUser Pointer to a VMPowerUpTask structure.
6284 * @return VINF_SUCCESS (ignored).
6285 *
6286 * @note Locks the Console object for writing.
6287 */
6288/*static*/
6289DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6290{
6291 LogFlowFuncEnter();
6292
6293 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6294 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6295
6296 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6297 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6298
6299#if defined(RT_OS_WINDOWS)
6300 {
6301 /* initialize COM */
6302 HRESULT hrc = CoInitializeEx (NULL,
6303 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6304 COINIT_SPEED_OVER_MEMORY);
6305 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6306 }
6307#endif
6308
6309 HRESULT hrc = S_OK;
6310 int vrc = VINF_SUCCESS;
6311
6312 /* Set up a build identifier so that it can be seen from core dumps what
6313 * exact build was used to produce the core. */
6314 static char saBuildID[40];
6315 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
6316 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBoxSVNRev (), "BU", "IL", "DI", "D");
6317
6318 ComObjPtr <Console> console = task->mConsole;
6319
6320 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6321
6322 AutoWriteLock alock (console);
6323
6324 /* sanity */
6325 Assert (console->mpVM == NULL);
6326
6327 do
6328 {
6329#ifdef VBOX_WITH_VRDP
6330 /* Create the VRDP server. In case of headless operation, this will
6331 * also create the framebuffer, required at VM creation.
6332 */
6333 ConsoleVRDPServer *server = console->consoleVRDPServer();
6334 Assert (server);
6335 /// @todo (dmik)
6336 // does VRDP server call Console from the other thread?
6337 // Not sure, so leave the lock just in case
6338 alock.leave();
6339 vrc = server->Launch();
6340 alock.enter();
6341 if (VBOX_FAILURE (vrc))
6342 {
6343 Utf8Str errMsg;
6344 switch (vrc)
6345 {
6346 case VERR_NET_ADDRESS_IN_USE:
6347 {
6348 ULONG port = 0;
6349 console->mVRDPServer->COMGETTER(Port) (&port);
6350 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6351 port);
6352 break;
6353 }
6354 case VERR_FILE_NOT_FOUND:
6355 {
6356 errMsg = Utf8StrFmt (tr ("Could not load the VRDP library"));
6357 break;
6358 }
6359 default:
6360 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6361 vrc);
6362 }
6363 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6364 vrc, errMsg.raw()));
6365 hrc = setError (E_FAIL, errMsg);
6366 break;
6367 }
6368#endif /* VBOX_WITH_VRDP */
6369
6370 /*
6371 * Create the VM
6372 */
6373 PVM pVM;
6374 /*
6375 * leave the lock since EMT will call Console. It's safe because
6376 * mMachineState is either Starting or Restoring state here.
6377 */
6378 alock.leave();
6379
6380 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6381 task->mConfigConstructor, static_cast <Console *> (console),
6382 &pVM);
6383
6384 alock.enter();
6385
6386#ifdef VBOX_WITH_VRDP
6387 /* Enable client connections to the server. */
6388 console->consoleVRDPServer()->EnableConnections ();
6389#endif /* VBOX_WITH_VRDP */
6390
6391 if (VBOX_SUCCESS (vrc))
6392 {
6393 do
6394 {
6395 /*
6396 * Register our load/save state file handlers
6397 */
6398 vrc = SSMR3RegisterExternal (pVM,
6399 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6400 0 /* cbGuess */,
6401 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6402 static_cast <Console *> (console));
6403 AssertRC (vrc);
6404 if (VBOX_FAILURE (vrc))
6405 break;
6406
6407 /*
6408 * Synchronize debugger settings
6409 */
6410 MachineDebugger *machineDebugger = console->getMachineDebugger();
6411 if (machineDebugger)
6412 {
6413 machineDebugger->flushQueuedSettings();
6414 }
6415
6416 /*
6417 * Shared Folders
6418 */
6419 if (console->getVMMDev()->isShFlActive())
6420 {
6421 /// @todo (dmik)
6422 // does the code below call Console from the other thread?
6423 // Not sure, so leave the lock just in case
6424 alock.leave();
6425
6426 for (SharedFolderDataMap::const_iterator
6427 it = task->mSharedFolders.begin();
6428 it != task->mSharedFolders.end();
6429 ++ it)
6430 {
6431 hrc = console->createSharedFolder ((*it).first, (*it).second);
6432 CheckComRCBreakRC (hrc);
6433 }
6434
6435 /* enter the lock again */
6436 alock.enter();
6437
6438 CheckComRCBreakRC (hrc);
6439 }
6440
6441 /*
6442 * Capture USB devices.
6443 */
6444 hrc = console->captureUSBDevices (pVM);
6445 CheckComRCBreakRC (hrc);
6446
6447 /* leave the lock before a lengthy operation */
6448 alock.leave();
6449
6450 /* Load saved state? */
6451 if (!!task->mSavedStateFile)
6452 {
6453 LogFlowFunc (("Restoring saved state from '%s'...\n",
6454 task->mSavedStateFile.raw()));
6455
6456 vrc = VMR3Load (pVM, task->mSavedStateFile,
6457 Console::stateProgressCallback,
6458 static_cast <VMProgressTask *> (task.get()));
6459
6460 if (VBOX_SUCCESS (vrc))
6461 {
6462 if (task->mStartPaused)
6463 /* done */
6464 console->setMachineState (MachineState_Paused);
6465 else
6466 {
6467 /* Start/Resume the VM execution */
6468 vrc = VMR3Resume (pVM);
6469 AssertRC (vrc);
6470 }
6471 }
6472
6473 /* Power off in case we failed loading or resuming the VM */
6474 if (VBOX_FAILURE (vrc))
6475 {
6476 int vrc2 = VMR3PowerOff (pVM);
6477 AssertRC (vrc2);
6478 }
6479 }
6480 else if (task->mStartPaused)
6481 /* done */
6482 console->setMachineState (MachineState_Paused);
6483 else
6484 {
6485 /* Power on the VM (i.e. start executing) */
6486 vrc = VMR3PowerOn(pVM);
6487 AssertRC (vrc);
6488 }
6489
6490 /* enter the lock again */
6491 alock.enter();
6492 }
6493 while (0);
6494
6495 /* On failure, destroy the VM */
6496 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6497 {
6498 /* preserve existing error info */
6499 ErrorInfoKeeper eik;
6500
6501 /* powerDown() will call VMR3Destroy() and do all necessary
6502 * cleanup (VRDP, USB devices) */
6503 HRESULT hrc2 = console->powerDown();
6504 AssertComRC (hrc2);
6505 }
6506 }
6507 else
6508 {
6509 /*
6510 * If VMR3Create() failed it has released the VM memory.
6511 */
6512 console->mpVM = NULL;
6513 }
6514
6515 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6516 {
6517 /* If VMR3Create() or one of the other calls in this function fail,
6518 * an appropriate error message has been set in task->mErrorMsg.
6519 * However since that happens via a callback, the hrc status code in
6520 * this function is not updated.
6521 */
6522 if (task->mErrorMsg.isNull())
6523 {
6524 /* If the error message is not set but we've got a failure,
6525 * convert the VBox status code into a meaningfulerror message.
6526 * This becomes unused once all the sources of errors set the
6527 * appropriate error message themselves.
6528 */
6529 AssertMsgFailed (("Missing error message during powerup for "
6530 "status code %Vrc\n", vrc));
6531 task->mErrorMsg = Utf8StrFmt (
6532 tr ("Failed to start VM execution (%Vrc)"), vrc);
6533 }
6534
6535 /* Set the error message as the COM error.
6536 * Progress::notifyComplete() will pick it up later. */
6537 hrc = setError (E_FAIL, task->mErrorMsg);
6538 break;
6539 }
6540 }
6541 while (0);
6542
6543 if (console->mMachineState == MachineState_Starting ||
6544 console->mMachineState == MachineState_Restoring)
6545 {
6546 /* We are still in the Starting/Restoring state. This means one of:
6547 *
6548 * 1) we failed before VMR3Create() was called;
6549 * 2) VMR3Create() failed.
6550 *
6551 * In both cases, there is no need to call powerDown(), but we still
6552 * need to go back to the PoweredOff/Saved state. Reuse
6553 * vmstateChangeCallback() for that purpose.
6554 */
6555
6556 /* preserve existing error info */
6557 ErrorInfoKeeper eik;
6558
6559 Assert (console->mpVM == NULL);
6560 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6561 console);
6562 }
6563
6564 /*
6565 * Evaluate the final result. Note that the appropriate mMachineState value
6566 * is already set by vmstateChangeCallback() in all cases.
6567 */
6568
6569 /* leave the lock, don't need it any more */
6570 alock.leave();
6571
6572 if (SUCCEEDED (hrc))
6573 {
6574 /* Notify the progress object of the success */
6575 task->mProgress->notifyComplete (S_OK);
6576 }
6577 else
6578 {
6579 /* The progress object will fetch the current error info */
6580 task->mProgress->notifyComplete (hrc);
6581
6582 LogRel (("Power up failed (vrc=%Vrc, hrc=%Rhrc (%#08X))\n", vrc, hrc, hrc));
6583 }
6584
6585#if defined(RT_OS_WINDOWS)
6586 /* uninitialize COM */
6587 CoUninitialize();
6588#endif
6589
6590 LogFlowFuncLeave();
6591
6592 return VINF_SUCCESS;
6593}
6594
6595
6596/**
6597 * Reconfigures a VDI.
6598 *
6599 * @param pVM The VM handle.
6600 * @param hda The harddisk attachment.
6601 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6602 * @return VBox status code.
6603 */
6604static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6605{
6606 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6607
6608 int rc;
6609 HRESULT hrc;
6610 char *psz = NULL;
6611 BSTR str = NULL;
6612 *phrc = S_OK;
6613#define STR_CONV() do { rc = RTUtf16ToUtf8(str, &psz); RC_CHECK(); } while (0)
6614#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6615#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6616#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6617
6618 /*
6619 * Figure out which IDE device this is.
6620 */
6621 ComPtr<IHardDisk> hardDisk;
6622 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6623 StorageBus_T enmBus;
6624 hrc = hda->COMGETTER(Bus)(&enmBus); H();
6625 LONG lDev;
6626 hrc = hda->COMGETTER(Device)(&lDev); H();
6627 LONG lChannel;
6628 hrc = hda->COMGETTER(Channel)(&lChannel); H();
6629
6630 int iLUN;
6631 switch (enmBus)
6632 {
6633 case StorageBus_IDE:
6634 {
6635 if (lChannel >= 2)
6636 {
6637 AssertMsgFailed(("invalid controller channel number: %d\n", lChannel));
6638 return VERR_GENERAL_FAILURE;
6639 }
6640
6641 if (lDev >= 2)
6642 {
6643 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6644 return VERR_GENERAL_FAILURE;
6645 }
6646 iLUN = 2*lChannel + lDev;
6647 }
6648 break;
6649 case StorageBus_SATA:
6650 iLUN = lChannel;
6651 break;
6652 default:
6653 AssertMsgFailed(("invalid disk controller type: %d\n", enmBus));
6654 return VERR_GENERAL_FAILURE;
6655 }
6656
6657 /*
6658 * Is there an existing LUN? If not create it.
6659 * We ASSUME that this will NEVER collide with the DVD.
6660 */
6661 PCFGMNODE pCfg;
6662 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", iLUN);
6663 if (!pLunL1)
6664 {
6665 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6666 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6667
6668 PCFGMNODE pLunL0;
6669 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", iLUN); RC_CHECK();
6670 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6671 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6672 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6673 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6674
6675 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6676 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6677 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6678 }
6679 else
6680 {
6681#ifdef VBOX_STRICT
6682 char *pszDriver;
6683 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6684 Assert(!strcmp(pszDriver, "VBoxHDD"));
6685 MMR3HeapFree(pszDriver);
6686#endif
6687
6688 /*
6689 * Check if things has changed.
6690 */
6691 pCfg = CFGMR3GetChild(pLunL1, "Config");
6692 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6693
6694 /* the image */
6695 /// @todo (dmik) we temporarily use the location property to
6696 // determine the image file name. This is subject to change
6697 // when iSCSI disks are here (we should either query a
6698 // storage-specific interface from IHardDisk, or "standardize"
6699 // the location property)
6700 hrc = hardDisk->COMGETTER(Location)(&str); H();
6701 STR_CONV();
6702 char *pszPath;
6703 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6704 if (!strcmp(psz, pszPath))
6705 {
6706 /* parent images. */
6707 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6708 for (PCFGMNODE pParent = pCfg;;)
6709 {
6710 MMR3HeapFree(pszPath);
6711 pszPath = NULL;
6712 STR_FREE();
6713
6714 /* get parent */
6715 ComPtr<IHardDisk> curHardDisk;
6716 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6717 PCFGMNODE pCur;
6718 pCur = CFGMR3GetChild(pParent, "Parent");
6719 if (!pCur && !curHardDisk)
6720 {
6721 /* no change */
6722 LogFlowFunc (("No change!\n"));
6723 return VINF_SUCCESS;
6724 }
6725 if (!pCur || !curHardDisk)
6726 break;
6727
6728 /* compare paths. */
6729 /// @todo (dmik) we temporarily use the location property to
6730 // determine the image file name. This is subject to change
6731 // when iSCSI disks are here (we should either query a
6732 // storage-specific interface from IHardDisk, or "standardize"
6733 // the location property)
6734 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6735 STR_CONV();
6736 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6737 if (strcmp(psz, pszPath))
6738 break;
6739
6740 /* next */
6741 pParent = pCur;
6742 parentHardDisk = curHardDisk;
6743 }
6744
6745 }
6746 else
6747 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", iLUN, pszPath));
6748
6749 MMR3HeapFree(pszPath);
6750 STR_FREE();
6751
6752 /*
6753 * Detach the driver and replace the config node.
6754 */
6755 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, iLUN); RC_CHECK();
6756 CFGMR3RemoveNode(pCfg);
6757 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6758 }
6759
6760 /*
6761 * Create the driver configuration.
6762 */
6763 /// @todo (dmik) we temporarily use the location property to
6764 // determine the image file name. This is subject to change
6765 // when iSCSI disks are here (we should either query a
6766 // storage-specific interface from IHardDisk, or "standardize"
6767 // the location property)
6768 hrc = hardDisk->COMGETTER(Location)(&str); H();
6769 STR_CONV();
6770 LogFlowFunc (("LUN#%d: leaf image '%s'\n", iLUN, psz));
6771 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6772 STR_FREE();
6773 /* Create an inversed tree of parents. */
6774 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6775 for (PCFGMNODE pParent = pCfg;;)
6776 {
6777 ComPtr<IHardDisk> curHardDisk;
6778 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6779 if (!curHardDisk)
6780 break;
6781
6782 PCFGMNODE pCur;
6783 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6784 /// @todo (dmik) we temporarily use the location property to
6785 // determine the image file name. This is subject to change
6786 // when iSCSI disks are here (we should either query a
6787 // storage-specific interface from IHardDisk, or "standardize"
6788 // the location property)
6789 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6790 STR_CONV();
6791 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6792 STR_FREE();
6793
6794 /* next */
6795 pParent = pCur;
6796 parentHardDisk = curHardDisk;
6797 }
6798
6799 /*
6800 * Attach the new driver.
6801 */
6802 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, iLUN, NULL); RC_CHECK();
6803
6804 LogFlowFunc (("Returns success\n"));
6805 return rc;
6806}
6807
6808
6809/**
6810 * Thread for executing the saved state operation.
6811 *
6812 * @param Thread The thread handle.
6813 * @param pvUser Pointer to a VMSaveTask structure.
6814 * @return VINF_SUCCESS (ignored).
6815 *
6816 * @note Locks the Console object for writing.
6817 */
6818/*static*/
6819DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6820{
6821 LogFlowFuncEnter();
6822
6823 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6824 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6825
6826 Assert (!task->mSavedStateFile.isNull());
6827 Assert (!task->mProgress.isNull());
6828
6829 const ComObjPtr <Console> &that = task->mConsole;
6830
6831 /*
6832 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6833 * protect mpVM because VMSaveTask does that
6834 */
6835
6836 Utf8Str errMsg;
6837 HRESULT rc = S_OK;
6838
6839 if (task->mIsSnapshot)
6840 {
6841 Assert (!task->mServerProgress.isNull());
6842 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6843
6844 rc = task->mServerProgress->WaitForCompletion (-1);
6845 if (SUCCEEDED (rc))
6846 {
6847 HRESULT result = S_OK;
6848 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6849 if (SUCCEEDED (rc))
6850 rc = result;
6851 }
6852 }
6853
6854 if (SUCCEEDED (rc))
6855 {
6856 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6857
6858 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6859 Console::stateProgressCallback,
6860 static_cast <VMProgressTask *> (task.get()));
6861 if (VBOX_FAILURE (vrc))
6862 {
6863 errMsg = Utf8StrFmt (
6864 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6865 task->mSavedStateFile.raw(), vrc);
6866 rc = E_FAIL;
6867 }
6868 }
6869
6870 /* lock the console sonce we're going to access it */
6871 AutoWriteLock thatLock (that);
6872
6873 if (SUCCEEDED (rc))
6874 {
6875 if (task->mIsSnapshot)
6876 do
6877 {
6878 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
6879
6880 ComPtr <IHardDiskAttachmentCollection> hdaColl;
6881 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
6882 if (FAILED (rc))
6883 break;
6884 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
6885 rc = hdaColl->Enumerate (hdaEn.asOutParam());
6886 if (FAILED (rc))
6887 break;
6888 BOOL more = FALSE;
6889 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
6890 {
6891 ComPtr <IHardDiskAttachment> hda;
6892 rc = hdaEn->GetNext (hda.asOutParam());
6893 if (FAILED (rc))
6894 break;
6895
6896 PVMREQ pReq;
6897 IHardDiskAttachment *pHda = hda;
6898 /*
6899 * don't leave the lock since reconfigureVDI isn't going to
6900 * access Console.
6901 */
6902 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
6903 (PFNRT)reconfigureVDI, 3, that->mpVM,
6904 pHda, &rc);
6905 if (VBOX_SUCCESS (rc))
6906 rc = pReq->iStatus;
6907 VMR3ReqFree (pReq);
6908 if (FAILED (rc))
6909 break;
6910 if (VBOX_FAILURE (vrc))
6911 {
6912 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
6913 rc = E_FAIL;
6914 break;
6915 }
6916 }
6917 }
6918 while (0);
6919 }
6920
6921 /* finalize the procedure regardless of the result */
6922 if (task->mIsSnapshot)
6923 {
6924 /*
6925 * finalize the requested snapshot object.
6926 * This will reset the machine state to the state it had right
6927 * before calling mControl->BeginTakingSnapshot().
6928 */
6929 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
6930 }
6931 else
6932 {
6933 /*
6934 * finalize the requested save state procedure.
6935 * In case of success, the server will set the machine state to Saved;
6936 * in case of failure it will reset the it to the state it had right
6937 * before calling mControl->BeginSavingState().
6938 */
6939 that->mControl->EndSavingState (SUCCEEDED (rc));
6940 }
6941
6942 /* synchronize the state with the server */
6943 if (task->mIsSnapshot || FAILED (rc))
6944 {
6945 if (task->mLastMachineState == MachineState_Running)
6946 {
6947 /* restore the paused state if appropriate */
6948 that->setMachineStateLocally (MachineState_Paused);
6949 /* restore the running state if appropriate */
6950 that->Resume();
6951 }
6952 else
6953 that->setMachineStateLocally (task->mLastMachineState);
6954 }
6955 else
6956 {
6957 /*
6958 * The machine has been successfully saved, so power it down
6959 * (vmstateChangeCallback() will set state to Saved on success).
6960 * Note: we release the task's VM caller, otherwise it will
6961 * deadlock.
6962 */
6963 task->releaseVMCaller();
6964
6965 rc = that->powerDown();
6966 }
6967
6968 /* notify the progress object about operation completion */
6969 if (SUCCEEDED (rc))
6970 task->mProgress->notifyComplete (S_OK);
6971 else
6972 {
6973 if (!errMsg.isNull())
6974 task->mProgress->notifyComplete (rc,
6975 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
6976 else
6977 task->mProgress->notifyComplete (rc);
6978 }
6979
6980 LogFlowFuncLeave();
6981 return VINF_SUCCESS;
6982}
6983
6984/**
6985 * Thread for powering down the Console.
6986 *
6987 * @param Thread The thread handle.
6988 * @param pvUser Pointer to the VMTask structure.
6989 * @return VINF_SUCCESS (ignored).
6990 *
6991 * @note Locks the Console object for writing.
6992 */
6993/*static*/
6994DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
6995{
6996 LogFlowFuncEnter();
6997
6998 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
6999 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7000
7001 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
7002
7003 const ComObjPtr <Console> &that = task->mConsole;
7004
7005 /*
7006 * Note: no need to use addCaller() to protect Console
7007 * because VMTask does that
7008 */
7009
7010 /* release VM caller to let powerDown() proceed */
7011 task->releaseVMCaller();
7012
7013 HRESULT rc = that->powerDown();
7014 AssertComRC (rc);
7015
7016 LogFlowFuncLeave();
7017 return VINF_SUCCESS;
7018}
7019
7020/**
7021 * The Main status driver instance data.
7022 */
7023typedef struct DRVMAINSTATUS
7024{
7025 /** The LED connectors. */
7026 PDMILEDCONNECTORS ILedConnectors;
7027 /** Pointer to the LED ports interface above us. */
7028 PPDMILEDPORTS pLedPorts;
7029 /** Pointer to the array of LED pointers. */
7030 PPDMLED *papLeds;
7031 /** The unit number corresponding to the first entry in the LED array. */
7032 RTUINT iFirstLUN;
7033 /** The unit number corresponding to the last entry in the LED array.
7034 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7035 RTUINT iLastLUN;
7036} DRVMAINSTATUS, *PDRVMAINSTATUS;
7037
7038
7039/**
7040 * Notification about a unit which have been changed.
7041 *
7042 * The driver must discard any pointers to data owned by
7043 * the unit and requery it.
7044 *
7045 * @param pInterface Pointer to the interface structure containing the called function pointer.
7046 * @param iLUN The unit number.
7047 */
7048DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7049{
7050 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7051 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7052 {
7053 PPDMLED pLed;
7054 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7055 if (VBOX_FAILURE(rc))
7056 pLed = NULL;
7057 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7058 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7059 }
7060}
7061
7062
7063/**
7064 * Queries an interface to the driver.
7065 *
7066 * @returns Pointer to interface.
7067 * @returns NULL if the interface was not supported by the driver.
7068 * @param pInterface Pointer to this interface structure.
7069 * @param enmInterface The requested interface identification.
7070 */
7071DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7072{
7073 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7074 PDRVMAINSTATUS pDrv = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7075 switch (enmInterface)
7076 {
7077 case PDMINTERFACE_BASE:
7078 return &pDrvIns->IBase;
7079 case PDMINTERFACE_LED_CONNECTORS:
7080 return &pDrv->ILedConnectors;
7081 default:
7082 return NULL;
7083 }
7084}
7085
7086
7087/**
7088 * Destruct a status driver instance.
7089 *
7090 * @returns VBox status.
7091 * @param pDrvIns The driver instance data.
7092 */
7093DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7094{
7095 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7096 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7097 if (pData->papLeds)
7098 {
7099 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7100 while (iLed-- > 0)
7101 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7102 }
7103}
7104
7105
7106/**
7107 * Construct a status driver instance.
7108 *
7109 * @returns VBox status.
7110 * @param pDrvIns The driver instance data.
7111 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7112 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7113 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7114 * iInstance it's expected to be used a bit in this function.
7115 */
7116DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7117{
7118 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7119 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7120
7121 /*
7122 * Validate configuration.
7123 */
7124 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7125 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7126 PPDMIBASE pBaseIgnore;
7127 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7128 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7129 {
7130 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7131 return VERR_PDM_DRVINS_NO_ATTACH;
7132 }
7133
7134 /*
7135 * Data.
7136 */
7137 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7138 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7139
7140 /*
7141 * Read config.
7142 */
7143 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7144 if (VBOX_FAILURE(rc))
7145 {
7146 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7147 return rc;
7148 }
7149
7150 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7151 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7152 pData->iFirstLUN = 0;
7153 else if (VBOX_FAILURE(rc))
7154 {
7155 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7156 return rc;
7157 }
7158
7159 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7160 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7161 pData->iLastLUN = 0;
7162 else if (VBOX_FAILURE(rc))
7163 {
7164 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7165 return rc;
7166 }
7167 if (pData->iFirstLUN > pData->iLastLUN)
7168 {
7169 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7170 return VERR_GENERAL_FAILURE;
7171 }
7172
7173 /*
7174 * Get the ILedPorts interface of the above driver/device and
7175 * query the LEDs we want.
7176 */
7177 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7178 if (!pData->pLedPorts)
7179 {
7180 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7181 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7182 }
7183
7184 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7185 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7186
7187 return VINF_SUCCESS;
7188}
7189
7190
7191/**
7192 * Keyboard driver registration record.
7193 */
7194const PDMDRVREG Console::DrvStatusReg =
7195{
7196 /* u32Version */
7197 PDM_DRVREG_VERSION,
7198 /* szDriverName */
7199 "MainStatus",
7200 /* pszDescription */
7201 "Main status driver (Main as in the API).",
7202 /* fFlags */
7203 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7204 /* fClass. */
7205 PDM_DRVREG_CLASS_STATUS,
7206 /* cMaxInstances */
7207 ~0,
7208 /* cbInstance */
7209 sizeof(DRVMAINSTATUS),
7210 /* pfnConstruct */
7211 Console::drvStatus_Construct,
7212 /* pfnDestruct */
7213 Console::drvStatus_Destruct,
7214 /* pfnIOCtl */
7215 NULL,
7216 /* pfnPowerOn */
7217 NULL,
7218 /* pfnReset */
7219 NULL,
7220 /* pfnSuspend */
7221 NULL,
7222 /* pfnResume */
7223 NULL,
7224 /* pfnDetach */
7225 NULL
7226};
7227
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