VirtualBox

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

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

Older 82543GC chip support, works in linux only.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 211.1 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# ifdef RT_OS_DARWIN
2014 /* Notify the USB Proxy that we're about to detach the device. Since
2015 * we don't dare do IPC when holding the console lock, so we'll have
2016 * to revalidate the device when we get back. */
2017 alock.leave();
2018 HRESULT rc2 = mControl->DetachUSBDevice (aId, false /* aDone */);
2019 if (FAILED (rc2))
2020 return rc2;
2021 alock.enter();
2022
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
2030 /* First, request VMM to detach the device */
2031 HRESULT rc = detachUSBDevice (it);
2032
2033 if (SUCCEEDED (rc))
2034 {
2035 /* leave the lock since we don't need it any more (note though that
2036 * the USB Proxy service must not call us back here) */
2037 alock.leave();
2038
2039 /* Request the device release. Even if it fails, the device will
2040 * remain as held by proxy, which is OK for us (the VM process). */
2041 rc = mControl->DetachUSBDevice (aId, true /* aDone */);
2042 }
2043
2044 return rc;
2045
2046
2047#else /* !VBOX_WITH_USB */
2048 return setError (E_INVALIDARG,
2049 tr ("USB device with UUID {%Vuuid} is not attached to this machine"),
2050 Guid (aId).raw());
2051#endif /* !VBOX_WITH_USB */
2052}
2053
2054STDMETHODIMP
2055Console::CreateSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath, BOOL aWritable)
2056{
2057 if (!aName || !aHostPath)
2058 return E_INVALIDARG;
2059
2060 AutoCaller autoCaller (this);
2061 CheckComRCReturnRC (autoCaller.rc());
2062
2063 AutoWriteLock alock (this);
2064
2065 /// @todo see @todo in AttachUSBDevice() about the Paused state
2066 if (mMachineState == MachineState_Saved)
2067 return setError (E_FAIL,
2068 tr ("Cannot create a transient shared folder on the "
2069 "machine in the saved state"));
2070 if (mMachineState > MachineState_Paused)
2071 return setError (E_FAIL,
2072 tr ("Cannot create a transient shared folder on the "
2073 "machine while it is changing the state (machine state: %d)"),
2074 mMachineState);
2075
2076 ComObjPtr <SharedFolder> sharedFolder;
2077 HRESULT rc = findSharedFolder (aName, sharedFolder, false /* aSetError */);
2078 if (SUCCEEDED (rc))
2079 return setError (E_FAIL,
2080 tr ("Shared folder named '%ls' already exists"), aName);
2081
2082 sharedFolder.createObject();
2083 rc = sharedFolder->init (this, aName, aHostPath, aWritable);
2084 CheckComRCReturnRC (rc);
2085
2086 BOOL accessible = FALSE;
2087 rc = sharedFolder->COMGETTER(Accessible) (&accessible);
2088 CheckComRCReturnRC (rc);
2089
2090 if (!accessible)
2091 return setError (E_FAIL,
2092 tr ("Shared folder host path '%ls' is not accessible"), aHostPath);
2093
2094 /* protect mpVM (if not NULL) */
2095 AutoVMCallerQuietWeak autoVMCaller (this);
2096
2097 if (mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive())
2098 {
2099 /* If the VM is online and supports shared folders, share this folder
2100 * under the specified name. */
2101
2102 /* first, remove the machine or the global folder if there is any */
2103 SharedFolderDataMap::const_iterator it;
2104 if (findOtherSharedFolder (aName, it))
2105 {
2106 rc = removeSharedFolder (aName);
2107 CheckComRCReturnRC (rc);
2108 }
2109
2110 /* second, create the given folder */
2111 rc = createSharedFolder (aName, SharedFolderData (aHostPath, aWritable));
2112 CheckComRCReturnRC (rc);
2113 }
2114
2115 mSharedFolders.insert (std::make_pair (aName, sharedFolder));
2116
2117 /* notify console callbacks after the folder is added to the list */
2118 {
2119 CallbackList::iterator it = mCallbacks.begin();
2120 while (it != mCallbacks.end())
2121 (*it++)->OnSharedFolderChange (Scope_Session);
2122 }
2123
2124 return rc;
2125}
2126
2127STDMETHODIMP Console::RemoveSharedFolder (INPTR BSTR aName)
2128{
2129 if (!aName)
2130 return E_INVALIDARG;
2131
2132 AutoCaller autoCaller (this);
2133 CheckComRCReturnRC (autoCaller.rc());
2134
2135 AutoWriteLock alock (this);
2136
2137 /// @todo see @todo in AttachUSBDevice() about the Paused state
2138 if (mMachineState == MachineState_Saved)
2139 return setError (E_FAIL,
2140 tr ("Cannot remove a transient shared folder from the "
2141 "machine in the saved state"));
2142 if (mMachineState > MachineState_Paused)
2143 return setError (E_FAIL,
2144 tr ("Cannot remove a transient shared folder from the "
2145 "machine while it is changing the state (machine state: %d)"),
2146 mMachineState);
2147
2148 ComObjPtr <SharedFolder> sharedFolder;
2149 HRESULT rc = findSharedFolder (aName, sharedFolder, true /* aSetError */);
2150 CheckComRCReturnRC (rc);
2151
2152 /* protect mpVM (if not NULL) */
2153 AutoVMCallerQuietWeak autoVMCaller (this);
2154
2155 if (mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive())
2156 {
2157 /* if the VM is online and supports shared folders, UNshare this
2158 * folder. */
2159
2160 /* first, remove the given folder */
2161 rc = removeSharedFolder (aName);
2162 CheckComRCReturnRC (rc);
2163
2164 /* first, remove the machine or the global folder if there is any */
2165 SharedFolderDataMap::const_iterator it;
2166 if (findOtherSharedFolder (aName, it))
2167 {
2168 rc = createSharedFolder (aName, it->second);
2169 /* don't check rc here because we need to remove the console
2170 * folder from the collection even on failure */
2171 }
2172 }
2173
2174 mSharedFolders.erase (aName);
2175
2176 /* notify console callbacks after the folder is removed to the list */
2177 {
2178 CallbackList::iterator it = mCallbacks.begin();
2179 while (it != mCallbacks.end())
2180 (*it++)->OnSharedFolderChange (Scope_Session);
2181 }
2182
2183 return rc;
2184}
2185
2186STDMETHODIMP Console::TakeSnapshot (INPTR BSTR aName, INPTR BSTR aDescription,
2187 IProgress **aProgress)
2188{
2189 LogFlowThisFuncEnter();
2190 LogFlowThisFunc (("aName='%ls' mMachineState=%08X\n", aName, mMachineState));
2191
2192 if (!aName)
2193 return E_INVALIDARG;
2194 if (!aProgress)
2195 return E_POINTER;
2196
2197 AutoCaller autoCaller (this);
2198 CheckComRCReturnRC (autoCaller.rc());
2199
2200 AutoWriteLock alock (this);
2201
2202 if (mMachineState > MachineState_Paused)
2203 {
2204 return setError (E_FAIL,
2205 tr ("Cannot take a snapshot of the machine "
2206 "while it is changing the state (machine state: %d)"),
2207 mMachineState);
2208 }
2209
2210 /* memorize the current machine state */
2211 MachineState_T lastMachineState = mMachineState;
2212
2213 if (mMachineState == MachineState_Running)
2214 {
2215 HRESULT rc = Pause();
2216 CheckComRCReturnRC (rc);
2217 }
2218
2219 HRESULT rc = S_OK;
2220
2221 bool takingSnapshotOnline = mMachineState == MachineState_Paused;
2222
2223 /*
2224 * create a descriptionless VM-side progress object
2225 * (only when creating a snapshot online)
2226 */
2227 ComObjPtr <Progress> saveProgress;
2228 if (takingSnapshotOnline)
2229 {
2230 saveProgress.createObject();
2231 rc = saveProgress->init (FALSE, 1, Bstr (tr ("Saving the execution state")));
2232 AssertComRCReturn (rc, rc);
2233 }
2234
2235 bool beganTakingSnapshot = false;
2236 bool taskCreationFailed = false;
2237
2238 do
2239 {
2240 /* create a task object early to ensure mpVM protection is successful */
2241 std::auto_ptr <VMSaveTask> task;
2242 if (takingSnapshotOnline)
2243 {
2244 task.reset (new VMSaveTask (this, saveProgress));
2245 rc = task->rc();
2246 /*
2247 * If we fail here it means a PowerDown() call happened on another
2248 * thread while we were doing Pause() (which leaves the Console lock).
2249 * We assign PowerDown() a higher precendence than TakeSnapshot(),
2250 * therefore just return the error to the caller.
2251 */
2252 if (FAILED (rc))
2253 {
2254 taskCreationFailed = true;
2255 break;
2256 }
2257 }
2258
2259 Bstr stateFilePath;
2260 ComPtr <IProgress> serverProgress;
2261
2262 /*
2263 * request taking a new snapshot object on the server
2264 * (this will set the machine state to Saving on the server to block
2265 * others from accessing this machine)
2266 */
2267 rc = mControl->BeginTakingSnapshot (this, aName, aDescription,
2268 saveProgress, stateFilePath.asOutParam(),
2269 serverProgress.asOutParam());
2270 if (FAILED (rc))
2271 break;
2272
2273 /*
2274 * state file is non-null only when the VM is paused
2275 * (i.e. createing a snapshot online)
2276 */
2277 ComAssertBreak (
2278 (!stateFilePath.isNull() && takingSnapshotOnline) ||
2279 (stateFilePath.isNull() && !takingSnapshotOnline),
2280 rc = E_FAIL);
2281
2282 beganTakingSnapshot = true;
2283
2284 /* sync the state with the server */
2285 setMachineStateLocally (MachineState_Saving);
2286
2287 /*
2288 * create a combined VM-side progress object and start the save task
2289 * (only when creating a snapshot online)
2290 */
2291 ComObjPtr <CombinedProgress> combinedProgress;
2292 if (takingSnapshotOnline)
2293 {
2294 combinedProgress.createObject();
2295 rc = combinedProgress->init (static_cast <IConsole *> (this),
2296 Bstr (tr ("Taking snapshot of virtual machine")),
2297 serverProgress, saveProgress);
2298 AssertComRCBreakRC (rc);
2299
2300 /* setup task object and thread to carry out the operation asynchronously */
2301 task->mIsSnapshot = true;
2302 task->mSavedStateFile = stateFilePath;
2303 task->mServerProgress = serverProgress;
2304 /* set the state the operation thread will restore when it is finished */
2305 task->mLastMachineState = lastMachineState;
2306
2307 /* create a thread to wait until the VM state is saved */
2308 int vrc = RTThreadCreate (NULL, Console::saveStateThread, (void *) task.get(),
2309 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMTakeSnap");
2310
2311 ComAssertMsgRCBreak (vrc, ("Could not create VMTakeSnap thread (%Vrc)\n", vrc),
2312 rc = E_FAIL);
2313
2314 /* task is now owned by saveStateThread(), so release it */
2315 task.release();
2316 }
2317
2318 if (SUCCEEDED (rc))
2319 {
2320 /* return the correct progress to the caller */
2321 if (combinedProgress)
2322 combinedProgress.queryInterfaceTo (aProgress);
2323 else
2324 serverProgress.queryInterfaceTo (aProgress);
2325 }
2326 }
2327 while (0);
2328
2329 if (FAILED (rc) && !taskCreationFailed)
2330 {
2331 /* preserve existing error info */
2332 ErrorInfoKeeper eik;
2333
2334 if (beganTakingSnapshot && takingSnapshotOnline)
2335 {
2336 /*
2337 * cancel the requested snapshot (only when creating a snapshot
2338 * online, otherwise the server will cancel the snapshot itself).
2339 * This will reset the machine state to the state it had right
2340 * before calling mControl->BeginTakingSnapshot().
2341 */
2342 mControl->EndTakingSnapshot (FALSE);
2343 }
2344
2345 if (lastMachineState == MachineState_Running)
2346 {
2347 /* restore the paused state if appropriate */
2348 setMachineStateLocally (MachineState_Paused);
2349 /* restore the running state if appropriate */
2350 Resume();
2351 }
2352 else
2353 setMachineStateLocally (lastMachineState);
2354 }
2355
2356 LogFlowThisFunc (("rc=%08X\n", rc));
2357 LogFlowThisFuncLeave();
2358 return rc;
2359}
2360
2361STDMETHODIMP Console::DiscardSnapshot (INPTR GUIDPARAM aId, IProgress **aProgress)
2362{
2363 if (Guid (aId).isEmpty())
2364 return E_INVALIDARG;
2365 if (!aProgress)
2366 return E_POINTER;
2367
2368 AutoCaller autoCaller (this);
2369 CheckComRCReturnRC (autoCaller.rc());
2370
2371 AutoWriteLock alock (this);
2372
2373 if (mMachineState >= MachineState_Running)
2374 return setError (E_FAIL,
2375 tr ("Cannot discard a snapshot of the running machine "
2376 "(machine state: %d)"),
2377 mMachineState);
2378
2379 MachineState_T machineState = MachineState_Null;
2380 HRESULT rc = mControl->DiscardSnapshot (this, aId, &machineState, aProgress);
2381 CheckComRCReturnRC (rc);
2382
2383 setMachineStateLocally (machineState);
2384 return S_OK;
2385}
2386
2387STDMETHODIMP Console::DiscardCurrentState (IProgress **aProgress)
2388{
2389 AutoCaller autoCaller (this);
2390 CheckComRCReturnRC (autoCaller.rc());
2391
2392 AutoWriteLock alock (this);
2393
2394 if (mMachineState >= MachineState_Running)
2395 return setError (E_FAIL,
2396 tr ("Cannot discard the current state of the running machine "
2397 "(nachine state: %d)"),
2398 mMachineState);
2399
2400 MachineState_T machineState = MachineState_Null;
2401 HRESULT rc = mControl->DiscardCurrentState (this, &machineState, aProgress);
2402 CheckComRCReturnRC (rc);
2403
2404 setMachineStateLocally (machineState);
2405 return S_OK;
2406}
2407
2408STDMETHODIMP Console::DiscardCurrentSnapshotAndState (IProgress **aProgress)
2409{
2410 AutoCaller autoCaller (this);
2411 CheckComRCReturnRC (autoCaller.rc());
2412
2413 AutoWriteLock alock (this);
2414
2415 if (mMachineState >= MachineState_Running)
2416 return setError (E_FAIL,
2417 tr ("Cannot discard the current snapshot and state of the "
2418 "running machine (machine state: %d)"),
2419 mMachineState);
2420
2421 MachineState_T machineState = MachineState_Null;
2422 HRESULT rc =
2423 mControl->DiscardCurrentSnapshotAndState (this, &machineState, aProgress);
2424 CheckComRCReturnRC (rc);
2425
2426 setMachineStateLocally (machineState);
2427 return S_OK;
2428}
2429
2430STDMETHODIMP Console::RegisterCallback (IConsoleCallback *aCallback)
2431{
2432 if (!aCallback)
2433 return E_INVALIDARG;
2434
2435 AutoCaller autoCaller (this);
2436 CheckComRCReturnRC (autoCaller.rc());
2437
2438 AutoWriteLock alock (this);
2439
2440 mCallbacks.push_back (CallbackList::value_type (aCallback));
2441
2442 /* Inform the callback about the current status (for example, the new
2443 * callback must know the current mouse capabilities and the pointer
2444 * shape in order to properly integrate the mouse pointer). */
2445
2446 if (mCallbackData.mpsc.valid)
2447 aCallback->OnMousePointerShapeChange (mCallbackData.mpsc.visible,
2448 mCallbackData.mpsc.alpha,
2449 mCallbackData.mpsc.xHot,
2450 mCallbackData.mpsc.yHot,
2451 mCallbackData.mpsc.width,
2452 mCallbackData.mpsc.height,
2453 mCallbackData.mpsc.shape);
2454 if (mCallbackData.mcc.valid)
2455 aCallback->OnMouseCapabilityChange (mCallbackData.mcc.supportsAbsolute,
2456 mCallbackData.mcc.needsHostCursor);
2457
2458 aCallback->OnAdditionsStateChange();
2459
2460 if (mCallbackData.klc.valid)
2461 aCallback->OnKeyboardLedsChange (mCallbackData.klc.numLock,
2462 mCallbackData.klc.capsLock,
2463 mCallbackData.klc.scrollLock);
2464
2465 /* Note: we don't call OnStateChange for new callbacks because the
2466 * machine state is a) not actually changed on callback registration
2467 * and b) can be always queried from Console. */
2468
2469 return S_OK;
2470}
2471
2472STDMETHODIMP Console::UnregisterCallback (IConsoleCallback *aCallback)
2473{
2474 if (!aCallback)
2475 return E_INVALIDARG;
2476
2477 AutoCaller autoCaller (this);
2478 CheckComRCReturnRC (autoCaller.rc());
2479
2480 AutoWriteLock alock (this);
2481
2482 CallbackList::iterator it;
2483 it = std::find (mCallbacks.begin(),
2484 mCallbacks.end(),
2485 CallbackList::value_type (aCallback));
2486 if (it == mCallbacks.end())
2487 return setError (E_INVALIDARG,
2488 tr ("The given callback handler is not registered"));
2489
2490 mCallbacks.erase (it);
2491 return S_OK;
2492}
2493
2494// Non-interface public methods
2495/////////////////////////////////////////////////////////////////////////////
2496
2497/**
2498 * Called by IInternalSessionControl::OnDVDDriveChange().
2499 *
2500 * @note Locks this object for writing.
2501 */
2502HRESULT Console::onDVDDriveChange()
2503{
2504 LogFlowThisFunc (("\n"));
2505
2506 AutoCaller autoCaller (this);
2507 AssertComRCReturnRC (autoCaller.rc());
2508
2509 /* doDriveChange() needs a write lock */
2510 AutoWriteLock alock (this);
2511
2512 /* Ignore callbacks when there's no VM around */
2513 if (!mpVM)
2514 return S_OK;
2515
2516 /* protect mpVM */
2517 AutoVMCaller autoVMCaller (this);
2518 CheckComRCReturnRC (autoVMCaller.rc());
2519
2520 /* Get the current DVD state */
2521 HRESULT rc;
2522 DriveState_T eState;
2523
2524 rc = mDVDDrive->COMGETTER (State) (&eState);
2525 ComAssertComRCRetRC (rc);
2526
2527 /* Paranoia */
2528 if ( eState == DriveState_NotMounted
2529 && meDVDState == DriveState_NotMounted)
2530 {
2531 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2532 return S_OK;
2533 }
2534
2535 /* Get the path string and other relevant properties */
2536 Bstr Path;
2537 bool fPassthrough = false;
2538 switch (eState)
2539 {
2540 case DriveState_ImageMounted:
2541 {
2542 ComPtr <IDVDImage> ImagePtr;
2543 rc = mDVDDrive->GetImage (ImagePtr.asOutParam());
2544 if (SUCCEEDED (rc))
2545 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2546 break;
2547 }
2548
2549 case DriveState_HostDriveCaptured:
2550 {
2551 ComPtr <IHostDVDDrive> DrivePtr;
2552 BOOL enabled;
2553 rc = mDVDDrive->GetHostDrive (DrivePtr.asOutParam());
2554 if (SUCCEEDED (rc))
2555 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2556 if (SUCCEEDED (rc))
2557 rc = mDVDDrive->COMGETTER (Passthrough) (&enabled);
2558 if (SUCCEEDED (rc))
2559 fPassthrough = !!enabled;
2560 break;
2561 }
2562
2563 case DriveState_NotMounted:
2564 break;
2565
2566 default:
2567 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2568 rc = E_FAIL;
2569 break;
2570 }
2571
2572 AssertComRC (rc);
2573 if (FAILED (rc))
2574 {
2575 LogFlowThisFunc (("Returns %#x\n", rc));
2576 return rc;
2577 }
2578
2579 rc = doDriveChange ("piix3ide", 0, 2, eState, &meDVDState,
2580 Utf8Str (Path).raw(), fPassthrough);
2581
2582 /* notify console callbacks on success */
2583 if (SUCCEEDED (rc))
2584 {
2585 CallbackList::iterator it = mCallbacks.begin();
2586 while (it != mCallbacks.end())
2587 (*it++)->OnDVDDriveChange();
2588 }
2589
2590 return rc;
2591}
2592
2593
2594/**
2595 * Called by IInternalSessionControl::OnFloppyDriveChange().
2596 *
2597 * @note Locks this object for writing.
2598 */
2599HRESULT Console::onFloppyDriveChange()
2600{
2601 LogFlowThisFunc (("\n"));
2602
2603 AutoCaller autoCaller (this);
2604 AssertComRCReturnRC (autoCaller.rc());
2605
2606 /* doDriveChange() needs a write lock */
2607 AutoWriteLock alock (this);
2608
2609 /* Ignore callbacks when there's no VM around */
2610 if (!mpVM)
2611 return S_OK;
2612
2613 /* protect mpVM */
2614 AutoVMCaller autoVMCaller (this);
2615 CheckComRCReturnRC (autoVMCaller.rc());
2616
2617 /* Get the current floppy state */
2618 HRESULT rc;
2619 DriveState_T eState;
2620
2621 /* If the floppy drive is disabled, we're not interested */
2622 BOOL fEnabled;
2623 rc = mFloppyDrive->COMGETTER (Enabled) (&fEnabled);
2624 ComAssertComRCRetRC (rc);
2625
2626 if (!fEnabled)
2627 return S_OK;
2628
2629 rc = mFloppyDrive->COMGETTER (State) (&eState);
2630 ComAssertComRCRetRC (rc);
2631
2632 Log2 (("onFloppyDriveChange: eState=%d meFloppyState=%d\n", eState, meFloppyState));
2633
2634
2635 /* Paranoia */
2636 if ( eState == DriveState_NotMounted
2637 && meFloppyState == DriveState_NotMounted)
2638 {
2639 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2640 return S_OK;
2641 }
2642
2643 /* Get the path string and other relevant properties */
2644 Bstr Path;
2645 switch (eState)
2646 {
2647 case DriveState_ImageMounted:
2648 {
2649 ComPtr <IFloppyImage> ImagePtr;
2650 rc = mFloppyDrive->GetImage (ImagePtr.asOutParam());
2651 if (SUCCEEDED (rc))
2652 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2653 break;
2654 }
2655
2656 case DriveState_HostDriveCaptured:
2657 {
2658 ComPtr <IHostFloppyDrive> DrivePtr;
2659 rc = mFloppyDrive->GetHostDrive (DrivePtr.asOutParam());
2660 if (SUCCEEDED (rc))
2661 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2662 break;
2663 }
2664
2665 case DriveState_NotMounted:
2666 break;
2667
2668 default:
2669 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2670 rc = E_FAIL;
2671 break;
2672 }
2673
2674 AssertComRC (rc);
2675 if (FAILED (rc))
2676 {
2677 LogFlowThisFunc (("Returns %#x\n", rc));
2678 return rc;
2679 }
2680
2681 rc = doDriveChange ("i82078", 0, 0, eState, &meFloppyState,
2682 Utf8Str (Path).raw(), false);
2683
2684 /* notify console callbacks on success */
2685 if (SUCCEEDED (rc))
2686 {
2687 CallbackList::iterator it = mCallbacks.begin();
2688 while (it != mCallbacks.end())
2689 (*it++)->OnFloppyDriveChange();
2690 }
2691
2692 return rc;
2693}
2694
2695
2696/**
2697 * Process a floppy or dvd change.
2698 *
2699 * @returns COM status code.
2700 *
2701 * @param pszDevice The PDM device name.
2702 * @param uInstance The PDM device instance.
2703 * @param uLun The PDM LUN number of the drive.
2704 * @param eState The new state.
2705 * @param peState Pointer to the variable keeping the actual state of the drive.
2706 * This will be both read and updated to eState or other appropriate state.
2707 * @param pszPath The path to the media / drive which is now being mounted / captured.
2708 * If NULL no media or drive is attached and the lun will be configured with
2709 * the default block driver with no media. This will also be the state if
2710 * mounting / capturing the specified media / drive fails.
2711 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2712 *
2713 * @note Locks this object for writing.
2714 */
2715HRESULT Console::doDriveChange (const char *pszDevice, unsigned uInstance, unsigned uLun, DriveState_T eState,
2716 DriveState_T *peState, const char *pszPath, bool fPassthrough)
2717{
2718 LogFlowThisFunc (("pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2719 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2720 pszDevice, pszDevice, uInstance, uLun, eState,
2721 peState, *peState, pszPath, pszPath, fPassthrough));
2722
2723 AutoCaller autoCaller (this);
2724 AssertComRCReturnRC (autoCaller.rc());
2725
2726 /* We will need to release the write lock before calling EMT */
2727 AutoWriteLock alock (this);
2728
2729 /* protect mpVM */
2730 AutoVMCaller autoVMCaller (this);
2731 CheckComRCReturnRC (autoVMCaller.rc());
2732
2733 /*
2734 * Call worker in EMT, that's faster and safer than doing everything
2735 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2736 * here to make requests from under the lock in order to serialize them.
2737 */
2738 PVMREQ pReq;
2739 int vrc = VMR3ReqCall (mpVM, &pReq, 0 /* no wait! */,
2740 (PFNRT) Console::changeDrive, 8,
2741 this, pszDevice, uInstance, uLun, eState, peState,
2742 pszPath, fPassthrough);
2743 /// @todo (r=dmik) bird, it would be nice to have a special VMR3Req method
2744 // for that purpose, that doesn't return useless VERR_TIMEOUT
2745 if (vrc == VERR_TIMEOUT)
2746 vrc = VINF_SUCCESS;
2747
2748 /* leave the lock before waiting for a result (EMT will call us back!) */
2749 alock.leave();
2750
2751 if (VBOX_SUCCESS (vrc))
2752 {
2753 vrc = VMR3ReqWait (pReq, RT_INDEFINITE_WAIT);
2754 AssertRC (vrc);
2755 if (VBOX_SUCCESS (vrc))
2756 vrc = pReq->iStatus;
2757 }
2758 VMR3ReqFree (pReq);
2759
2760 if (VBOX_SUCCESS (vrc))
2761 {
2762 LogFlowThisFunc (("Returns S_OK\n"));
2763 return S_OK;
2764 }
2765
2766 if (pszPath)
2767 return setError (E_FAIL,
2768 tr ("Could not mount the media/drive '%s' (%Vrc)"), pszPath, vrc);
2769
2770 return setError (E_FAIL,
2771 tr ("Could not unmount the currently mounted media/drive (%Vrc)"), vrc);
2772}
2773
2774
2775/**
2776 * Performs the Floppy/DVD change in EMT.
2777 *
2778 * @returns VBox status code.
2779 *
2780 * @param pThis Pointer to the Console object.
2781 * @param pszDevice The PDM device name.
2782 * @param uInstance The PDM device instance.
2783 * @param uLun The PDM LUN number of the drive.
2784 * @param eState The new state.
2785 * @param peState Pointer to the variable keeping the actual state of the drive.
2786 * This will be both read and updated to eState or other appropriate state.
2787 * @param pszPath The path to the media / drive which is now being mounted / captured.
2788 * If NULL no media or drive is attached and the lun will be configured with
2789 * the default block driver with no media. This will also be the state if
2790 * mounting / capturing the specified media / drive fails.
2791 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2792 *
2793 * @thread EMT
2794 * @note Locks the Console object for writing.
2795 */
2796DECLCALLBACK(int) Console::changeDrive (Console *pThis, const char *pszDevice, unsigned uInstance, unsigned uLun,
2797 DriveState_T eState, DriveState_T *peState,
2798 const char *pszPath, bool fPassthrough)
2799{
2800 LogFlowFunc (("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2801 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2802 pThis, pszDevice, pszDevice, uInstance, uLun, eState,
2803 peState, *peState, pszPath, pszPath, fPassthrough));
2804
2805 AssertReturn (pThis, VERR_INVALID_PARAMETER);
2806
2807 AssertMsg ( (!strcmp (pszDevice, "i82078") && uLun == 0 && uInstance == 0)
2808 || (!strcmp (pszDevice, "piix3ide") && uLun == 2 && uInstance == 0),
2809 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
2810
2811 AutoCaller autoCaller (pThis);
2812 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
2813
2814 /*
2815 * Locking the object before doing VMR3* calls is quite safe here, since
2816 * we're on EMT. Write lock is necessary because we indirectly modify the
2817 * meDVDState/meFloppyState members (pointed to by peState).
2818 */
2819 AutoWriteLock alock (pThis);
2820
2821 /* protect mpVM */
2822 AutoVMCaller autoVMCaller (pThis);
2823 CheckComRCReturnRC (autoVMCaller.rc());
2824
2825 PVM pVM = pThis->mpVM;
2826
2827 /*
2828 * Suspend the VM first.
2829 *
2830 * The VM must not be running since it might have pending I/O to
2831 * the drive which is being changed.
2832 */
2833 bool fResume;
2834 VMSTATE enmVMState = VMR3GetState (pVM);
2835 switch (enmVMState)
2836 {
2837 case VMSTATE_RESETTING:
2838 case VMSTATE_RUNNING:
2839 {
2840 LogFlowFunc (("Suspending the VM...\n"));
2841 /* disable the callback to prevent Console-level state change */
2842 pThis->mVMStateChangeCallbackDisabled = true;
2843 int rc = VMR3Suspend (pVM);
2844 pThis->mVMStateChangeCallbackDisabled = false;
2845 AssertRCReturn (rc, rc);
2846 fResume = true;
2847 break;
2848 }
2849
2850 case VMSTATE_SUSPENDED:
2851 case VMSTATE_CREATED:
2852 case VMSTATE_OFF:
2853 fResume = false;
2854 break;
2855
2856 default:
2857 AssertMsgFailedReturn (("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
2858 }
2859
2860 int rc = VINF_SUCCESS;
2861 int rcRet = VINF_SUCCESS;
2862
2863 do
2864 {
2865 /*
2866 * Unmount existing media / detach host drive.
2867 */
2868 PPDMIMOUNT pIMount = NULL;
2869 switch (*peState)
2870 {
2871
2872 case DriveState_ImageMounted:
2873 {
2874 /*
2875 * Resolve the interface.
2876 */
2877 PPDMIBASE pBase;
2878 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2879 if (VBOX_FAILURE (rc))
2880 {
2881 if (rc == VERR_PDM_LUN_NOT_FOUND)
2882 rc = VINF_SUCCESS;
2883 AssertRC (rc);
2884 break;
2885 }
2886
2887 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2888 AssertBreak (pIMount, rc = VERR_INVALID_POINTER);
2889
2890 /*
2891 * Unmount the media.
2892 */
2893 rc = pIMount->pfnUnmount (pIMount, false);
2894 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2895 rc = VINF_SUCCESS;
2896 break;
2897 }
2898
2899 case DriveState_HostDriveCaptured:
2900 {
2901 rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2902 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2903 rc = VINF_SUCCESS;
2904 AssertRC (rc);
2905 break;
2906 }
2907
2908 case DriveState_NotMounted:
2909 break;
2910
2911 default:
2912 AssertMsgFailed (("Invalid *peState: %d\n", peState));
2913 break;
2914 }
2915
2916 if (VBOX_FAILURE (rc))
2917 {
2918 rcRet = rc;
2919 break;
2920 }
2921
2922 /*
2923 * Nothing is currently mounted.
2924 */
2925 *peState = DriveState_NotMounted;
2926
2927
2928 /*
2929 * Process the HostDriveCaptured state first, as the fallback path
2930 * means mounting the normal block driver without media.
2931 */
2932 if (eState == DriveState_HostDriveCaptured)
2933 {
2934 /*
2935 * Detach existing driver chain (block).
2936 */
2937 int rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2938 if (VBOX_FAILURE (rc))
2939 {
2940 if (rc == VERR_PDM_LUN_NOT_FOUND)
2941 rc = VINF_SUCCESS;
2942 AssertReleaseRC (rc);
2943 break; /* we're toast */
2944 }
2945 pIMount = NULL;
2946
2947 /*
2948 * Construct a new driver configuration.
2949 */
2950 PCFGMNODE pInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2951 AssertRelease (pInst);
2952 /* nuke anything which might have been left behind. */
2953 CFGMR3RemoveNode (CFGMR3GetChildF (pInst, "LUN#%d", uLun));
2954
2955 /* create a new block driver config */
2956 PCFGMNODE pLunL0;
2957 PCFGMNODE pCfg;
2958 if ( VBOX_SUCCESS (rc = CFGMR3InsertNodeF (pInst, &pLunL0, "LUN#%u", uLun))
2959 && VBOX_SUCCESS (rc = CFGMR3InsertString (pLunL0, "Driver", !strcmp (pszDevice, "i82078") ? "HostFloppy" : "HostDVD"))
2960 && VBOX_SUCCESS (rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg))
2961 && VBOX_SUCCESS (rc = CFGMR3InsertString (pCfg, "Path", pszPath))
2962 && VBOX_SUCCESS (rc = !strcmp (pszDevice, "i82078") ? VINF_SUCCESS : CFGMR3InsertInteger(pCfg, "Passthrough", fPassthrough)))
2963 {
2964 /*
2965 * Attempt to attach the driver.
2966 */
2967 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, NULL);
2968 AssertRC (rc);
2969 }
2970 if (VBOX_FAILURE (rc))
2971 rcRet = rc;
2972 }
2973
2974 /*
2975 * Process the ImageMounted, NotMounted and failed HostDriveCapture cases.
2976 */
2977 rc = VINF_SUCCESS;
2978 switch (eState)
2979 {
2980#define RC_CHECK() do { if (VBOX_FAILURE (rc)) { AssertReleaseRC (rc); break; } } while (0)
2981
2982 case DriveState_HostDriveCaptured:
2983 if (VBOX_SUCCESS (rcRet))
2984 break;
2985 /* fallback: umounted block driver. */
2986 pszPath = NULL;
2987 eState = DriveState_NotMounted;
2988 /* fallthru */
2989 case DriveState_ImageMounted:
2990 case DriveState_NotMounted:
2991 {
2992 /*
2993 * Resolve the drive interface / create the driver.
2994 */
2995 if (!pIMount)
2996 {
2997 PPDMIBASE pBase;
2998 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2999 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3000 {
3001 /*
3002 * We have to create it, so we'll do the full config setup and everything.
3003 */
3004 PCFGMNODE pIdeInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
3005 AssertRelease (pIdeInst);
3006
3007 /* nuke anything which might have been left behind. */
3008 CFGMR3RemoveNode (CFGMR3GetChildF (pIdeInst, "LUN#%d", uLun));
3009
3010 /* create a new block driver config */
3011 PCFGMNODE pLunL0;
3012 rc = CFGMR3InsertNodeF (pIdeInst, &pLunL0, "LUN#%d", uLun); RC_CHECK();
3013 rc = CFGMR3InsertString (pLunL0, "Driver", "Block"); RC_CHECK();
3014 PCFGMNODE pCfg;
3015 rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg); RC_CHECK();
3016 rc = CFGMR3InsertString (pCfg, "Type", !strcmp (pszDevice, "i82078") ? "Floppy 1.44" : "DVD");
3017 RC_CHECK();
3018 rc = CFGMR3InsertInteger (pCfg, "Mountable", 1); RC_CHECK();
3019
3020 /*
3021 * Attach the driver.
3022 */
3023 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, &pBase);
3024 RC_CHECK();
3025 }
3026 else if (VBOX_FAILURE(rc))
3027 {
3028 AssertRC (rc);
3029 return rc;
3030 }
3031
3032 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
3033 if (!pIMount)
3034 {
3035 AssertFailed();
3036 return rc;
3037 }
3038 }
3039
3040 /*
3041 * If we've got an image, let's mount it.
3042 */
3043 if (pszPath && *pszPath)
3044 {
3045 rc = pIMount->pfnMount (pIMount, pszPath, strcmp (pszDevice, "i82078") ? "MediaISO" : "RawImage");
3046 if (VBOX_FAILURE (rc))
3047 eState = DriveState_NotMounted;
3048 }
3049 break;
3050 }
3051
3052 default:
3053 AssertMsgFailed (("Invalid eState: %d\n", eState));
3054 break;
3055
3056#undef RC_CHECK
3057 }
3058
3059 if (VBOX_FAILURE (rc) && VBOX_SUCCESS (rcRet))
3060 rcRet = rc;
3061
3062 *peState = eState;
3063 }
3064 while (0);
3065
3066 /*
3067 * Resume the VM if necessary.
3068 */
3069 if (fResume)
3070 {
3071 LogFlowFunc (("Resuming the VM...\n"));
3072 /* disable the callback to prevent Console-level state change */
3073 pThis->mVMStateChangeCallbackDisabled = true;
3074 rc = VMR3Resume (pVM);
3075 pThis->mVMStateChangeCallbackDisabled = false;
3076 AssertRC (rc);
3077 if (VBOX_FAILURE (rc))
3078 {
3079 /* too bad, we failed. try to sync the console state with the VMM state */
3080 vmstateChangeCallback (pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
3081 }
3082 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
3083 // error (if any) will be hidden from the caller. For proper reporting
3084 // of such multiple errors to the caller we need to enhance the
3085 // IVurtualBoxError interface. For now, give the first error the higher
3086 // priority.
3087 if (VBOX_SUCCESS (rcRet))
3088 rcRet = rc;
3089 }
3090
3091 LogFlowFunc (("Returning %Vrc\n", rcRet));
3092 return rcRet;
3093}
3094
3095
3096/**
3097 * Called by IInternalSessionControl::OnNetworkAdapterChange().
3098 *
3099 * @note Locks this object for writing.
3100 */
3101HRESULT Console::onNetworkAdapterChange (INetworkAdapter *aNetworkAdapter)
3102{
3103 LogFlowThisFunc (("\n"));
3104
3105 AutoCaller autoCaller (this);
3106 AssertComRCReturnRC (autoCaller.rc());
3107
3108 AutoWriteLock alock (this);
3109
3110 /* Don't do anything if the VM isn't running */
3111 if (!mpVM)
3112 return S_OK;
3113
3114 /* protect mpVM */
3115 AutoVMCaller autoVMCaller (this);
3116 CheckComRCReturnRC (autoVMCaller.rc());
3117
3118 /* Get the properties we need from the adapter */
3119 BOOL fCableConnected;
3120 HRESULT rc = aNetworkAdapter->COMGETTER(CableConnected) (&fCableConnected);
3121 AssertComRC(rc);
3122 if (SUCCEEDED(rc))
3123 {
3124 ULONG ulInstance;
3125 rc = aNetworkAdapter->COMGETTER(Slot) (&ulInstance);
3126 AssertComRC (rc);
3127 if (SUCCEEDED (rc))
3128 {
3129 /*
3130 * Find the pcnet instance, get the config interface and update
3131 * the link state.
3132 */
3133 PPDMIBASE pBase;
3134 const char *cszAdapterName = "pcnet";
3135#ifdef VBOX_WITH_E1000
3136 /*
3137 * Perharps it would be much wiser to wrap both 'pcnet' and 'e1000'
3138 * into generic 'net' device.
3139 */
3140 NetworkAdapterType_T adapterType;
3141 rc = aNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
3142 AssertComRC(rc);
3143 if (adapterType == NetworkAdapterType_I82540EM ||
3144 adapterType == NetworkAdapterType_I82543GC)
3145 cszAdapterName = "e1000";
3146#endif
3147 int vrc = PDMR3QueryDeviceLun (mpVM, cszAdapterName,
3148 (unsigned) ulInstance, 0, &pBase);
3149 ComAssertRC (vrc);
3150 if (VBOX_SUCCESS (vrc))
3151 {
3152 Assert(pBase);
3153 PPDMINETWORKCONFIG pINetCfg = (PPDMINETWORKCONFIG) pBase->
3154 pfnQueryInterface(pBase, PDMINTERFACE_NETWORK_CONFIG);
3155 if (pINetCfg)
3156 {
3157 Log (("Console::onNetworkAdapterChange: setting link state to %d\n",
3158 fCableConnected));
3159 vrc = pINetCfg->pfnSetLinkState (pINetCfg,
3160 fCableConnected ? PDMNETWORKLINKSTATE_UP
3161 : PDMNETWORKLINKSTATE_DOWN);
3162 ComAssertRC (vrc);
3163 }
3164 }
3165
3166 if (VBOX_FAILURE (vrc))
3167 rc = E_FAIL;
3168 }
3169 }
3170
3171 /* notify console callbacks on success */
3172 if (SUCCEEDED (rc))
3173 {
3174 CallbackList::iterator it = mCallbacks.begin();
3175 while (it != mCallbacks.end())
3176 (*it++)->OnNetworkAdapterChange (aNetworkAdapter);
3177 }
3178
3179 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3180 return rc;
3181}
3182
3183/**
3184 * Called by IInternalSessionControl::OnSerialPortChange().
3185 *
3186 * @note Locks this object for writing.
3187 */
3188HRESULT Console::onSerialPortChange (ISerialPort *aSerialPort)
3189{
3190 LogFlowThisFunc (("\n"));
3191
3192 AutoCaller autoCaller (this);
3193 AssertComRCReturnRC (autoCaller.rc());
3194
3195 AutoWriteLock alock (this);
3196
3197 /* Don't do anything if the VM isn't running */
3198 if (!mpVM)
3199 return S_OK;
3200
3201 HRESULT rc = S_OK;
3202
3203 /* protect mpVM */
3204 AutoVMCaller autoVMCaller (this);
3205 CheckComRCReturnRC (autoVMCaller.rc());
3206
3207 /* nothing to do so far */
3208
3209 /* notify console callbacks on success */
3210 if (SUCCEEDED (rc))
3211 {
3212 CallbackList::iterator it = mCallbacks.begin();
3213 while (it != mCallbacks.end())
3214 (*it++)->OnSerialPortChange (aSerialPort);
3215 }
3216
3217 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3218 return rc;
3219}
3220
3221/**
3222 * Called by IInternalSessionControl::OnParallelPortChange().
3223 *
3224 * @note Locks this object for writing.
3225 */
3226HRESULT Console::onParallelPortChange (IParallelPort *aParallelPort)
3227{
3228 LogFlowThisFunc (("\n"));
3229
3230 AutoCaller autoCaller (this);
3231 AssertComRCReturnRC (autoCaller.rc());
3232
3233 AutoWriteLock alock (this);
3234
3235 /* Don't do anything if the VM isn't running */
3236 if (!mpVM)
3237 return S_OK;
3238
3239 HRESULT rc = S_OK;
3240
3241 /* protect mpVM */
3242 AutoVMCaller autoVMCaller (this);
3243 CheckComRCReturnRC (autoVMCaller.rc());
3244
3245 /* nothing to do so far */
3246
3247 /* notify console callbacks on success */
3248 if (SUCCEEDED (rc))
3249 {
3250 CallbackList::iterator it = mCallbacks.begin();
3251 while (it != mCallbacks.end())
3252 (*it++)->OnParallelPortChange (aParallelPort);
3253 }
3254
3255 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3256 return rc;
3257}
3258
3259/**
3260 * Called by IInternalSessionControl::OnVRDPServerChange().
3261 *
3262 * @note Locks this object for writing.
3263 */
3264HRESULT Console::onVRDPServerChange()
3265{
3266 AutoCaller autoCaller (this);
3267 AssertComRCReturnRC (autoCaller.rc());
3268
3269 AutoWriteLock alock (this);
3270
3271 HRESULT rc = S_OK;
3272
3273 if (mVRDPServer && mMachineState == MachineState_Running)
3274 {
3275 BOOL vrdpEnabled = FALSE;
3276
3277 rc = mVRDPServer->COMGETTER(Enabled) (&vrdpEnabled);
3278 ComAssertComRCRetRC (rc);
3279
3280 if (vrdpEnabled)
3281 {
3282 // If there was no VRDP server started the 'stop' will do nothing.
3283 // However if a server was started and this notification was called,
3284 // we have to restart the server.
3285 mConsoleVRDPServer->Stop ();
3286
3287 if (VBOX_FAILURE(mConsoleVRDPServer->Launch ()))
3288 {
3289 rc = E_FAIL;
3290 }
3291 else
3292 {
3293 mConsoleVRDPServer->EnableConnections ();
3294 }
3295 }
3296 else
3297 {
3298 mConsoleVRDPServer->Stop ();
3299 }
3300 }
3301
3302 /* notify console callbacks on success */
3303 if (SUCCEEDED (rc))
3304 {
3305 CallbackList::iterator it = mCallbacks.begin();
3306 while (it != mCallbacks.end())
3307 (*it++)->OnVRDPServerChange();
3308 }
3309
3310 return rc;
3311}
3312
3313/**
3314 * Called by IInternalSessionControl::OnUSBControllerChange().
3315 *
3316 * @note Locks this object for writing.
3317 */
3318HRESULT Console::onUSBControllerChange()
3319{
3320 LogFlowThisFunc (("\n"));
3321
3322 AutoCaller autoCaller (this);
3323 AssertComRCReturnRC (autoCaller.rc());
3324
3325 AutoWriteLock alock (this);
3326
3327 /* Ignore if no VM is running yet. */
3328 if (!mpVM)
3329 return S_OK;
3330
3331 HRESULT rc = S_OK;
3332
3333/// @todo (dmik)
3334// check for the Enabled state and disable virtual USB controller??
3335// Anyway, if we want to query the machine's USB Controller we need to cache
3336// it to to mUSBController in #init() (as it is done with mDVDDrive).
3337//
3338// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
3339//
3340// /* protect mpVM */
3341// AutoVMCaller autoVMCaller (this);
3342// CheckComRCReturnRC (autoVMCaller.rc());
3343
3344 /* notify console callbacks on success */
3345 if (SUCCEEDED (rc))
3346 {
3347 CallbackList::iterator it = mCallbacks.begin();
3348 while (it != mCallbacks.end())
3349 (*it++)->OnUSBControllerChange();
3350 }
3351
3352 return rc;
3353}
3354
3355/**
3356 * Called by IInternalSessionControl::OnSharedFolderChange().
3357 *
3358 * @note Locks this object for writing.
3359 */
3360HRESULT Console::onSharedFolderChange (BOOL aGlobal)
3361{
3362 LogFlowThisFunc (("aGlobal=%RTbool\n", aGlobal));
3363
3364 AutoCaller autoCaller (this);
3365 AssertComRCReturnRC (autoCaller.rc());
3366
3367 AutoWriteLock alock (this);
3368
3369 HRESULT rc = fetchSharedFolders (aGlobal);
3370
3371 /* notify console callbacks on success */
3372 if (SUCCEEDED (rc))
3373 {
3374 CallbackList::iterator it = mCallbacks.begin();
3375 while (it != mCallbacks.end())
3376 (*it++)->OnSharedFolderChange (aGlobal ? (Scope_T) Scope_Global
3377 : (Scope_T) Scope_Machine);
3378 }
3379
3380 return rc;
3381}
3382
3383/**
3384 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
3385 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
3386 * returns TRUE for a given remote USB device.
3387 *
3388 * @return S_OK if the device was attached to the VM.
3389 * @return failure if not attached.
3390 *
3391 * @param aDevice
3392 * The device in question.
3393 * @param aMaskedIfs
3394 * The interfaces to hide from the guest.
3395 *
3396 * @note Locks this object for writing.
3397 */
3398HRESULT Console::onUSBDeviceAttach (IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
3399{
3400#ifdef VBOX_WITH_USB
3401 LogFlowThisFunc (("aDevice=%p aError=%p\n", aDevice, aError));
3402
3403 AutoCaller autoCaller (this);
3404 ComAssertComRCRetRC (autoCaller.rc());
3405
3406 AutoWriteLock alock (this);
3407
3408 /* protect mpVM (we don't need error info, since it's a callback) */
3409 AutoVMCallerQuiet autoVMCaller (this);
3410 if (FAILED (autoVMCaller.rc()))
3411 {
3412 /* The VM may be no more operational when this message arrives
3413 * (e.g. it may be Saving or Stopping or just PoweredOff) --
3414 * autoVMCaller.rc() will return a failure in this case. */
3415 LogFlowThisFunc (("Attach request ignored (mMachineState=%d).\n",
3416 mMachineState));
3417 return autoVMCaller.rc();
3418 }
3419
3420 if (aError != NULL)
3421 {
3422 /* notify callbacks about the error */
3423 onUSBDeviceStateChange (aDevice, true /* aAttached */, aError);
3424 return S_OK;
3425 }
3426
3427 /* Don't proceed unless there's at least one USB hub. */
3428 if (!PDMR3USBHasHub (mpVM))
3429 {
3430 LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
3431 return E_FAIL;
3432 }
3433
3434 HRESULT rc = attachUSBDevice (aDevice, aMaskedIfs);
3435 if (FAILED (rc))
3436 {
3437 /* take the current error info */
3438 com::ErrorInfoKeeper eik;
3439 /* the error must be a VirtualBoxErrorInfo instance */
3440 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3441 Assert (!error.isNull());
3442 if (!error.isNull())
3443 {
3444 /* notify callbacks about the error */
3445 onUSBDeviceStateChange (aDevice, true /* aAttached */, error);
3446 }
3447 }
3448
3449 return rc;
3450
3451#else /* !VBOX_WITH_USB */
3452 return E_FAIL;
3453#endif /* !VBOX_WITH_USB */
3454}
3455
3456/**
3457 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
3458 * processRemoteUSBDevices().
3459 *
3460 * @note Locks this object for writing.
3461 */
3462HRESULT Console::onUSBDeviceDetach (INPTR GUIDPARAM aId,
3463 IVirtualBoxErrorInfo *aError)
3464{
3465#ifdef VBOX_WITH_USB
3466 Guid Uuid (aId);
3467 LogFlowThisFunc (("aId={%Vuuid} aError=%p\n", Uuid.raw(), aError));
3468
3469 AutoCaller autoCaller (this);
3470 AssertComRCReturnRC (autoCaller.rc());
3471
3472 AutoWriteLock alock (this);
3473
3474 /* Find the device. */
3475 ComObjPtr <OUSBDevice> device;
3476 USBDeviceList::iterator it = mUSBDevices.begin();
3477 while (it != mUSBDevices.end())
3478 {
3479 LogFlowThisFunc (("it={%Vuuid}\n", (*it)->id().raw()));
3480 if ((*it)->id() == Uuid)
3481 {
3482 device = *it;
3483 break;
3484 }
3485 ++ it;
3486 }
3487
3488
3489 if (device.isNull())
3490 {
3491 LogFlowThisFunc (("USB device not found.\n"));
3492
3493 /* The VM may be no more operational when this message arrives
3494 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
3495 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
3496 * failure in this case. */
3497
3498 AutoVMCallerQuiet autoVMCaller (this);
3499 if (FAILED (autoVMCaller.rc()))
3500 {
3501 LogFlowThisFunc (("Detach request ignored (mMachineState=%d).\n",
3502 mMachineState));
3503 return autoVMCaller.rc();
3504 }
3505
3506 /* the device must be in the list otherwise */
3507 AssertFailedReturn (E_FAIL);
3508 }
3509
3510 if (aError != NULL)
3511 {
3512 /* notify callback about an error */
3513 onUSBDeviceStateChange (device, false /* aAttached */, aError);
3514 return S_OK;
3515 }
3516
3517 HRESULT rc = detachUSBDevice (it);
3518
3519 if (FAILED (rc))
3520 {
3521 /* take the current error info */
3522 com::ErrorInfoKeeper eik;
3523 /* the error must be a VirtualBoxErrorInfo instance */
3524 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3525 Assert (!error.isNull());
3526 if (!error.isNull())
3527 {
3528 /* notify callbacks about the error */
3529 onUSBDeviceStateChange (device, false /* aAttached */, error);
3530 }
3531 }
3532
3533 return rc;
3534
3535#else /* !VBOX_WITH_USB */
3536 return E_FAIL;
3537#endif /* !VBOX_WITH_USB */
3538}
3539
3540/**
3541 * Gets called by Session::UpdateMachineState()
3542 * (IInternalSessionControl::updateMachineState()).
3543 *
3544 * Must be called only in certain cases (see the implementation).
3545 *
3546 * @note Locks this object for writing.
3547 */
3548HRESULT Console::updateMachineState (MachineState_T aMachineState)
3549{
3550 AutoCaller autoCaller (this);
3551 AssertComRCReturnRC (autoCaller.rc());
3552
3553 AutoWriteLock alock (this);
3554
3555 AssertReturn (mMachineState == MachineState_Saving ||
3556 mMachineState == MachineState_Discarding,
3557 E_FAIL);
3558
3559 return setMachineStateLocally (aMachineState);
3560}
3561
3562/**
3563 * @note Locks this object for writing.
3564 */
3565void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3566 uint32_t xHot, uint32_t yHot,
3567 uint32_t width, uint32_t height,
3568 void *pShape)
3569{
3570#if 0
3571 LogFlowThisFuncEnter();
3572 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3573 "height=%d, shape=%p\n",
3574 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3575#endif
3576
3577 AutoCaller autoCaller (this);
3578 AssertComRCReturnVoid (autoCaller.rc());
3579
3580 /* We need a write lock because we alter the cached callback data */
3581 AutoWriteLock alock (this);
3582
3583 /* Save the callback arguments */
3584 mCallbackData.mpsc.visible = fVisible;
3585 mCallbackData.mpsc.alpha = fAlpha;
3586 mCallbackData.mpsc.xHot = xHot;
3587 mCallbackData.mpsc.yHot = yHot;
3588 mCallbackData.mpsc.width = width;
3589 mCallbackData.mpsc.height = height;
3590
3591 /* start with not valid */
3592 bool wasValid = mCallbackData.mpsc.valid;
3593 mCallbackData.mpsc.valid = false;
3594
3595 if (pShape != NULL)
3596 {
3597 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3598 cb = ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3599 /* try to reuse the old shape buffer if the size is the same */
3600 if (!wasValid)
3601 mCallbackData.mpsc.shape = NULL;
3602 else
3603 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3604 {
3605 RTMemFree (mCallbackData.mpsc.shape);
3606 mCallbackData.mpsc.shape = NULL;
3607 }
3608 if (mCallbackData.mpsc.shape == NULL)
3609 {
3610 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3611 AssertReturnVoid (mCallbackData.mpsc.shape);
3612 }
3613 mCallbackData.mpsc.shapeSize = cb;
3614 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3615 }
3616 else
3617 {
3618 if (wasValid && mCallbackData.mpsc.shape != NULL)
3619 RTMemFree (mCallbackData.mpsc.shape);
3620 mCallbackData.mpsc.shape = NULL;
3621 mCallbackData.mpsc.shapeSize = 0;
3622 }
3623
3624 mCallbackData.mpsc.valid = true;
3625
3626 CallbackList::iterator it = mCallbacks.begin();
3627 while (it != mCallbacks.end())
3628 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3629 width, height, (BYTE *) pShape);
3630
3631#if 0
3632 LogFlowThisFuncLeave();
3633#endif
3634}
3635
3636/**
3637 * @note Locks this object for writing.
3638 */
3639void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3640{
3641 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3642 supportsAbsolute, needsHostCursor));
3643
3644 AutoCaller autoCaller (this);
3645 AssertComRCReturnVoid (autoCaller.rc());
3646
3647 /* We need a write lock because we alter the cached callback data */
3648 AutoWriteLock alock (this);
3649
3650 /* save the callback arguments */
3651 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3652 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3653 mCallbackData.mcc.valid = true;
3654
3655 CallbackList::iterator it = mCallbacks.begin();
3656 while (it != mCallbacks.end())
3657 {
3658 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3659 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3660 }
3661}
3662
3663/**
3664 * @note Locks this object for reading.
3665 */
3666void Console::onStateChange (MachineState_T machineState)
3667{
3668 AutoCaller autoCaller (this);
3669 AssertComRCReturnVoid (autoCaller.rc());
3670
3671 AutoReadLock alock (this);
3672
3673 CallbackList::iterator it = mCallbacks.begin();
3674 while (it != mCallbacks.end())
3675 (*it++)->OnStateChange (machineState);
3676}
3677
3678/**
3679 * @note Locks this object for reading.
3680 */
3681void Console::onAdditionsStateChange()
3682{
3683 AutoCaller autoCaller (this);
3684 AssertComRCReturnVoid (autoCaller.rc());
3685
3686 AutoReadLock alock (this);
3687
3688 CallbackList::iterator it = mCallbacks.begin();
3689 while (it != mCallbacks.end())
3690 (*it++)->OnAdditionsStateChange();
3691}
3692
3693/**
3694 * @note Locks this object for reading.
3695 */
3696void Console::onAdditionsOutdated()
3697{
3698 AutoCaller autoCaller (this);
3699 AssertComRCReturnVoid (autoCaller.rc());
3700
3701 AutoReadLock alock (this);
3702
3703 /** @todo Use the On-Screen Display feature to report the fact.
3704 * The user should be told to install additions that are
3705 * provided with the current VBox build:
3706 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3707 */
3708}
3709
3710/**
3711 * @note Locks this object for writing.
3712 */
3713void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3714{
3715 AutoCaller autoCaller (this);
3716 AssertComRCReturnVoid (autoCaller.rc());
3717
3718 /* We need a write lock because we alter the cached callback data */
3719 AutoWriteLock alock (this);
3720
3721 /* save the callback arguments */
3722 mCallbackData.klc.numLock = fNumLock;
3723 mCallbackData.klc.capsLock = fCapsLock;
3724 mCallbackData.klc.scrollLock = fScrollLock;
3725 mCallbackData.klc.valid = true;
3726
3727 CallbackList::iterator it = mCallbacks.begin();
3728 while (it != mCallbacks.end())
3729 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3730}
3731
3732/**
3733 * @note Locks this object for reading.
3734 */
3735void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
3736 IVirtualBoxErrorInfo *aError)
3737{
3738 AutoCaller autoCaller (this);
3739 AssertComRCReturnVoid (autoCaller.rc());
3740
3741 AutoReadLock alock (this);
3742
3743 CallbackList::iterator it = mCallbacks.begin();
3744 while (it != mCallbacks.end())
3745 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
3746}
3747
3748/**
3749 * @note Locks this object for reading.
3750 */
3751void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3752{
3753 AutoCaller autoCaller (this);
3754 AssertComRCReturnVoid (autoCaller.rc());
3755
3756 AutoReadLock alock (this);
3757
3758 CallbackList::iterator it = mCallbacks.begin();
3759 while (it != mCallbacks.end())
3760 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3761}
3762
3763/**
3764 * @note Locks this object for reading.
3765 */
3766HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
3767{
3768 AssertReturn (aCanShow, E_POINTER);
3769 AssertReturn (aWinId, E_POINTER);
3770
3771 *aCanShow = FALSE;
3772 *aWinId = 0;
3773
3774 AutoCaller autoCaller (this);
3775 AssertComRCReturnRC (autoCaller.rc());
3776
3777 AutoReadLock alock (this);
3778
3779 HRESULT rc = S_OK;
3780 CallbackList::iterator it = mCallbacks.begin();
3781
3782 if (aCheck)
3783 {
3784 while (it != mCallbacks.end())
3785 {
3786 BOOL canShow = FALSE;
3787 rc = (*it++)->OnCanShowWindow (&canShow);
3788 AssertComRC (rc);
3789 if (FAILED (rc) || !canShow)
3790 return rc;
3791 }
3792 *aCanShow = TRUE;
3793 }
3794 else
3795 {
3796 while (it != mCallbacks.end())
3797 {
3798 ULONG64 winId = 0;
3799 rc = (*it++)->OnShowWindow (&winId);
3800 AssertComRC (rc);
3801 if (FAILED (rc))
3802 return rc;
3803 /* only one callback may return non-null winId */
3804 Assert (*aWinId == 0 || winId == 0);
3805 if (*aWinId == 0)
3806 *aWinId = winId;
3807 }
3808 }
3809
3810 return S_OK;
3811}
3812
3813// private methods
3814////////////////////////////////////////////////////////////////////////////////
3815
3816/**
3817 * Increases the usage counter of the mpVM pointer. Guarantees that
3818 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
3819 * is called.
3820 *
3821 * If this method returns a failure, the caller is not allowed to use mpVM
3822 * and may return the failed result code to the upper level. This method sets
3823 * the extended error info on failure if \a aQuiet is false.
3824 *
3825 * Setting \a aQuiet to true is useful for methods that don't want to return
3826 * the failed result code to the caller when this method fails (e.g. need to
3827 * silently check for the mpVM avaliability).
3828 *
3829 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
3830 * returned instead of asserting. Having it false is intended as a sanity check
3831 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
3832 *
3833 * @param aQuiet true to suppress setting error info
3834 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
3835 * (otherwise this method will assert if mpVM is NULL)
3836 *
3837 * @note Locks this object for writing.
3838 */
3839HRESULT Console::addVMCaller (bool aQuiet /* = false */,
3840 bool aAllowNullVM /* = false */)
3841{
3842 AutoCaller autoCaller (this);
3843 AssertComRCReturnRC (autoCaller.rc());
3844
3845 AutoWriteLock alock (this);
3846
3847 if (mVMDestroying)
3848 {
3849 /* powerDown() is waiting for all callers to finish */
3850 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3851 tr ("Virtual machine is being powered down"));
3852 }
3853
3854 if (mpVM == NULL)
3855 {
3856 Assert (aAllowNullVM == true);
3857
3858 /* The machine is not powered up */
3859 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3860 tr ("Virtual machine is not powered up"));
3861 }
3862
3863 ++ mVMCallers;
3864
3865 return S_OK;
3866}
3867
3868/**
3869 * Decreases the usage counter of the mpVM pointer. Must always complete
3870 * the addVMCaller() call after the mpVM pointer is no more necessary.
3871 *
3872 * @note Locks this object for writing.
3873 */
3874void Console::releaseVMCaller()
3875{
3876 AutoCaller autoCaller (this);
3877 AssertComRCReturnVoid (autoCaller.rc());
3878
3879 AutoWriteLock alock (this);
3880
3881 AssertReturnVoid (mpVM != NULL);
3882
3883 Assert (mVMCallers > 0);
3884 -- mVMCallers;
3885
3886 if (mVMCallers == 0 && mVMDestroying)
3887 {
3888 /* inform powerDown() there are no more callers */
3889 RTSemEventSignal (mVMZeroCallersSem);
3890 }
3891}
3892
3893/**
3894 * Initialize the release logging facility. In case something
3895 * goes wrong, there will be no release logging. Maybe in the future
3896 * we can add some logic to use different file names in this case.
3897 * Note that the logic must be in sync with Machine::DeleteSettings().
3898 */
3899HRESULT Console::consoleInitReleaseLog (const ComPtr <IMachine> aMachine)
3900{
3901 HRESULT hrc = S_OK;
3902
3903 Bstr logFolder;
3904 hrc = aMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
3905 CheckComRCReturnRC (hrc);
3906
3907 Utf8Str logDir = logFolder;
3908
3909 /* make sure the Logs folder exists */
3910 Assert (!logDir.isEmpty());
3911 if (!RTDirExists (logDir))
3912 RTDirCreateFullPath (logDir, 0777);
3913
3914 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
3915 logDir.raw(), RTPATH_DELIMITER);
3916 Utf8Str pngFile = Utf8StrFmt ("%s%cVBox.png",
3917 logDir.raw(), RTPATH_DELIMITER);
3918
3919 /*
3920 * Age the old log files
3921 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
3922 * Overwrite target files in case they exist.
3923 */
3924 ComPtr<IVirtualBox> virtualBox;
3925 aMachine->COMGETTER(Parent)(virtualBox.asOutParam());
3926 ComPtr <ISystemProperties> systemProperties;
3927 virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
3928 ULONG uLogHistoryCount = 3;
3929 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
3930 if (uLogHistoryCount)
3931 {
3932 for (int i = uLogHistoryCount-1; i >= 0; i--)
3933 {
3934 Utf8Str *files[] = { &logFile, &pngFile };
3935 Utf8Str oldName, newName;
3936
3937 for (unsigned int j = 0; j < ELEMENTS (files); ++ j)
3938 {
3939 if (i > 0)
3940 oldName = Utf8StrFmt ("%s.%d", files [j]->raw(), i);
3941 else
3942 oldName = *files [j];
3943 newName = Utf8StrFmt ("%s.%d", files [j]->raw(), i + 1);
3944 /* If the old file doesn't exist, delete the new file (if it
3945 * exists) to provide correct rotation even if the sequence is
3946 * broken */
3947 if ( RTFileRename (oldName, newName, RTFILEMOVE_FLAGS_REPLACE)
3948 == VERR_FILE_NOT_FOUND)
3949 RTFileDelete (newName);
3950 }
3951 }
3952 }
3953
3954 PRTLOGGER loggerRelease;
3955 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
3956 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
3957#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
3958 fFlags |= RTLOGFLAGS_USECRLF;
3959#endif
3960 char szError[RTPATH_MAX + 128] = "";
3961 int vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
3962 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
3963 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
3964 if (RT_SUCCESS(vrc))
3965 {
3966 /* some introductory information */
3967 RTTIMESPEC timeSpec;
3968 char nowUct[64];
3969 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
3970 RTLogRelLogger(loggerRelease, 0, ~0U,
3971 "VirtualBox %s r%d %s (%s %s) release log\n"
3972 "Log opened %s\n",
3973 VBOX_VERSION_STRING, VBoxSVNRev (), VBOX_BUILD_TARGET,
3974 __DATE__, __TIME__, nowUct);
3975
3976 /* register this logger as the release logger */
3977 RTLogRelSetDefaultInstance(loggerRelease);
3978 hrc = S_OK;
3979 }
3980 else
3981 hrc = setError (E_FAIL,
3982 tr ("Failed to open release log (%s, %Rrc)"), szError, vrc);
3983
3984 return hrc;
3985}
3986
3987
3988/**
3989 * Internal power off worker routine.
3990 *
3991 * This method may be called only at certain places with the folliwing meaning
3992 * as shown below:
3993 *
3994 * - if the machine state is either Running or Paused, a normal
3995 * Console-initiated powerdown takes place (e.g. PowerDown());
3996 * - if the machine state is Saving, saveStateThread() has successfully
3997 * done its job;
3998 * - if the machine state is Starting or Restoring, powerUpThread() has
3999 * failed to start/load the VM;
4000 * - if the machine state is Stopping, the VM has powered itself off
4001 * (i.e. not as a result of the powerDown() call).
4002 *
4003 * Calling it in situations other than the above will cause unexpected
4004 * behavior.
4005 *
4006 * Note that this method should be the only one that destroys mpVM and sets
4007 * it to NULL.
4008 *
4009 * @note Locks this object for writing.
4010 *
4011 * @note Never call this method from a thread that called addVMCaller() or
4012 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
4013 * release(). Otherwise it will deadlock.
4014 */
4015HRESULT Console::powerDown()
4016{
4017 LogFlowThisFuncEnter();
4018
4019 AutoCaller autoCaller (this);
4020 AssertComRCReturnRC (autoCaller.rc());
4021
4022 AutoWriteLock alock (this);
4023
4024 /* sanity */
4025 AssertReturn (mVMDestroying == false, E_FAIL);
4026
4027 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
4028 "(mMachineState=%d, InUninit=%d)\n",
4029 mMachineState, autoCaller.state() == InUninit));
4030
4031 /*
4032 * Stop the VRDP server to prevent new clients connection while VM is being powered off.
4033 */
4034 if (mConsoleVRDPServer)
4035 {
4036 LogFlowThisFunc (("Stopping VRDP server...\n"));
4037
4038 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
4039 alock.leave();
4040
4041 mConsoleVRDPServer->Stop();
4042
4043 alock.enter();
4044 }
4045
4046
4047#ifdef VBOX_HGCM
4048 /*
4049 * Shutdown HGCM services before stopping the guest, because they might need a cleanup.
4050 */
4051 if (mVMMDev)
4052 {
4053 LogFlowThisFunc (("Shutdown HGCM...\n"));
4054
4055 /* Leave the lock. */
4056 alock.leave();
4057
4058 mVMMDev->hgcmShutdown ();
4059
4060 alock.enter();
4061 }
4062#endif /* VBOX_HGCM */
4063
4064 /* First, wait for all mpVM callers to finish their work if necessary */
4065 if (mVMCallers > 0)
4066 {
4067 /* go to the destroying state to prevent from adding new callers */
4068 mVMDestroying = true;
4069
4070 /* lazy creation */
4071 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
4072 RTSemEventCreate (&mVMZeroCallersSem);
4073
4074 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
4075 mVMCallers));
4076
4077 alock.leave();
4078
4079 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
4080
4081 alock.enter();
4082 }
4083
4084 AssertReturn (mpVM, E_FAIL);
4085
4086 AssertMsg (mMachineState == MachineState_Running ||
4087 mMachineState == MachineState_Paused ||
4088 mMachineState == MachineState_Stuck ||
4089 mMachineState == MachineState_Saving ||
4090 mMachineState == MachineState_Starting ||
4091 mMachineState == MachineState_Restoring ||
4092 mMachineState == MachineState_Stopping,
4093 ("Invalid machine state: %d\n", mMachineState));
4094
4095 HRESULT rc = S_OK;
4096 int vrc = VINF_SUCCESS;
4097
4098 /*
4099 * Power off the VM if not already done that. In case of Stopping, the VM
4100 * has powered itself off and notified Console in vmstateChangeCallback().
4101 * In case of Starting or Restoring, powerUpThread() is calling us on
4102 * failure, so the VM is already off at that point.
4103 */
4104 if (mMachineState != MachineState_Stopping &&
4105 mMachineState != MachineState_Starting &&
4106 mMachineState != MachineState_Restoring)
4107 {
4108 /*
4109 * don't go from Saving to Stopping, vmstateChangeCallback needs it
4110 * to set the state to Saved on VMSTATE_TERMINATED.
4111 */
4112 if (mMachineState != MachineState_Saving)
4113 setMachineState (MachineState_Stopping);
4114
4115 LogFlowThisFunc (("Powering off the VM...\n"));
4116
4117 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
4118 alock.leave();
4119
4120 vrc = VMR3PowerOff (mpVM);
4121 /*
4122 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
4123 * VM-(guest-)initiated power off happened in parallel a ms before
4124 * this call. So far, we let this error pop up on the user's side.
4125 */
4126
4127 alock.enter();
4128 }
4129
4130 LogFlowThisFunc (("Ready for VM destruction\n"));
4131
4132 /*
4133 * If we are called from Console::uninit(), then try to destroy the VM
4134 * even on failure (this will most likely fail too, but what to do?..)
4135 */
4136 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
4137 {
4138 /* If the machine has an USB comtroller, release all USB devices
4139 * (symmetric to the code in captureUSBDevices()) */
4140 bool fHasUSBController = false;
4141 {
4142 PPDMIBASE pBase;
4143 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4144 if (VBOX_SUCCESS (vrc))
4145 {
4146 fHasUSBController = true;
4147 detachAllUSBDevices (false /* aDone */);
4148 }
4149 }
4150
4151 /*
4152 * Now we've got to destroy the VM as well. (mpVM is not valid
4153 * beyond this point). We leave the lock before calling VMR3Destroy()
4154 * because it will result into calling destructors of drivers
4155 * associated with Console children which may in turn try to lock
4156 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
4157 * here because mVMDestroying is set which should prevent any activity.
4158 */
4159
4160 /*
4161 * Set mpVM to NULL early just in case if some old code is not using
4162 * addVMCaller()/releaseVMCaller().
4163 */
4164 PVM pVM = mpVM;
4165 mpVM = NULL;
4166
4167 LogFlowThisFunc (("Destroying the VM...\n"));
4168
4169 alock.leave();
4170
4171 vrc = VMR3Destroy (pVM);
4172
4173 /* take the lock again */
4174 alock.enter();
4175
4176 if (VBOX_SUCCESS (vrc))
4177 {
4178 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
4179 mMachineState));
4180 /*
4181 * Note: the Console-level machine state change happens on the
4182 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
4183 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
4184 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
4185 * occured yet. This is okay, because mMachineState is already
4186 * Stopping in this case, so any other attempt to call PowerDown()
4187 * will be rejected.
4188 */
4189 }
4190 else
4191 {
4192 /* bad bad bad, but what to do? */
4193 mpVM = pVM;
4194 rc = setError (E_FAIL,
4195 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
4196 }
4197
4198 /*
4199 * Complete the detaching of the USB devices.
4200 */
4201 if (fHasUSBController)
4202 detachAllUSBDevices (true /* aDone */);
4203 }
4204 else
4205 {
4206 rc = setError (E_FAIL,
4207 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
4208 }
4209
4210 /*
4211 * Finished with destruction. Note that if something impossible happened
4212 * and we've failed to destroy the VM, mVMDestroying will remain false and
4213 * mMachineState will be something like Stopping, so most Console methods
4214 * will return an error to the caller.
4215 */
4216 if (mpVM == NULL)
4217 mVMDestroying = false;
4218
4219 if (SUCCEEDED (rc))
4220 {
4221 /* uninit dynamically allocated members of mCallbackData */
4222 if (mCallbackData.mpsc.valid)
4223 {
4224 if (mCallbackData.mpsc.shape != NULL)
4225 RTMemFree (mCallbackData.mpsc.shape);
4226 }
4227 memset (&mCallbackData, 0, sizeof (mCallbackData));
4228 }
4229
4230 LogFlowThisFuncLeave();
4231 return rc;
4232}
4233
4234/**
4235 * @note Locks this object for writing.
4236 */
4237HRESULT Console::setMachineState (MachineState_T aMachineState,
4238 bool aUpdateServer /* = true */)
4239{
4240 AutoCaller autoCaller (this);
4241 AssertComRCReturnRC (autoCaller.rc());
4242
4243 AutoWriteLock alock (this);
4244
4245 HRESULT rc = S_OK;
4246
4247 if (mMachineState != aMachineState)
4248 {
4249 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4250 mMachineState = aMachineState;
4251
4252 /// @todo (dmik)
4253 // possibly, we need to redo onStateChange() using the dedicated
4254 // Event thread, like it is done in VirtualBox. This will make it
4255 // much safer (no deadlocks possible if someone tries to use the
4256 // console from the callback), however, listeners will lose the
4257 // ability to synchronously react to state changes (is it really
4258 // necessary??)
4259 LogFlowThisFunc (("Doing onStateChange()...\n"));
4260 onStateChange (aMachineState);
4261 LogFlowThisFunc (("Done onStateChange()\n"));
4262
4263 if (aUpdateServer)
4264 {
4265 /*
4266 * Server notification MUST be done from under the lock; otherwise
4267 * the machine state here and on the server might go out of sync, that
4268 * can lead to various unexpected results (like the machine state being
4269 * >= MachineState_Running on the server, while the session state is
4270 * already SessionState_Closed at the same time there).
4271 *
4272 * Cross-lock conditions should be carefully watched out: calling
4273 * UpdateState we will require Machine and SessionMachine locks
4274 * (remember that here we're holding the Console lock here, and
4275 * also all locks that have been entered by the thread before calling
4276 * this method).
4277 */
4278 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4279 rc = mControl->UpdateState (aMachineState);
4280 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4281 }
4282 }
4283
4284 return rc;
4285}
4286
4287/**
4288 * Searches for a shared folder with the given logical name
4289 * in the collection of shared folders.
4290 *
4291 * @param aName logical name of the shared folder
4292 * @param aSharedFolder where to return the found object
4293 * @param aSetError whether to set the error info if the folder is
4294 * not found
4295 * @return
4296 * S_OK when found or E_INVALIDARG when not found
4297 *
4298 * @note The caller must lock this object for writing.
4299 */
4300HRESULT Console::findSharedFolder (const BSTR aName,
4301 ComObjPtr <SharedFolder> &aSharedFolder,
4302 bool aSetError /* = false */)
4303{
4304 /* sanity check */
4305 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4306
4307 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4308 if (it != mSharedFolders.end())
4309 {
4310 aSharedFolder = it->second;
4311 return S_OK;
4312 }
4313
4314 if (aSetError)
4315 setError (E_INVALIDARG,
4316 tr ("Could not find a shared folder named '%ls'."), aName);
4317
4318 return E_INVALIDARG;
4319}
4320
4321/**
4322 * Fetches the list of global or machine shared folders from the server.
4323 *
4324 * @param aGlobal true to fetch global folders.
4325 *
4326 * @note The caller must lock this object for writing.
4327 */
4328HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4329{
4330 /* sanity check */
4331 AssertReturn (AutoCaller (this).state() == InInit ||
4332 isWriteLockOnCurrentThread(), E_FAIL);
4333
4334 /* protect mpVM (if not NULL) */
4335 AutoVMCallerQuietWeak autoVMCaller (this);
4336
4337 HRESULT rc = S_OK;
4338
4339 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4340
4341 if (aGlobal)
4342 {
4343 /// @todo grab & process global folders when they are done
4344 }
4345 else
4346 {
4347 SharedFolderDataMap oldFolders;
4348 if (online)
4349 oldFolders = mMachineSharedFolders;
4350
4351 mMachineSharedFolders.clear();
4352
4353 ComPtr <ISharedFolderCollection> coll;
4354 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
4355 AssertComRCReturnRC (rc);
4356
4357 ComPtr <ISharedFolderEnumerator> en;
4358 rc = coll->Enumerate (en.asOutParam());
4359 AssertComRCReturnRC (rc);
4360
4361 BOOL hasMore = FALSE;
4362 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
4363 {
4364 ComPtr <ISharedFolder> folder;
4365 rc = en->GetNext (folder.asOutParam());
4366 CheckComRCBreakRC (rc);
4367
4368 Bstr name;
4369 Bstr hostPath;
4370 BOOL writable;
4371
4372 rc = folder->COMGETTER(Name) (name.asOutParam());
4373 CheckComRCBreakRC (rc);
4374 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
4375 CheckComRCBreakRC (rc);
4376 rc = folder->COMGETTER(Writable) (&writable);
4377
4378 mMachineSharedFolders.insert (std::make_pair (name, SharedFolderData (hostPath, writable)));
4379
4380 /* send changes to HGCM if the VM is running */
4381 /// @todo report errors as runtime warnings through VMSetError
4382 if (online)
4383 {
4384 SharedFolderDataMap::iterator it = oldFolders.find (name);
4385 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
4386 {
4387 /* a new machine folder is added or
4388 * the existing machine folder is changed */
4389 if (mSharedFolders.find (name) != mSharedFolders.end())
4390 ; /* the console folder exists, nothing to do */
4391 else
4392 {
4393 /* remove the old machhine folder (when changed)
4394 * or the global folder if any (when new) */
4395 if (it != oldFolders.end() ||
4396 mGlobalSharedFolders.find (name) !=
4397 mGlobalSharedFolders.end())
4398 rc = removeSharedFolder (name);
4399 /* create the new machine folder */
4400 rc = createSharedFolder (name, SharedFolderData (hostPath, writable));
4401 }
4402 }
4403 /* forget the processed (or identical) folder */
4404 if (it != oldFolders.end())
4405 oldFolders.erase (it);
4406
4407 rc = S_OK;
4408 }
4409 }
4410
4411 AssertComRCReturnRC (rc);
4412
4413 /* process outdated (removed) folders */
4414 /// @todo report errors as runtime warnings through VMSetError
4415 if (online)
4416 {
4417 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
4418 it != oldFolders.end(); ++ it)
4419 {
4420 if (mSharedFolders.find (it->first) != mSharedFolders.end())
4421 ; /* the console folder exists, nothing to do */
4422 else
4423 {
4424 /* remove the outdated machine folder */
4425 rc = removeSharedFolder (it->first);
4426 /* create the global folder if there is any */
4427 SharedFolderDataMap::const_iterator git =
4428 mGlobalSharedFolders.find (it->first);
4429 if (git != mGlobalSharedFolders.end())
4430 rc = createSharedFolder (git->first, git->second);
4431 }
4432 }
4433
4434 rc = S_OK;
4435 }
4436 }
4437
4438 return rc;
4439}
4440
4441/**
4442 * Searches for a shared folder with the given name in the list of machine
4443 * shared folders and then in the list of the global shared folders.
4444 *
4445 * @param aName Name of the folder to search for.
4446 * @param aIt Where to store the pointer to the found folder.
4447 * @return @c true if the folder was found and @c false otherwise.
4448 *
4449 * @note The caller must lock this object for reading.
4450 */
4451bool Console::findOtherSharedFolder (INPTR BSTR aName,
4452 SharedFolderDataMap::const_iterator &aIt)
4453{
4454 /* sanity check */
4455 AssertReturn (isWriteLockOnCurrentThread(), false);
4456
4457 /* first, search machine folders */
4458 aIt = mMachineSharedFolders.find (aName);
4459 if (aIt != mMachineSharedFolders.end())
4460 return true;
4461
4462 /* second, search machine folders */
4463 aIt = mGlobalSharedFolders.find (aName);
4464 if (aIt != mGlobalSharedFolders.end())
4465 return true;
4466
4467 return false;
4468}
4469
4470/**
4471 * Calls the HGCM service to add a shared folder definition.
4472 *
4473 * @param aName Shared folder name.
4474 * @param aHostPath Shared folder path.
4475 *
4476 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4477 * @note Doesn't lock anything.
4478 */
4479HRESULT Console::createSharedFolder (INPTR BSTR aName, SharedFolderData aData)
4480{
4481 ComAssertRet (aName && *aName, E_FAIL);
4482 ComAssertRet (aData.mHostPath, E_FAIL);
4483
4484 /* sanity checks */
4485 AssertReturn (mpVM, E_FAIL);
4486 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4487
4488 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
4489 SHFLSTRING *pFolderName, *pMapName;
4490 size_t cbString;
4491
4492 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
4493
4494 cbString = (RTUtf16Len (aData.mHostPath) + 1) * sizeof (RTUTF16);
4495 if (cbString >= UINT16_MAX)
4496 return setError (E_INVALIDARG, tr ("The name is too long"));
4497 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4498 Assert (pFolderName);
4499 memcpy (pFolderName->String.ucs2, aData.mHostPath, cbString);
4500
4501 pFolderName->u16Size = (uint16_t)cbString;
4502 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
4503
4504 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4505 parms[0].u.pointer.addr = pFolderName;
4506 parms[0].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4507
4508 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
4509 if (cbString >= UINT16_MAX)
4510 {
4511 RTMemFree (pFolderName);
4512 return setError (E_INVALIDARG, tr ("The host path is too long"));
4513 }
4514 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
4515 Assert (pMapName);
4516 memcpy (pMapName->String.ucs2, aName, cbString);
4517
4518 pMapName->u16Size = (uint16_t)cbString;
4519 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
4520
4521 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4522 parms[1].u.pointer.addr = pMapName;
4523 parms[1].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4524
4525 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
4526 parms[2].u.uint32 = aData.mWritable;
4527
4528 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4529 SHFL_FN_ADD_MAPPING,
4530 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
4531 RTMemFree (pFolderName);
4532 RTMemFree (pMapName);
4533
4534 if (VBOX_FAILURE (vrc))
4535 return setError (E_FAIL,
4536 tr ("Could not create a shared folder '%ls' "
4537 "mapped to '%ls' (%Vrc)"),
4538 aName, aData.mHostPath.raw(), vrc);
4539
4540 return S_OK;
4541}
4542
4543/**
4544 * Calls the HGCM service to remove the shared folder definition.
4545 *
4546 * @param aName Shared folder name.
4547 *
4548 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4549 * @note Doesn't lock anything.
4550 */
4551HRESULT Console::removeSharedFolder (INPTR BSTR aName)
4552{
4553 ComAssertRet (aName && *aName, E_FAIL);
4554
4555 /* sanity checks */
4556 AssertReturn (mpVM, E_FAIL);
4557 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4558
4559 VBOXHGCMSVCPARM parms;
4560 SHFLSTRING *pMapName;
4561 size_t cbString;
4562
4563 Log (("Removing shared folder '%ls'\n", aName));
4564
4565 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
4566 if (cbString >= UINT16_MAX)
4567 return setError (E_INVALIDARG, tr ("The name is too long"));
4568 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4569 Assert (pMapName);
4570 memcpy (pMapName->String.ucs2, aName, cbString);
4571
4572 pMapName->u16Size = (uint16_t)cbString;
4573 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
4574
4575 parms.type = VBOX_HGCM_SVC_PARM_PTR;
4576 parms.u.pointer.addr = pMapName;
4577 parms.u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4578
4579 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4580 SHFL_FN_REMOVE_MAPPING,
4581 1, &parms);
4582 RTMemFree(pMapName);
4583 if (VBOX_FAILURE (vrc))
4584 return setError (E_FAIL,
4585 tr ("Could not remove the shared folder '%ls' (%Vrc)"),
4586 aName, vrc);
4587
4588 return S_OK;
4589}
4590
4591/**
4592 * VM state callback function. Called by the VMM
4593 * using its state machine states.
4594 *
4595 * Primarily used to handle VM initiated power off, suspend and state saving,
4596 * but also for doing termination completed work (VMSTATE_TERMINATE).
4597 *
4598 * In general this function is called in the context of the EMT.
4599 *
4600 * @param aVM The VM handle.
4601 * @param aState The new state.
4602 * @param aOldState The old state.
4603 * @param aUser The user argument (pointer to the Console object).
4604 *
4605 * @note Locks the Console object for writing.
4606 */
4607DECLCALLBACK(void)
4608Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
4609 void *aUser)
4610{
4611 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
4612 aOldState, aState, aVM));
4613
4614 Console *that = static_cast <Console *> (aUser);
4615 AssertReturnVoid (that);
4616
4617 AutoCaller autoCaller (that);
4618 /*
4619 * Note that we must let this method proceed even if Console::uninit() has
4620 * been already called. In such case this VMSTATE change is a result of:
4621 * 1) powerDown() called from uninit() itself, or
4622 * 2) VM-(guest-)initiated power off.
4623 */
4624 AssertReturnVoid (autoCaller.isOk() ||
4625 autoCaller.state() == InUninit);
4626
4627 switch (aState)
4628 {
4629 /*
4630 * The VM has terminated
4631 */
4632 case VMSTATE_OFF:
4633 {
4634 AutoWriteLock alock (that);
4635
4636 if (that->mVMStateChangeCallbackDisabled)
4637 break;
4638
4639 /*
4640 * Do we still think that it is running? It may happen if this is
4641 * a VM-(guest-)initiated shutdown/poweroff.
4642 */
4643 if (that->mMachineState != MachineState_Stopping &&
4644 that->mMachineState != MachineState_Saving &&
4645 that->mMachineState != MachineState_Restoring)
4646 {
4647 LogFlowFunc (("VM has powered itself off but Console still "
4648 "thinks it is running. Notifying.\n"));
4649
4650 /* prevent powerDown() from calling VMR3PowerOff() again */
4651 that->setMachineState (MachineState_Stopping);
4652
4653 /*
4654 * Setup task object and thread to carry out the operation
4655 * asynchronously (if we call powerDown() right here but there
4656 * is one or more mpVM callers (added with addVMCaller()) we'll
4657 * deadlock.
4658 */
4659 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
4660 /*
4661 * If creating a task is falied, this can currently mean one
4662 * of two: either Console::uninit() has been called just a ms
4663 * before (so a powerDown() call is already on the way), or
4664 * powerDown() itself is being already executed. Just do
4665 * nothing .
4666 */
4667 if (!task->isOk())
4668 {
4669 LogFlowFunc (("Console is already being uninitialized.\n"));
4670 break;
4671 }
4672
4673 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
4674 (void *) task.get(), 0,
4675 RTTHREADTYPE_MAIN_WORKER, 0,
4676 "VMPowerDowm");
4677
4678 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
4679 if (VBOX_FAILURE (vrc))
4680 break;
4681
4682 /* task is now owned by powerDownThread(), so release it */
4683 task.release();
4684 }
4685 break;
4686 }
4687
4688 /*
4689 * The VM has been completely destroyed.
4690 *
4691 * Note: This state change can happen at two points:
4692 * 1) At the end of VMR3Destroy() if it was not called from EMT.
4693 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
4694 * called by EMT.
4695 */
4696 case VMSTATE_TERMINATED:
4697 {
4698 AutoWriteLock alock (that);
4699
4700 if (that->mVMStateChangeCallbackDisabled)
4701 break;
4702
4703 /*
4704 * Terminate host interface networking. If aVM is NULL, we've been
4705 * manually called from powerUpThread() either before calling
4706 * VMR3Create() or after VMR3Create() failed, so no need to touch
4707 * networking.
4708 */
4709 if (aVM)
4710 that->powerDownHostInterfaces();
4711
4712 /*
4713 * From now on the machine is officially powered down or
4714 * remains in the Saved state.
4715 */
4716 switch (that->mMachineState)
4717 {
4718 default:
4719 AssertFailed();
4720 /* fall through */
4721 case MachineState_Stopping:
4722 /* successfully powered down */
4723 that->setMachineState (MachineState_PoweredOff);
4724 break;
4725 case MachineState_Saving:
4726 /*
4727 * successfully saved (note that the machine is already
4728 * in the Saved state on the server due to EndSavingState()
4729 * called from saveStateThread(), so only change the local
4730 * state)
4731 */
4732 that->setMachineStateLocally (MachineState_Saved);
4733 break;
4734 case MachineState_Starting:
4735 /*
4736 * failed to start, but be patient: set back to PoweredOff
4737 * (for similarity with the below)
4738 */
4739 that->setMachineState (MachineState_PoweredOff);
4740 break;
4741 case MachineState_Restoring:
4742 /*
4743 * failed to load the saved state file, but be patient:
4744 * set back to Saved (to preserve the saved state file)
4745 */
4746 that->setMachineState (MachineState_Saved);
4747 break;
4748 }
4749
4750 break;
4751 }
4752
4753 case VMSTATE_SUSPENDED:
4754 {
4755 if (aOldState == VMSTATE_RUNNING)
4756 {
4757 AutoWriteLock alock (that);
4758
4759 if (that->mVMStateChangeCallbackDisabled)
4760 break;
4761
4762 /* Change the machine state from Running to Paused */
4763 Assert (that->mMachineState == MachineState_Running);
4764 that->setMachineState (MachineState_Paused);
4765 }
4766
4767 break;
4768 }
4769
4770 case VMSTATE_RUNNING:
4771 {
4772 if (aOldState == VMSTATE_CREATED ||
4773 aOldState == VMSTATE_SUSPENDED)
4774 {
4775 AutoWriteLock alock (that);
4776
4777 if (that->mVMStateChangeCallbackDisabled)
4778 break;
4779
4780 /*
4781 * Change the machine state from Starting, Restoring or Paused
4782 * to Running
4783 */
4784 Assert ((that->mMachineState == MachineState_Starting &&
4785 aOldState == VMSTATE_CREATED) ||
4786 ((that->mMachineState == MachineState_Restoring ||
4787 that->mMachineState == MachineState_Paused) &&
4788 aOldState == VMSTATE_SUSPENDED));
4789
4790 that->setMachineState (MachineState_Running);
4791 }
4792
4793 break;
4794 }
4795
4796 case VMSTATE_GURU_MEDITATION:
4797 {
4798 AutoWriteLock alock (that);
4799
4800 if (that->mVMStateChangeCallbackDisabled)
4801 break;
4802
4803 /* Guru respects only running VMs */
4804 Assert ((that->mMachineState >= MachineState_Running));
4805
4806 that->setMachineState (MachineState_Stuck);
4807
4808 break;
4809 }
4810
4811 default: /* shut up gcc */
4812 break;
4813 }
4814}
4815
4816#ifdef VBOX_WITH_USB
4817
4818/**
4819 * Sends a request to VMM to attach the given host device.
4820 * After this method succeeds, the attached device will appear in the
4821 * mUSBDevices collection.
4822 *
4823 * @param aHostDevice device to attach
4824 *
4825 * @note Synchronously calls EMT.
4826 * @note Must be called from under this object's lock.
4827 */
4828HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, ULONG aMaskedIfs)
4829{
4830 AssertReturn (aHostDevice, E_FAIL);
4831 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4832
4833 /* still want a lock object because we need to leave it */
4834 AutoWriteLock alock (this);
4835
4836 HRESULT hrc;
4837
4838 /*
4839 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
4840 * method in EMT (using usbAttachCallback()).
4841 */
4842 Bstr BstrAddress;
4843 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
4844 ComAssertComRCRetRC (hrc);
4845
4846 Utf8Str Address (BstrAddress);
4847
4848 Guid Uuid;
4849 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
4850 ComAssertComRCRetRC (hrc);
4851
4852 BOOL fRemote = FALSE;
4853 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
4854 ComAssertComRCRetRC (hrc);
4855
4856 /* protect mpVM */
4857 AutoVMCaller autoVMCaller (this);
4858 CheckComRCReturnRC (autoVMCaller.rc());
4859
4860 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
4861 Address.raw(), Uuid.ptr()));
4862
4863 /* leave the lock before a VMR3* call (EMT will call us back)! */
4864 alock.leave();
4865
4866/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
4867 PVMREQ pReq = NULL;
4868 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4869 (PFNRT) usbAttachCallback, 6, this, aHostDevice, Uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
4870 if (VBOX_SUCCESS (vrc))
4871 vrc = pReq->iStatus;
4872 VMR3ReqFree (pReq);
4873
4874 /* restore the lock */
4875 alock.enter();
4876
4877 /* hrc is S_OK here */
4878
4879 if (VBOX_FAILURE (vrc))
4880 {
4881 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
4882 Address.raw(), Uuid.ptr(), vrc));
4883
4884 switch (vrc)
4885 {
4886 case VERR_VUSB_NO_PORTS:
4887 hrc = setError (E_FAIL,
4888 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
4889 break;
4890 case VERR_VUSB_USBFS_PERMISSION:
4891 hrc = setError (E_FAIL,
4892 tr ("Not permitted to open the USB device, check usbfs options"));
4893 break;
4894 default:
4895 hrc = setError (E_FAIL,
4896 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
4897 break;
4898 }
4899 }
4900
4901 return hrc;
4902}
4903
4904/**
4905 * USB device attach callback used by AttachUSBDevice().
4906 * Note that AttachUSBDevice() doesn't return until this callback is executed,
4907 * so we don't use AutoCaller and don't care about reference counters of
4908 * interface pointers passed in.
4909 *
4910 * @thread EMT
4911 * @note Locks the console object for writing.
4912 */
4913//static
4914DECLCALLBACK(int)
4915Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
4916{
4917 LogFlowFuncEnter();
4918 LogFlowFunc (("that={%p}\n", that));
4919
4920 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
4921
4922 void *pvRemoteBackend = NULL;
4923 if (aRemote)
4924 {
4925 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
4926 Guid guid (*aUuid);
4927
4928 pvRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
4929 if (!pvRemoteBackend)
4930 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
4931 }
4932
4933 USHORT portVersion = 1;
4934 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
4935 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
4936 Assert(portVersion == 1 || portVersion == 2);
4937
4938 int vrc = PDMR3USBCreateProxyDevice (that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
4939 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
4940 if (VBOX_SUCCESS (vrc))
4941 {
4942 /* Create a OUSBDevice and add it to the device list */
4943 ComObjPtr <OUSBDevice> device;
4944 device.createObject();
4945 HRESULT hrc = device->init (aHostDevice);
4946 AssertComRC (hrc);
4947
4948 AutoWriteLock alock (that);
4949 that->mUSBDevices.push_back (device);
4950 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
4951
4952 /* notify callbacks */
4953 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
4954 }
4955
4956 LogFlowFunc (("vrc=%Vrc\n", vrc));
4957 LogFlowFuncLeave();
4958 return vrc;
4959}
4960
4961/**
4962 * Sends a request to VMM to detach the given host device. After this method
4963 * succeeds, the detached device will disappear from the mUSBDevices
4964 * collection.
4965 *
4966 * @param aIt Iterator pointing to the device to detach.
4967 *
4968 * @note Synchronously calls EMT.
4969 * @note Must be called from under this object's lock.
4970 */
4971HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
4972{
4973 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4974
4975 /* still want a lock object because we need to leave it */
4976 AutoWriteLock alock (this);
4977
4978 /* protect mpVM */
4979 AutoVMCaller autoVMCaller (this);
4980 CheckComRCReturnRC (autoVMCaller.rc());
4981
4982 /* if the device is attached, then there must at least one USB hub. */
4983 AssertReturn (PDMR3USBHasHub (mpVM), E_FAIL);
4984
4985 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
4986 (*aIt)->id().raw()));
4987
4988 /* leave the lock before a VMR3* call (EMT will call us back)! */
4989 alock.leave();
4990
4991 PVMREQ pReq;
4992/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
4993 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4994 (PFNRT) usbDetachCallback, 4,
4995 this, &aIt, (*aIt)->id().raw());
4996 if (VBOX_SUCCESS (vrc))
4997 vrc = pReq->iStatus;
4998 VMR3ReqFree (pReq);
4999
5000 ComAssertRCRet (vrc, E_FAIL);
5001
5002 return S_OK;
5003}
5004
5005/**
5006 * USB device detach callback used by DetachUSBDevice().
5007 * Note that DetachUSBDevice() doesn't return until this callback is executed,
5008 * so we don't use AutoCaller and don't care about reference counters of
5009 * interface pointers passed in.
5010 *
5011 * @thread EMT
5012 * @note Locks the console object for writing.
5013 */
5014//static
5015DECLCALLBACK(int)
5016Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
5017{
5018 LogFlowFuncEnter();
5019 LogFlowFunc (("that={%p}\n", that));
5020
5021 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5022
5023 /*
5024 * If that was a remote device, release the backend pointer.
5025 * The pointer was requested in usbAttachCallback.
5026 */
5027 BOOL fRemote = FALSE;
5028
5029 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
5030 ComAssertComRC (hrc2);
5031
5032 if (fRemote)
5033 {
5034 Guid guid (*aUuid);
5035 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
5036 }
5037
5038 int vrc = PDMR3USBDetachDevice (that->mpVM, aUuid);
5039
5040 if (VBOX_SUCCESS (vrc))
5041 {
5042 AutoWriteLock alock (that);
5043
5044 /* Remove the device from the collection */
5045 that->mUSBDevices.erase (*aIt);
5046 LogFlowFunc (("Detached device {%Vuuid}\n", (**aIt)->id().raw()));
5047
5048 /* notify callbacks */
5049 that->onUSBDeviceStateChange (**aIt, false /* aAttached */, NULL);
5050 }
5051
5052 LogFlowFunc (("vrc=%Vrc\n", vrc));
5053 LogFlowFuncLeave();
5054 return vrc;
5055}
5056
5057#endif /* VBOX_WITH_USB */
5058
5059/**
5060 * Call the initialisation script for a dynamic TAP interface.
5061 *
5062 * The initialisation script should create a TAP interface, set it up and write its name to
5063 * standard output followed by a carriage return. Anything further written to standard
5064 * output will be ignored. If it returns a non-zero exit code, or does not write an
5065 * intelligable interface name to standard output, it will be treated as having failed.
5066 * For now, this method only works on Linux.
5067 *
5068 * @returns COM status code
5069 * @param tapDevice string to store the name of the tap device created to
5070 * @param tapSetupApplication the name of the setup script
5071 */
5072HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5073 Bstr &tapSetupApplication)
5074{
5075 LogFlowThisFunc(("\n"));
5076#ifdef RT_OS_LINUX
5077 /* Command line to start the script with. */
5078 char szCommand[4096];
5079 /* Result code */
5080 int rc;
5081
5082 /* Get the script name. */
5083 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5084 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5085 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5086 /*
5087 * Create the process and read its output.
5088 */
5089 Log2(("About to start the TAP setup script with the following command line: %s\n",
5090 szCommand));
5091 FILE *pfScriptHandle = popen(szCommand, "r");
5092 if (pfScriptHandle == 0)
5093 {
5094 int iErr = errno;
5095 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5096 szCommand, strerror(iErr)));
5097 LogFlowThisFunc(("rc=E_FAIL\n"));
5098 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5099 szCommand, strerror(iErr));
5100 }
5101 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5102 if (!isStatic)
5103 {
5104 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5105 interested in the first few (normally 5 or 6) bytes. */
5106 char acBuffer[64];
5107 /* The length of the string returned by the application. We only accept strings of 63
5108 characters or less. */
5109 size_t cBufSize;
5110
5111 /* Read the name of the device from the application. */
5112 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5113 cBufSize = strlen(acBuffer);
5114 /* The script must return the name of the interface followed by a carriage return as the
5115 first line of its output. We need a null-terminated string. */
5116 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5117 {
5118 pclose(pfScriptHandle);
5119 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5120 LogFlowThisFunc(("rc=E_FAIL\n"));
5121 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5122 }
5123 /* Overwrite the terminating newline character. */
5124 acBuffer[cBufSize - 1] = 0;
5125 tapDevice = acBuffer;
5126 }
5127 rc = pclose(pfScriptHandle);
5128 if (!WIFEXITED(rc))
5129 {
5130 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5131 LogFlowThisFunc(("rc=E_FAIL\n"));
5132 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5133 }
5134 if (WEXITSTATUS(rc) != 0)
5135 {
5136 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5137 LogFlowThisFunc(("rc=E_FAIL\n"));
5138 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5139 }
5140 LogFlowThisFunc(("rc=S_OK\n"));
5141 return S_OK;
5142#else /* RT_OS_LINUX not defined */
5143 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5144 return E_NOTIMPL; /* not yet supported */
5145#endif
5146}
5147
5148/**
5149 * Helper function to handle host interface device creation and attachment.
5150 *
5151 * @param networkAdapter the network adapter which attachment should be reset
5152 * @return COM status code
5153 *
5154 * @note The caller must lock this object for writing.
5155 */
5156HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5157{
5158 LogFlowThisFunc(("\n"));
5159 /* sanity check */
5160 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5161
5162#ifdef DEBUG
5163 /* paranoia */
5164 NetworkAttachmentType_T attachment;
5165 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5166 Assert(attachment == NetworkAttachmentType_HostInterface);
5167#endif /* DEBUG */
5168
5169 HRESULT rc = S_OK;
5170
5171#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5172 ULONG slot = 0;
5173 rc = networkAdapter->COMGETTER(Slot)(&slot);
5174 AssertComRC(rc);
5175
5176 /*
5177 * Try get the FD.
5178 */
5179 LONG ltapFD;
5180 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5181 if (SUCCEEDED(rc))
5182 maTapFD[slot] = (RTFILE)ltapFD;
5183 else
5184 maTapFD[slot] = NIL_RTFILE;
5185
5186 /*
5187 * Are we supposed to use an existing TAP interface?
5188 */
5189 if (maTapFD[slot] != NIL_RTFILE)
5190 {
5191 /* nothing to do */
5192 Assert(ltapFD >= 0);
5193 Assert((LONG)maTapFD[slot] == ltapFD);
5194 rc = S_OK;
5195 }
5196 else
5197#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5198 {
5199 /*
5200 * Allocate a host interface device
5201 */
5202#ifdef RT_OS_WINDOWS
5203 /* nothing to do */
5204 int rcVBox = VINF_SUCCESS;
5205#elif defined(RT_OS_LINUX)
5206 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5207 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5208 if (VBOX_SUCCESS(rcVBox))
5209 {
5210 /*
5211 * Set/obtain the tap interface.
5212 */
5213 bool isStatic = false;
5214 struct ifreq IfReq;
5215 memset(&IfReq, 0, sizeof(IfReq));
5216 /* The name of the TAP interface we are using and the TAP setup script resp. */
5217 Bstr tapDeviceName, tapSetupApplication;
5218 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5219 if (FAILED(rc))
5220 {
5221 tapDeviceName.setNull(); /* Is this necessary? */
5222 }
5223 else if (!tapDeviceName.isEmpty())
5224 {
5225 isStatic = true;
5226 /* If we are using a static TAP device then try to open it. */
5227 Utf8Str str(tapDeviceName);
5228 if (str.length() <= sizeof(IfReq.ifr_name))
5229 strcpy(IfReq.ifr_name, str.raw());
5230 else
5231 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5232 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5233 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5234 if (rcVBox != 0)
5235 {
5236 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5237 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5238 tapDeviceName.raw());
5239 }
5240 }
5241 if (SUCCEEDED(rc))
5242 {
5243 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5244 if (tapSetupApplication.isEmpty())
5245 {
5246 if (tapDeviceName.isEmpty())
5247 {
5248 LogRel(("No setup application was supplied for the TAP interface.\n"));
5249 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5250 }
5251 }
5252 else
5253 {
5254 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5255 tapSetupApplication);
5256 }
5257 }
5258 if (SUCCEEDED(rc))
5259 {
5260 if (!isStatic)
5261 {
5262 Utf8Str str(tapDeviceName);
5263 if (str.length() <= sizeof(IfReq.ifr_name))
5264 strcpy(IfReq.ifr_name, str.raw());
5265 else
5266 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5267 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5268 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5269 if (rcVBox != 0)
5270 {
5271 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5272 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5273 }
5274 }
5275 if (SUCCEEDED(rc))
5276 {
5277 /*
5278 * Make it pollable.
5279 */
5280 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5281 {
5282 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5283
5284 /*
5285 * Here is the right place to communicate the TAP file descriptor and
5286 * the host interface name to the server if/when it becomes really
5287 * necessary.
5288 */
5289 maTAPDeviceName[slot] = tapDeviceName;
5290 rcVBox = VINF_SUCCESS;
5291 }
5292 else
5293 {
5294 int iErr = errno;
5295
5296 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5297 rcVBox = VERR_HOSTIF_BLOCKING;
5298 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5299 strerror(errno));
5300 }
5301 }
5302 }
5303 }
5304 else
5305 {
5306 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5307 switch (rcVBox)
5308 {
5309 case VERR_ACCESS_DENIED:
5310 /* will be handled by our caller */
5311 rc = rcVBox;
5312 break;
5313 default:
5314 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
5315 break;
5316 }
5317 }
5318#elif defined(RT_OS_DARWIN)
5319 /** @todo Implement tap networking for Darwin. */
5320 int rcVBox = VERR_NOT_IMPLEMENTED;
5321#elif defined(RT_OS_FREEBSD)
5322 /** @todo Implement tap networking for FreeBSD. */
5323 int rcVBox = VERR_NOT_IMPLEMENTED;
5324#elif defined(RT_OS_OS2)
5325 /** @todo Implement tap networking for OS/2. */
5326 int rcVBox = VERR_NOT_IMPLEMENTED;
5327#elif defined(RT_OS_SOLARIS)
5328 /* nothing to do */
5329 int rcVBox = VINF_SUCCESS;
5330#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
5331# error "PORTME: Implement OS specific TAP interface open/creation."
5332#else
5333# error "Unknown host OS"
5334#endif
5335 /* in case of failure, cleanup. */
5336 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5337 {
5338 LogRel(("General failure attaching to host interface\n"));
5339 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5340 }
5341 }
5342 LogFlowThisFunc(("rc=%d\n", rc));
5343 return rc;
5344}
5345
5346/**
5347 * Helper function to handle detachment from a host interface
5348 *
5349 * @param networkAdapter the network adapter which attachment should be reset
5350 * @return COM status code
5351 *
5352 * @note The caller must lock this object for writing.
5353 */
5354HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5355{
5356 /* sanity check */
5357 LogFlowThisFunc(("\n"));
5358 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5359
5360 HRESULT rc = S_OK;
5361#ifdef DEBUG
5362 /* paranoia */
5363 NetworkAttachmentType_T attachment;
5364 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5365 Assert(attachment == NetworkAttachmentType_HostInterface);
5366#endif /* DEBUG */
5367
5368#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5369
5370 ULONG slot = 0;
5371 rc = networkAdapter->COMGETTER(Slot)(&slot);
5372 AssertComRC(rc);
5373
5374 /* is there an open TAP device? */
5375 if (maTapFD[slot] != NIL_RTFILE)
5376 {
5377 /*
5378 * Close the file handle.
5379 */
5380 Bstr tapDeviceName, tapTerminateApplication;
5381 bool isStatic = true;
5382 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5383 if (FAILED(rc) || tapDeviceName.isEmpty())
5384 {
5385 /* If the name is empty, this is a dynamic TAP device, so close it now,
5386 so that the termination script can remove the interface. Otherwise we still
5387 need the FD to pass to the termination script. */
5388 isStatic = false;
5389 int rcVBox = RTFileClose(maTapFD[slot]);
5390 AssertRC(rcVBox);
5391 maTapFD[slot] = NIL_RTFILE;
5392 }
5393 /*
5394 * Execute the termination command.
5395 */
5396 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5397 if (tapTerminateApplication)
5398 {
5399 /* Get the program name. */
5400 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5401
5402 /* Build the command line. */
5403 char szCommand[4096];
5404 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
5405 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
5406
5407 /*
5408 * Create the process and wait for it to complete.
5409 */
5410 Log(("Calling the termination command: %s\n", szCommand));
5411 int rcCommand = system(szCommand);
5412 if (rcCommand == -1)
5413 {
5414 LogRel(("Failed to execute the clean up script for the TAP interface"));
5415 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
5416 }
5417 if (!WIFEXITED(rc))
5418 {
5419 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
5420 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
5421 }
5422 if (WEXITSTATUS(rc) != 0)
5423 {
5424 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
5425 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
5426 }
5427 }
5428
5429 if (isStatic)
5430 {
5431 /* If we are using a static TAP device, we close it now, after having called the
5432 termination script. */
5433 int rcVBox = RTFileClose(maTapFD[slot]);
5434 AssertRC(rcVBox);
5435 }
5436 /* the TAP device name and handle are no longer valid */
5437 maTapFD[slot] = NIL_RTFILE;
5438 maTAPDeviceName[slot] = "";
5439 }
5440#endif
5441 LogFlowThisFunc(("returning %d\n", rc));
5442 return rc;
5443}
5444
5445
5446/**
5447 * Called at power down to terminate host interface networking.
5448 *
5449 * @note The caller must lock this object for writing.
5450 */
5451HRESULT Console::powerDownHostInterfaces()
5452{
5453 LogFlowThisFunc (("\n"));
5454
5455 /* sanity check */
5456 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5457
5458 /*
5459 * host interface termination handling
5460 */
5461 HRESULT rc;
5462 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
5463 {
5464 ComPtr<INetworkAdapter> networkAdapter;
5465 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
5466 CheckComRCBreakRC (rc);
5467
5468 BOOL enabled = FALSE;
5469 networkAdapter->COMGETTER(Enabled) (&enabled);
5470 if (!enabled)
5471 continue;
5472
5473 NetworkAttachmentType_T attachment;
5474 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5475 if (attachment == NetworkAttachmentType_HostInterface)
5476 {
5477 HRESULT rc2 = detachFromHostInterface(networkAdapter);
5478 if (FAILED(rc2) && SUCCEEDED(rc))
5479 rc = rc2;
5480 }
5481 }
5482
5483 return rc;
5484}
5485
5486
5487/**
5488 * Process callback handler for VMR3Load and VMR3Save.
5489 *
5490 * @param pVM The VM handle.
5491 * @param uPercent Completetion precentage (0-100).
5492 * @param pvUser Pointer to the VMProgressTask structure.
5493 * @return VINF_SUCCESS.
5494 */
5495/*static*/ DECLCALLBACK (int)
5496Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
5497{
5498 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5499 AssertReturn (task, VERR_INVALID_PARAMETER);
5500
5501 /* update the progress object */
5502 if (task->mProgress)
5503 task->mProgress->notifyProgress (uPercent);
5504
5505 return VINF_SUCCESS;
5506}
5507
5508/**
5509 * VM error callback function. Called by the various VM components.
5510 *
5511 * @param pVM VM handle. Can be NULL if an error occurred before
5512 * successfully creating a VM.
5513 * @param pvUser Pointer to the VMProgressTask structure.
5514 * @param rc VBox status code.
5515 * @param pszFormat Printf-like error message.
5516 * @param args Various number of argumens for the error message.
5517 *
5518 * @thread EMT, VMPowerUp...
5519 *
5520 * @note The VMProgressTask structure modified by this callback is not thread
5521 * safe.
5522 */
5523/* static */ DECLCALLBACK (void)
5524Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
5525 const char *pszFormat, va_list args)
5526{
5527 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5528 AssertReturnVoid (task);
5529
5530 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
5531 va_list va2;
5532 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
5533 Utf8Str errorMsg = Utf8StrFmt (tr ("%N.\n"
5534 "VBox status code: %d (%Vrc)"),
5535 pszFormat, &va2, rc, rc);
5536 va_end(va2);
5537
5538 /* For now, this may be called only once. Ignore subsequent calls. */
5539 AssertMsgReturnVoid (task->mErrorMsg.isNull(),
5540 ("Cannot set error to '%s': it is already set to '%s'",
5541 errorMsg.raw(), task->mErrorMsg.raw()));
5542
5543 task->mErrorMsg = errorMsg;
5544}
5545
5546/**
5547 * VM runtime error callback function.
5548 * See VMSetRuntimeError for the detailed description of parameters.
5549 *
5550 * @param pVM The VM handle.
5551 * @param pvUser The user argument.
5552 * @param fFatal Whether it is a fatal error or not.
5553 * @param pszErrorID Error ID string.
5554 * @param pszFormat Error message format string.
5555 * @param args Error message arguments.
5556 * @thread EMT.
5557 */
5558/* static */ DECLCALLBACK(void)
5559Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
5560 const char *pszErrorID,
5561 const char *pszFormat, va_list args)
5562{
5563 LogFlowFuncEnter();
5564
5565 Console *that = static_cast <Console *> (pvUser);
5566 AssertReturnVoid (that);
5567
5568 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
5569
5570 LogRel (("Console: VM runtime error: fatal=%RTbool, "
5571 "errorID=%s message=\"%s\"\n",
5572 fFatal, pszErrorID, message.raw()));
5573
5574 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
5575
5576 LogFlowFuncLeave();
5577}
5578
5579/**
5580 * Captures USB devices that match filters of the VM.
5581 * Called at VM startup.
5582 *
5583 * @param pVM The VM handle.
5584 *
5585 * @note The caller must lock this object for writing.
5586 */
5587HRESULT Console::captureUSBDevices (PVM pVM)
5588{
5589 LogFlowThisFunc (("\n"));
5590
5591 /* sanity check */
5592 ComAssertRet (isWriteLockOnCurrentThread(), E_FAIL);
5593
5594 /* If the machine has an USB controller, ask the USB proxy service to
5595 * capture devices */
5596 PPDMIBASE pBase;
5597 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
5598 if (VBOX_SUCCESS (vrc))
5599 {
5600 /* leave the lock before calling Host in VBoxSVC since Host may call
5601 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5602 * produce an inter-process dead-lock otherwise. */
5603 AutoWriteLock alock (this);
5604 alock.leave();
5605
5606 HRESULT hrc = mControl->AutoCaptureUSBDevices();
5607 ComAssertComRCRetRC (hrc);
5608 }
5609 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
5610 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
5611 vrc = VINF_SUCCESS;
5612 else
5613 AssertRC (vrc);
5614
5615 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
5616}
5617
5618
5619/**
5620 * Detach all USB device which are attached to the VM for the
5621 * purpose of clean up and such like.
5622 *
5623 * @note The caller must lock this object for writing.
5624 */
5625void Console::detachAllUSBDevices (bool aDone)
5626{
5627 LogFlowThisFunc (("\n"));
5628
5629 /* sanity check */
5630 AssertReturnVoid (isWriteLockOnCurrentThread());
5631
5632 mUSBDevices.clear();
5633
5634 /* leave the lock before calling Host in VBoxSVC since Host may call
5635 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5636 * produce an inter-process dead-lock otherwise. */
5637 AutoWriteLock alock (this);
5638 alock.leave();
5639
5640 mControl->DetachAllUSBDevices (aDone);
5641}
5642
5643/**
5644 * @note Locks this object for writing.
5645 */
5646void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
5647{
5648 LogFlowThisFuncEnter();
5649 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
5650
5651 AutoCaller autoCaller (this);
5652 if (!autoCaller.isOk())
5653 {
5654 /* Console has been already uninitialized, deny request */
5655 AssertMsgFailed (("Temporary assertion to prove that it happens, "
5656 "please report to dmik\n"));
5657 LogFlowThisFunc (("Console is already uninitialized\n"));
5658 LogFlowThisFuncLeave();
5659 return;
5660 }
5661
5662 AutoWriteLock alock (this);
5663
5664 /*
5665 * Mark all existing remote USB devices as dirty.
5666 */
5667 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
5668 while (it != mRemoteUSBDevices.end())
5669 {
5670 (*it)->dirty (true);
5671 ++ it;
5672 }
5673
5674 /*
5675 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
5676 */
5677 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
5678 VRDPUSBDEVICEDESC *e = pDevList;
5679
5680 /* The cbDevList condition must be checked first, because the function can
5681 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
5682 */
5683 while (cbDevList >= 2 && e->oNext)
5684 {
5685 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
5686 e->idVendor, e->idProduct,
5687 e->oProduct? (char *)e + e->oProduct: ""));
5688
5689 bool fNewDevice = true;
5690
5691 it = mRemoteUSBDevices.begin();
5692 while (it != mRemoteUSBDevices.end())
5693 {
5694 if ((*it)->devId () == e->id
5695 && (*it)->clientId () == u32ClientId)
5696 {
5697 /* The device is already in the list. */
5698 (*it)->dirty (false);
5699 fNewDevice = false;
5700 break;
5701 }
5702
5703 ++ it;
5704 }
5705
5706 if (fNewDevice)
5707 {
5708 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
5709 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
5710 ));
5711
5712 /* Create the device object and add the new device to list. */
5713 ComObjPtr <RemoteUSBDevice> device;
5714 device.createObject();
5715 device->init (u32ClientId, e);
5716
5717 mRemoteUSBDevices.push_back (device);
5718
5719 /* Check if the device is ok for current USB filters. */
5720 BOOL fMatched = FALSE;
5721 ULONG fMaskedIfs = 0;
5722
5723 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
5724
5725 AssertComRC (hrc);
5726
5727 LogFlowThisFunc (("USB filters return %d %#x\n", fMatched, fMaskedIfs));
5728
5729 if (fMatched)
5730 {
5731 hrc = onUSBDeviceAttach (device, NULL, fMaskedIfs);
5732
5733 /// @todo (r=dmik) warning reporting subsystem
5734
5735 if (hrc == S_OK)
5736 {
5737 LogFlowThisFunc (("Device attached\n"));
5738 device->captured (true);
5739 }
5740 }
5741 }
5742
5743 if (cbDevList < e->oNext)
5744 {
5745 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
5746 cbDevList, e->oNext));
5747 break;
5748 }
5749
5750 cbDevList -= e->oNext;
5751
5752 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
5753 }
5754
5755 /*
5756 * Remove dirty devices, that is those which are not reported by the server anymore.
5757 */
5758 for (;;)
5759 {
5760 ComObjPtr <RemoteUSBDevice> device;
5761
5762 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
5763 while (it != mRemoteUSBDevices.end())
5764 {
5765 if ((*it)->dirty ())
5766 {
5767 device = *it;
5768 break;
5769 }
5770
5771 ++ it;
5772 }
5773
5774 if (!device)
5775 {
5776 break;
5777 }
5778
5779 USHORT vendorId = 0;
5780 device->COMGETTER(VendorId) (&vendorId);
5781
5782 USHORT productId = 0;
5783 device->COMGETTER(ProductId) (&productId);
5784
5785 Bstr product;
5786 device->COMGETTER(Product) (product.asOutParam());
5787
5788 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
5789 vendorId, productId, product.raw ()
5790 ));
5791
5792 /* Detach the device from VM. */
5793 if (device->captured ())
5794 {
5795 Guid uuid;
5796 device->COMGETTER (Id) (uuid.asOutParam());
5797 onUSBDeviceDetach (uuid, NULL);
5798 }
5799
5800 /* And remove it from the list. */
5801 mRemoteUSBDevices.erase (it);
5802 }
5803
5804 LogFlowThisFuncLeave();
5805}
5806
5807
5808
5809/**
5810 * Thread function which starts the VM (also from saved state) and
5811 * track progress.
5812 *
5813 * @param Thread The thread id.
5814 * @param pvUser Pointer to a VMPowerUpTask structure.
5815 * @return VINF_SUCCESS (ignored).
5816 *
5817 * @note Locks the Console object for writing.
5818 */
5819/*static*/
5820DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
5821{
5822 LogFlowFuncEnter();
5823
5824 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
5825 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
5826
5827 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
5828 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
5829
5830#if defined(RT_OS_WINDOWS)
5831 {
5832 /* initialize COM */
5833 HRESULT hrc = CoInitializeEx (NULL,
5834 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
5835 COINIT_SPEED_OVER_MEMORY);
5836 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
5837 }
5838#endif
5839
5840 HRESULT hrc = S_OK;
5841 int vrc = VINF_SUCCESS;
5842
5843 /* Set up a build identifier so that it can be seen from core dumps what
5844 * exact build was used to produce the core. */
5845 static char saBuildID[40];
5846 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
5847 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBoxSVNRev (), "BU", "IL", "DI", "D");
5848
5849 ComObjPtr <Console> console = task->mConsole;
5850
5851 /* Note: no need to use addCaller() because VMPowerUpTask does that */
5852
5853 AutoWriteLock alock (console);
5854
5855 /* sanity */
5856 Assert (console->mpVM == NULL);
5857
5858 do
5859 {
5860#ifdef VBOX_VRDP
5861 /* Create the VRDP server. In case of headless operation, this will
5862 * also create the framebuffer, required at VM creation.
5863 */
5864 ConsoleVRDPServer *server = console->consoleVRDPServer();
5865 Assert (server);
5866 /// @todo (dmik)
5867 // does VRDP server call Console from the other thread?
5868 // Not sure, so leave the lock just in case
5869 alock.leave();
5870 vrc = server->Launch();
5871 alock.enter();
5872 if (VBOX_FAILURE (vrc))
5873 {
5874 Utf8Str errMsg;
5875 switch (vrc)
5876 {
5877 case VERR_NET_ADDRESS_IN_USE:
5878 {
5879 ULONG port = 0;
5880 console->mVRDPServer->COMGETTER(Port) (&port);
5881 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
5882 port);
5883 break;
5884 }
5885 case VERR_FILE_NOT_FOUND:
5886 {
5887 errMsg = Utf8StrFmt (tr ("Could not load the VRDP library"));
5888 break;
5889 }
5890 default:
5891 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
5892 vrc);
5893 }
5894 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
5895 vrc, errMsg.raw()));
5896 hrc = setError (E_FAIL, errMsg);
5897 break;
5898 }
5899#endif /* VBOX_VRDP */
5900
5901 /*
5902 * Create the VM
5903 */
5904 PVM pVM;
5905 /*
5906 * leave the lock since EMT will call Console. It's safe because
5907 * mMachineState is either Starting or Restoring state here.
5908 */
5909 alock.leave();
5910
5911 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
5912 task->mConfigConstructor, static_cast <Console *> (console),
5913 &pVM);
5914
5915 alock.enter();
5916
5917#ifdef VBOX_VRDP
5918 /* Enable client connections to the server. */
5919 console->consoleVRDPServer()->EnableConnections ();
5920#endif /* VBOX_VRDP */
5921
5922 if (VBOX_SUCCESS (vrc))
5923 {
5924 do
5925 {
5926 /*
5927 * Register our load/save state file handlers
5928 */
5929 vrc = SSMR3RegisterExternal (pVM,
5930 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
5931 0 /* cbGuess */,
5932 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
5933 static_cast <Console *> (console));
5934 AssertRC (vrc);
5935 if (VBOX_FAILURE (vrc))
5936 break;
5937
5938 /*
5939 * Synchronize debugger settings
5940 */
5941 MachineDebugger *machineDebugger = console->getMachineDebugger();
5942 if (machineDebugger)
5943 {
5944 machineDebugger->flushQueuedSettings();
5945 }
5946
5947 /*
5948 * Shared Folders
5949 */
5950 if (console->getVMMDev()->isShFlActive())
5951 {
5952 /// @todo (dmik)
5953 // does the code below call Console from the other thread?
5954 // Not sure, so leave the lock just in case
5955 alock.leave();
5956
5957 for (SharedFolderDataMap::const_iterator
5958 it = task->mSharedFolders.begin();
5959 it != task->mSharedFolders.end();
5960 ++ it)
5961 {
5962 hrc = console->createSharedFolder ((*it).first, (*it).second);
5963 CheckComRCBreakRC (hrc);
5964 }
5965
5966 /* enter the lock again */
5967 alock.enter();
5968
5969 CheckComRCBreakRC (hrc);
5970 }
5971
5972 /*
5973 * Capture USB devices.
5974 */
5975 hrc = console->captureUSBDevices (pVM);
5976 CheckComRCBreakRC (hrc);
5977
5978 /* leave the lock before a lengthy operation */
5979 alock.leave();
5980
5981 /* Load saved state? */
5982 if (!!task->mSavedStateFile)
5983 {
5984 LogFlowFunc (("Restoring saved state from '%s'...\n",
5985 task->mSavedStateFile.raw()));
5986
5987 vrc = VMR3Load (pVM, task->mSavedStateFile,
5988 Console::stateProgressCallback,
5989 static_cast <VMProgressTask *> (task.get()));
5990
5991 /* Start/Resume the VM execution */
5992 if (VBOX_SUCCESS (vrc))
5993 {
5994 vrc = VMR3Resume (pVM);
5995 AssertRC (vrc);
5996 }
5997
5998 /* Power off in case we failed loading or resuming the VM */
5999 if (VBOX_FAILURE (vrc))
6000 {
6001 int vrc2 = VMR3PowerOff (pVM);
6002 AssertRC (vrc2);
6003 }
6004 }
6005 else
6006 {
6007 /* Power on the VM (i.e. start executing) */
6008 vrc = VMR3PowerOn(pVM);
6009 AssertRC (vrc);
6010 }
6011
6012 /* enter the lock again */
6013 alock.enter();
6014 }
6015 while (0);
6016
6017 /* On failure, destroy the VM */
6018 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6019 {
6020 /* preserve existing error info */
6021 ErrorInfoKeeper eik;
6022
6023 /* powerDown() will call VMR3Destroy() and do all necessary
6024 * cleanup (VRDP, USB devices) */
6025 HRESULT hrc2 = console->powerDown();
6026 AssertComRC (hrc2);
6027 }
6028 }
6029 else
6030 {
6031 /*
6032 * If VMR3Create() failed it has released the VM memory.
6033 */
6034 console->mpVM = NULL;
6035 }
6036
6037 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6038 {
6039 /* If VMR3Create() or one of the other calls in this function fail,
6040 * an appropriate error message has been set in task->mErrorMsg.
6041 * However since that happens via a callback, the hrc status code in
6042 * this function is not updated.
6043 */
6044 if (task->mErrorMsg.isNull())
6045 {
6046 /* If the error message is not set but we've got a failure,
6047 * convert the VBox status code into a meaningfulerror message.
6048 * This becomes unused once all the sources of errors set the
6049 * appropriate error message themselves.
6050 */
6051 AssertMsgFailed (("Missing error message during powerup for "
6052 "status code %Vrc\n", vrc));
6053 task->mErrorMsg = Utf8StrFmt (
6054 tr ("Failed to start VM execution (%Vrc)"), vrc);
6055 }
6056
6057 /* Set the error message as the COM error.
6058 * Progress::notifyComplete() will pick it up later. */
6059 hrc = setError (E_FAIL, task->mErrorMsg);
6060 break;
6061 }
6062 }
6063 while (0);
6064
6065 if (console->mMachineState == MachineState_Starting ||
6066 console->mMachineState == MachineState_Restoring)
6067 {
6068 /* We are still in the Starting/Restoring state. This means one of:
6069 *
6070 * 1) we failed before VMR3Create() was called;
6071 * 2) VMR3Create() failed.
6072 *
6073 * In both cases, there is no need to call powerDown(), but we still
6074 * need to go back to the PoweredOff/Saved state. Reuse
6075 * vmstateChangeCallback() for that purpose.
6076 */
6077
6078 /* preserve existing error info */
6079 ErrorInfoKeeper eik;
6080
6081 Assert (console->mpVM == NULL);
6082 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6083 console);
6084 }
6085
6086 /*
6087 * Evaluate the final result. Note that the appropriate mMachineState value
6088 * is already set by vmstateChangeCallback() in all cases.
6089 */
6090
6091 /* leave the lock, don't need it any more */
6092 alock.leave();
6093
6094 if (SUCCEEDED (hrc))
6095 {
6096 /* Notify the progress object of the success */
6097 task->mProgress->notifyComplete (S_OK);
6098 }
6099 else
6100 {
6101 /* The progress object will fetch the current error info */
6102 task->mProgress->notifyComplete (hrc);
6103
6104 LogRel (("Power up failed (vrc=%Vrc, hrc=0x%08X)\n", vrc, hrc));
6105 }
6106
6107#if defined(RT_OS_WINDOWS)
6108 /* uninitialize COM */
6109 CoUninitialize();
6110#endif
6111
6112 LogFlowFuncLeave();
6113
6114 return VINF_SUCCESS;
6115}
6116
6117
6118/**
6119 * Reconfigures a VDI.
6120 *
6121 * @param pVM The VM handle.
6122 * @param hda The harddisk attachment.
6123 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6124 * @return VBox status code.
6125 */
6126static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6127{
6128 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6129
6130 int rc;
6131 HRESULT hrc;
6132 char *psz = NULL;
6133 BSTR str = NULL;
6134 *phrc = S_OK;
6135#define STR_CONV() do { rc = RTUtf16ToUtf8(str, &psz); RC_CHECK(); } while (0)
6136#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6137#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6138#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6139
6140 /*
6141 * Figure out which IDE device this is.
6142 */
6143 ComPtr<IHardDisk> hardDisk;
6144 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6145 StorageBus_T enmBus;
6146 hrc = hda->COMGETTER(Bus)(&enmBus); H();
6147 LONG lDev;
6148 hrc = hda->COMGETTER(Device)(&lDev); H();
6149 LONG lChannel;
6150 hrc = hda->COMGETTER(Channel)(&lChannel); H();
6151
6152 int iLUN;
6153 switch (enmBus)
6154 {
6155 case StorageBus_IDE:
6156 {
6157 if (lChannel >= 2)
6158 {
6159 AssertMsgFailed(("invalid controller channel number: %d\n", lChannel));
6160 return VERR_GENERAL_FAILURE;
6161 }
6162
6163 if (lDev >= 2)
6164 {
6165 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6166 return VERR_GENERAL_FAILURE;
6167 }
6168 iLUN = 2*lChannel + lDev;
6169 }
6170 break;
6171 case StorageBus_SATA:
6172 iLUN = lChannel;
6173 break;
6174 default:
6175 AssertMsgFailed(("invalid disk controller type: %d\n", enmBus));
6176 return VERR_GENERAL_FAILURE;
6177 }
6178
6179 /*
6180 * Is there an existing LUN? If not create it.
6181 * We ASSUME that this will NEVER collide with the DVD.
6182 */
6183 PCFGMNODE pCfg;
6184 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", iLUN);
6185 if (!pLunL1)
6186 {
6187 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6188 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6189
6190 PCFGMNODE pLunL0;
6191 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", iLUN); RC_CHECK();
6192 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6193 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6194 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6195 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6196
6197 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6198 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6199 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6200 }
6201 else
6202 {
6203#ifdef VBOX_STRICT
6204 char *pszDriver;
6205 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6206 Assert(!strcmp(pszDriver, "VBoxHDD"));
6207 MMR3HeapFree(pszDriver);
6208#endif
6209
6210 /*
6211 * Check if things has changed.
6212 */
6213 pCfg = CFGMR3GetChild(pLunL1, "Config");
6214 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6215
6216 /* the image */
6217 /// @todo (dmik) we temporarily use the location property to
6218 // determine the image file name. This is subject to change
6219 // when iSCSI disks are here (we should either query a
6220 // storage-specific interface from IHardDisk, or "standardize"
6221 // the location property)
6222 hrc = hardDisk->COMGETTER(Location)(&str); H();
6223 STR_CONV();
6224 char *pszPath;
6225 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6226 if (!strcmp(psz, pszPath))
6227 {
6228 /* parent images. */
6229 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6230 for (PCFGMNODE pParent = pCfg;;)
6231 {
6232 MMR3HeapFree(pszPath);
6233 pszPath = NULL;
6234 STR_FREE();
6235
6236 /* get parent */
6237 ComPtr<IHardDisk> curHardDisk;
6238 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6239 PCFGMNODE pCur;
6240 pCur = CFGMR3GetChild(pParent, "Parent");
6241 if (!pCur && !curHardDisk)
6242 {
6243 /* no change */
6244 LogFlowFunc (("No change!\n"));
6245 return VINF_SUCCESS;
6246 }
6247 if (!pCur || !curHardDisk)
6248 break;
6249
6250 /* compare paths. */
6251 /// @todo (dmik) we temporarily use the location property to
6252 // determine the image file name. This is subject to change
6253 // when iSCSI disks are here (we should either query a
6254 // storage-specific interface from IHardDisk, or "standardize"
6255 // the location property)
6256 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6257 STR_CONV();
6258 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6259 if (strcmp(psz, pszPath))
6260 break;
6261
6262 /* next */
6263 pParent = pCur;
6264 parentHardDisk = curHardDisk;
6265 }
6266
6267 }
6268 else
6269 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", iLUN, pszPath));
6270
6271 MMR3HeapFree(pszPath);
6272 STR_FREE();
6273
6274 /*
6275 * Detach the driver and replace the config node.
6276 */
6277 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, iLUN); RC_CHECK();
6278 CFGMR3RemoveNode(pCfg);
6279 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6280 }
6281
6282 /*
6283 * Create the driver configuration.
6284 */
6285 /// @todo (dmik) we temporarily use the location property to
6286 // determine the image file name. This is subject to change
6287 // when iSCSI disks are here (we should either query a
6288 // storage-specific interface from IHardDisk, or "standardize"
6289 // the location property)
6290 hrc = hardDisk->COMGETTER(Location)(&str); H();
6291 STR_CONV();
6292 LogFlowFunc (("LUN#%d: leaf image '%s'\n", iLUN, psz));
6293 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6294 STR_FREE();
6295 /* Create an inversed tree of parents. */
6296 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6297 for (PCFGMNODE pParent = pCfg;;)
6298 {
6299 ComPtr<IHardDisk> curHardDisk;
6300 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6301 if (!curHardDisk)
6302 break;
6303
6304 PCFGMNODE pCur;
6305 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6306 /// @todo (dmik) we temporarily use the location property to
6307 // determine the image file name. This is subject to change
6308 // when iSCSI disks are here (we should either query a
6309 // storage-specific interface from IHardDisk, or "standardize"
6310 // the location property)
6311 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6312 STR_CONV();
6313 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6314 STR_FREE();
6315
6316 /* next */
6317 pParent = pCur;
6318 parentHardDisk = curHardDisk;
6319 }
6320
6321 /*
6322 * Attach the new driver.
6323 */
6324 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, iLUN, NULL); RC_CHECK();
6325
6326 LogFlowFunc (("Returns success\n"));
6327 return rc;
6328}
6329
6330
6331/**
6332 * Thread for executing the saved state operation.
6333 *
6334 * @param Thread The thread handle.
6335 * @param pvUser Pointer to a VMSaveTask structure.
6336 * @return VINF_SUCCESS (ignored).
6337 *
6338 * @note Locks the Console object for writing.
6339 */
6340/*static*/
6341DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6342{
6343 LogFlowFuncEnter();
6344
6345 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6346 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6347
6348 Assert (!task->mSavedStateFile.isNull());
6349 Assert (!task->mProgress.isNull());
6350
6351 const ComObjPtr <Console> &that = task->mConsole;
6352
6353 /*
6354 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6355 * protect mpVM because VMSaveTask does that
6356 */
6357
6358 Utf8Str errMsg;
6359 HRESULT rc = S_OK;
6360
6361 if (task->mIsSnapshot)
6362 {
6363 Assert (!task->mServerProgress.isNull());
6364 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6365
6366 rc = task->mServerProgress->WaitForCompletion (-1);
6367 if (SUCCEEDED (rc))
6368 {
6369 HRESULT result = S_OK;
6370 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6371 if (SUCCEEDED (rc))
6372 rc = result;
6373 }
6374 }
6375
6376 if (SUCCEEDED (rc))
6377 {
6378 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6379
6380 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6381 Console::stateProgressCallback,
6382 static_cast <VMProgressTask *> (task.get()));
6383 if (VBOX_FAILURE (vrc))
6384 {
6385 errMsg = Utf8StrFmt (
6386 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6387 task->mSavedStateFile.raw(), vrc);
6388 rc = E_FAIL;
6389 }
6390 }
6391
6392 /* lock the console sonce we're going to access it */
6393 AutoWriteLock thatLock (that);
6394
6395 if (SUCCEEDED (rc))
6396 {
6397 if (task->mIsSnapshot)
6398 do
6399 {
6400 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
6401
6402 ComPtr <IHardDiskAttachmentCollection> hdaColl;
6403 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
6404 if (FAILED (rc))
6405 break;
6406 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
6407 rc = hdaColl->Enumerate (hdaEn.asOutParam());
6408 if (FAILED (rc))
6409 break;
6410 BOOL more = FALSE;
6411 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
6412 {
6413 ComPtr <IHardDiskAttachment> hda;
6414 rc = hdaEn->GetNext (hda.asOutParam());
6415 if (FAILED (rc))
6416 break;
6417
6418 PVMREQ pReq;
6419 IHardDiskAttachment *pHda = hda;
6420 /*
6421 * don't leave the lock since reconfigureVDI isn't going to
6422 * access Console.
6423 */
6424 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
6425 (PFNRT)reconfigureVDI, 3, that->mpVM,
6426 pHda, &rc);
6427 if (VBOX_SUCCESS (rc))
6428 rc = pReq->iStatus;
6429 VMR3ReqFree (pReq);
6430 if (FAILED (rc))
6431 break;
6432 if (VBOX_FAILURE (vrc))
6433 {
6434 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
6435 rc = E_FAIL;
6436 break;
6437 }
6438 }
6439 }
6440 while (0);
6441 }
6442
6443 /* finalize the procedure regardless of the result */
6444 if (task->mIsSnapshot)
6445 {
6446 /*
6447 * finalize the requested snapshot object.
6448 * This will reset the machine state to the state it had right
6449 * before calling mControl->BeginTakingSnapshot().
6450 */
6451 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
6452 }
6453 else
6454 {
6455 /*
6456 * finalize the requested save state procedure.
6457 * In case of success, the server will set the machine state to Saved;
6458 * in case of failure it will reset the it to the state it had right
6459 * before calling mControl->BeginSavingState().
6460 */
6461 that->mControl->EndSavingState (SUCCEEDED (rc));
6462 }
6463
6464 /* synchronize the state with the server */
6465 if (task->mIsSnapshot || FAILED (rc))
6466 {
6467 if (task->mLastMachineState == MachineState_Running)
6468 {
6469 /* restore the paused state if appropriate */
6470 that->setMachineStateLocally (MachineState_Paused);
6471 /* restore the running state if appropriate */
6472 that->Resume();
6473 }
6474 else
6475 that->setMachineStateLocally (task->mLastMachineState);
6476 }
6477 else
6478 {
6479 /*
6480 * The machine has been successfully saved, so power it down
6481 * (vmstateChangeCallback() will set state to Saved on success).
6482 * Note: we release the task's VM caller, otherwise it will
6483 * deadlock.
6484 */
6485 task->releaseVMCaller();
6486
6487 rc = that->powerDown();
6488 }
6489
6490 /* notify the progress object about operation completion */
6491 if (SUCCEEDED (rc))
6492 task->mProgress->notifyComplete (S_OK);
6493 else
6494 {
6495 if (!errMsg.isNull())
6496 task->mProgress->notifyComplete (rc,
6497 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
6498 else
6499 task->mProgress->notifyComplete (rc);
6500 }
6501
6502 LogFlowFuncLeave();
6503 return VINF_SUCCESS;
6504}
6505
6506/**
6507 * Thread for powering down the Console.
6508 *
6509 * @param Thread The thread handle.
6510 * @param pvUser Pointer to the VMTask structure.
6511 * @return VINF_SUCCESS (ignored).
6512 *
6513 * @note Locks the Console object for writing.
6514 */
6515/*static*/
6516DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
6517{
6518 LogFlowFuncEnter();
6519
6520 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
6521 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6522
6523 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
6524
6525 const ComObjPtr <Console> &that = task->mConsole;
6526
6527 /*
6528 * Note: no need to use addCaller() to protect Console
6529 * because VMTask does that
6530 */
6531
6532 /* release VM caller to let powerDown() proceed */
6533 task->releaseVMCaller();
6534
6535 HRESULT rc = that->powerDown();
6536 AssertComRC (rc);
6537
6538 LogFlowFuncLeave();
6539 return VINF_SUCCESS;
6540}
6541
6542/**
6543 * The Main status driver instance data.
6544 */
6545typedef struct DRVMAINSTATUS
6546{
6547 /** The LED connectors. */
6548 PDMILEDCONNECTORS ILedConnectors;
6549 /** Pointer to the LED ports interface above us. */
6550 PPDMILEDPORTS pLedPorts;
6551 /** Pointer to the array of LED pointers. */
6552 PPDMLED *papLeds;
6553 /** The unit number corresponding to the first entry in the LED array. */
6554 RTUINT iFirstLUN;
6555 /** The unit number corresponding to the last entry in the LED array.
6556 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
6557 RTUINT iLastLUN;
6558} DRVMAINSTATUS, *PDRVMAINSTATUS;
6559
6560
6561/**
6562 * Notification about a unit which have been changed.
6563 *
6564 * The driver must discard any pointers to data owned by
6565 * the unit and requery it.
6566 *
6567 * @param pInterface Pointer to the interface structure containing the called function pointer.
6568 * @param iLUN The unit number.
6569 */
6570DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
6571{
6572 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
6573 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
6574 {
6575 PPDMLED pLed;
6576 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
6577 if (VBOX_FAILURE(rc))
6578 pLed = NULL;
6579 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
6580 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
6581 }
6582}
6583
6584
6585/**
6586 * Queries an interface to the driver.
6587 *
6588 * @returns Pointer to interface.
6589 * @returns NULL if the interface was not supported by the driver.
6590 * @param pInterface Pointer to this interface structure.
6591 * @param enmInterface The requested interface identification.
6592 */
6593DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
6594{
6595 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
6596 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6597 switch (enmInterface)
6598 {
6599 case PDMINTERFACE_BASE:
6600 return &pDrvIns->IBase;
6601 case PDMINTERFACE_LED_CONNECTORS:
6602 return &pDrv->ILedConnectors;
6603 default:
6604 return NULL;
6605 }
6606}
6607
6608
6609/**
6610 * Destruct a status driver instance.
6611 *
6612 * @returns VBox status.
6613 * @param pDrvIns The driver instance data.
6614 */
6615DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
6616{
6617 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6618 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6619 if (pData->papLeds)
6620 {
6621 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
6622 while (iLed-- > 0)
6623 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
6624 }
6625}
6626
6627
6628/**
6629 * Construct a status driver instance.
6630 *
6631 * @returns VBox status.
6632 * @param pDrvIns The driver instance data.
6633 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
6634 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
6635 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
6636 * iInstance it's expected to be used a bit in this function.
6637 */
6638DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
6639{
6640 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6641 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6642
6643 /*
6644 * Validate configuration.
6645 */
6646 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
6647 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
6648 PPDMIBASE pBaseIgnore;
6649 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
6650 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
6651 {
6652 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
6653 return VERR_PDM_DRVINS_NO_ATTACH;
6654 }
6655
6656 /*
6657 * Data.
6658 */
6659 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
6660 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
6661
6662 /*
6663 * Read config.
6664 */
6665 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
6666 if (VBOX_FAILURE(rc))
6667 {
6668 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
6669 return rc;
6670 }
6671
6672 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
6673 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
6674 pData->iFirstLUN = 0;
6675 else if (VBOX_FAILURE(rc))
6676 {
6677 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
6678 return rc;
6679 }
6680
6681 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
6682 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
6683 pData->iLastLUN = 0;
6684 else if (VBOX_FAILURE(rc))
6685 {
6686 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
6687 return rc;
6688 }
6689 if (pData->iFirstLUN > pData->iLastLUN)
6690 {
6691 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
6692 return VERR_GENERAL_FAILURE;
6693 }
6694
6695 /*
6696 * Get the ILedPorts interface of the above driver/device and
6697 * query the LEDs we want.
6698 */
6699 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
6700 if (!pData->pLedPorts)
6701 {
6702 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
6703 return VERR_PDM_MISSING_INTERFACE_ABOVE;
6704 }
6705
6706 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
6707 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
6708
6709 return VINF_SUCCESS;
6710}
6711
6712
6713/**
6714 * Keyboard driver registration record.
6715 */
6716const PDMDRVREG Console::DrvStatusReg =
6717{
6718 /* u32Version */
6719 PDM_DRVREG_VERSION,
6720 /* szDriverName */
6721 "MainStatus",
6722 /* pszDescription */
6723 "Main status driver (Main as in the API).",
6724 /* fFlags */
6725 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
6726 /* fClass. */
6727 PDM_DRVREG_CLASS_STATUS,
6728 /* cMaxInstances */
6729 ~0,
6730 /* cbInstance */
6731 sizeof(DRVMAINSTATUS),
6732 /* pfnConstruct */
6733 Console::drvStatus_Construct,
6734 /* pfnDestruct */
6735 Console::drvStatus_Destruct,
6736 /* pfnIOCtl */
6737 NULL,
6738 /* pfnPowerOn */
6739 NULL,
6740 /* pfnReset */
6741 NULL,
6742 /* pfnSuspend */
6743 NULL,
6744 /* pfnResume */
6745 NULL,
6746 /* pfnDetach */
6747 NULL
6748};
6749
Note: See TracBrowser for help on using the repository browser.

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