VirtualBox

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

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

shared folders: store 'writable' attribute, do it backward compatible

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