VirtualBox

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

Last change on this file since 13538 was 13417, checked in by vboxsync, 16 years ago

Main (Guest Properties): some cleaning up

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

© 2023 Oracle
ContactPrivacy policyTerms of Use