VirtualBox

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

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

Use %Rhrc.

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

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