VirtualBox

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

Last change on this file since 8471 was 8471, checked in by vboxsync, 17 years ago

More USB stuff.

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