VirtualBox

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

Last change on this file since 13552 was 13551, checked in by vboxsync, 16 years ago

HostServices/GuestProperties and Main (Guest Properties): use the new iprt pattern matching APIs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 233.2 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 Utf8Str utf8Patterns(aPatterns);
3662 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
3663 parm[0].u.pointer.addr = utf8Patterns.mutableRaw();
3664 parm[0].u.pointer.size = utf8Patterns.length() + 1;
3665
3666 /*
3667 * Now things get slightly complicated. Due to a race with the guest adding
3668 * properties, there is no good way to know how much large a buffer to provide
3669 * the service to enumerate into. We choose a decent starting size and loop a
3670 * few times, each time retrying with the size suggested by the service plus
3671 * one Kb.
3672 */
3673 size_t cchBuf = 4096;
3674 Utf8Str Utf8Buf;
3675 int vrc = VERR_BUFFER_OVERFLOW;
3676 for (unsigned i = 0; i < 10 && (VERR_BUFFER_OVERFLOW == vrc); ++i)
3677 {
3678 Utf8Buf.alloc(cchBuf + 1024);
3679 if (Utf8Buf.isNull())
3680 return E_OUTOFMEMORY;
3681 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
3682 parm[1].u.pointer.addr = Utf8Buf.mutableRaw();
3683 parm[1].u.pointer.size = cchBuf + 1024;
3684 vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", ENUM_PROPS_HOST, 3,
3685 &parm[0]);
3686 if (parm[2].type != VBOX_HGCM_SVC_PARM_32BIT)
3687 return setError (E_FAIL, tr ("Internal application error"));
3688 cchBuf = parm[2].u.uint32;
3689 }
3690 if (VERR_BUFFER_OVERFLOW == vrc)
3691 return setError (E_UNEXPECTED, tr ("Temporary failure due to guest activity, please retry"));
3692
3693 /*
3694 * Finally we have to unpack the data returned by the service into the safe
3695 * arrays supplied by the caller. We start by counting the number of entries.
3696 */
3697 const char *pszBuf
3698 = reinterpret_cast<const char *>(parm[1].u.pointer.addr);
3699 unsigned cEntries = 0;
3700 /* The list is terminated by a zero-length string at the end of a set
3701 * of four strings. */
3702 for (size_t i = 0; strlen(pszBuf + i) != 0; )
3703 {
3704 /* We are counting sets of four strings. */
3705 for (unsigned j = 0; j < 4; ++j)
3706 i += strlen(pszBuf + i) + 1;
3707 ++cEntries;
3708 }
3709
3710 /*
3711 * And now we create the COM safe arrays and fill them in.
3712 */
3713 com::SafeArray <BSTR> names(cEntries);
3714 com::SafeArray <BSTR> values(cEntries);
3715 com::SafeArray <ULONG64> timestamps(cEntries);
3716 com::SafeArray <BSTR> flags(cEntries);
3717 size_t iBuf = 0;
3718 /* Rely on the service to have formated the data correctly. */
3719 for (unsigned i = 0; i < cEntries; ++i)
3720 {
3721 size_t cchName = strlen(pszBuf + iBuf);
3722 Bstr(pszBuf + iBuf).detachTo(&names[i]);
3723 iBuf += cchName + 1;
3724 size_t cchValue = strlen(pszBuf + iBuf);
3725 Bstr(pszBuf + iBuf).detachTo(&values[i]);
3726 iBuf += cchValue + 1;
3727 size_t cchTimestamp = strlen(pszBuf + iBuf);
3728 timestamps[i] = RTStrToUInt64(pszBuf + iBuf);
3729 iBuf += cchTimestamp + 1;
3730 size_t cchFlags = strlen(pszBuf + iBuf);
3731 Bstr(pszBuf + iBuf).detachTo(&flags[i]);
3732 iBuf += cchFlags + 1;
3733 }
3734 names.detachTo(ComSafeArrayOutArg (aNames));
3735 values.detachTo(ComSafeArrayOutArg (aValues));
3736 timestamps.detachTo(ComSafeArrayOutArg (aTimestamps));
3737 flags.detachTo(ComSafeArrayOutArg (aFlags));
3738 return S_OK;
3739#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3740}
3741
3742/**
3743 * Gets called by Session::UpdateMachineState()
3744 * (IInternalSessionControl::updateMachineState()).
3745 *
3746 * Must be called only in certain cases (see the implementation).
3747 *
3748 * @note Locks this object for writing.
3749 */
3750HRESULT Console::updateMachineState (MachineState_T aMachineState)
3751{
3752 AutoCaller autoCaller (this);
3753 AssertComRCReturnRC (autoCaller.rc());
3754
3755 AutoWriteLock alock (this);
3756
3757 AssertReturn (mMachineState == MachineState_Saving ||
3758 mMachineState == MachineState_Discarding,
3759 E_FAIL);
3760
3761 return setMachineStateLocally (aMachineState);
3762}
3763
3764/**
3765 * @note Locks this object for writing.
3766 */
3767void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3768 uint32_t xHot, uint32_t yHot,
3769 uint32_t width, uint32_t height,
3770 void *pShape)
3771{
3772#if 0
3773 LogFlowThisFuncEnter();
3774 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3775 "height=%d, shape=%p\n",
3776 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3777#endif
3778
3779 AutoCaller autoCaller (this);
3780 AssertComRCReturnVoid (autoCaller.rc());
3781
3782 /* We need a write lock because we alter the cached callback data */
3783 AutoWriteLock alock (this);
3784
3785 /* Save the callback arguments */
3786 mCallbackData.mpsc.visible = fVisible;
3787 mCallbackData.mpsc.alpha = fAlpha;
3788 mCallbackData.mpsc.xHot = xHot;
3789 mCallbackData.mpsc.yHot = yHot;
3790 mCallbackData.mpsc.width = width;
3791 mCallbackData.mpsc.height = height;
3792
3793 /* start with not valid */
3794 bool wasValid = mCallbackData.mpsc.valid;
3795 mCallbackData.mpsc.valid = false;
3796
3797 if (pShape != NULL)
3798 {
3799 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3800 cb = ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3801 /* try to reuse the old shape buffer if the size is the same */
3802 if (!wasValid)
3803 mCallbackData.mpsc.shape = NULL;
3804 else
3805 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3806 {
3807 RTMemFree (mCallbackData.mpsc.shape);
3808 mCallbackData.mpsc.shape = NULL;
3809 }
3810 if (mCallbackData.mpsc.shape == NULL)
3811 {
3812 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3813 AssertReturnVoid (mCallbackData.mpsc.shape);
3814 }
3815 mCallbackData.mpsc.shapeSize = cb;
3816 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3817 }
3818 else
3819 {
3820 if (wasValid && mCallbackData.mpsc.shape != NULL)
3821 RTMemFree (mCallbackData.mpsc.shape);
3822 mCallbackData.mpsc.shape = NULL;
3823 mCallbackData.mpsc.shapeSize = 0;
3824 }
3825
3826 mCallbackData.mpsc.valid = true;
3827
3828 CallbackList::iterator it = mCallbacks.begin();
3829 while (it != mCallbacks.end())
3830 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3831 width, height, (BYTE *) pShape);
3832
3833#if 0
3834 LogFlowThisFuncLeave();
3835#endif
3836}
3837
3838/**
3839 * @note Locks this object for writing.
3840 */
3841void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3842{
3843 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3844 supportsAbsolute, needsHostCursor));
3845
3846 AutoCaller autoCaller (this);
3847 AssertComRCReturnVoid (autoCaller.rc());
3848
3849 /* We need a write lock because we alter the cached callback data */
3850 AutoWriteLock alock (this);
3851
3852 /* save the callback arguments */
3853 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3854 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3855 mCallbackData.mcc.valid = true;
3856
3857 CallbackList::iterator it = mCallbacks.begin();
3858 while (it != mCallbacks.end())
3859 {
3860 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3861 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3862 }
3863}
3864
3865/**
3866 * @note Locks this object for reading.
3867 */
3868void Console::onStateChange (MachineState_T machineState)
3869{
3870 AutoCaller autoCaller (this);
3871 AssertComRCReturnVoid (autoCaller.rc());
3872
3873 AutoReadLock alock (this);
3874
3875 CallbackList::iterator it = mCallbacks.begin();
3876 while (it != mCallbacks.end())
3877 (*it++)->OnStateChange (machineState);
3878}
3879
3880/**
3881 * @note Locks this object for reading.
3882 */
3883void Console::onAdditionsStateChange()
3884{
3885 AutoCaller autoCaller (this);
3886 AssertComRCReturnVoid (autoCaller.rc());
3887
3888 AutoReadLock alock (this);
3889
3890 CallbackList::iterator it = mCallbacks.begin();
3891 while (it != mCallbacks.end())
3892 (*it++)->OnAdditionsStateChange();
3893}
3894
3895/**
3896 * @note Locks this object for reading.
3897 */
3898void Console::onAdditionsOutdated()
3899{
3900 AutoCaller autoCaller (this);
3901 AssertComRCReturnVoid (autoCaller.rc());
3902
3903 AutoReadLock alock (this);
3904
3905 /** @todo Use the On-Screen Display feature to report the fact.
3906 * The user should be told to install additions that are
3907 * provided with the current VBox build:
3908 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3909 */
3910}
3911
3912/**
3913 * @note Locks this object for writing.
3914 */
3915void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3916{
3917 AutoCaller autoCaller (this);
3918 AssertComRCReturnVoid (autoCaller.rc());
3919
3920 /* We need a write lock because we alter the cached callback data */
3921 AutoWriteLock alock (this);
3922
3923 /* save the callback arguments */
3924 mCallbackData.klc.numLock = fNumLock;
3925 mCallbackData.klc.capsLock = fCapsLock;
3926 mCallbackData.klc.scrollLock = fScrollLock;
3927 mCallbackData.klc.valid = true;
3928
3929 CallbackList::iterator it = mCallbacks.begin();
3930 while (it != mCallbacks.end())
3931 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3932}
3933
3934/**
3935 * @note Locks this object for reading.
3936 */
3937void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
3938 IVirtualBoxErrorInfo *aError)
3939{
3940 AutoCaller autoCaller (this);
3941 AssertComRCReturnVoid (autoCaller.rc());
3942
3943 AutoReadLock alock (this);
3944
3945 CallbackList::iterator it = mCallbacks.begin();
3946 while (it != mCallbacks.end())
3947 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
3948}
3949
3950/**
3951 * @note Locks this object for reading.
3952 */
3953void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3954{
3955 AutoCaller autoCaller (this);
3956 AssertComRCReturnVoid (autoCaller.rc());
3957
3958 AutoReadLock alock (this);
3959
3960 CallbackList::iterator it = mCallbacks.begin();
3961 while (it != mCallbacks.end())
3962 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3963}
3964
3965/**
3966 * @note Locks this object for reading.
3967 */
3968HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
3969{
3970 AssertReturn (aCanShow, E_POINTER);
3971 AssertReturn (aWinId, E_POINTER);
3972
3973 *aCanShow = FALSE;
3974 *aWinId = 0;
3975
3976 AutoCaller autoCaller (this);
3977 AssertComRCReturnRC (autoCaller.rc());
3978
3979 AutoReadLock alock (this);
3980
3981 HRESULT rc = S_OK;
3982 CallbackList::iterator it = mCallbacks.begin();
3983
3984 if (aCheck)
3985 {
3986 while (it != mCallbacks.end())
3987 {
3988 BOOL canShow = FALSE;
3989 rc = (*it++)->OnCanShowWindow (&canShow);
3990 AssertComRC (rc);
3991 if (FAILED (rc) || !canShow)
3992 return rc;
3993 }
3994 *aCanShow = TRUE;
3995 }
3996 else
3997 {
3998 while (it != mCallbacks.end())
3999 {
4000 ULONG64 winId = 0;
4001 rc = (*it++)->OnShowWindow (&winId);
4002 AssertComRC (rc);
4003 if (FAILED (rc))
4004 return rc;
4005 /* only one callback may return non-null winId */
4006 Assert (*aWinId == 0 || winId == 0);
4007 if (*aWinId == 0)
4008 *aWinId = winId;
4009 }
4010 }
4011
4012 return S_OK;
4013}
4014
4015// private methods
4016////////////////////////////////////////////////////////////////////////////////
4017
4018/**
4019 * Increases the usage counter of the mpVM pointer. Guarantees that
4020 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
4021 * is called.
4022 *
4023 * If this method returns a failure, the caller is not allowed to use mpVM
4024 * and may return the failed result code to the upper level. This method sets
4025 * the extended error info on failure if \a aQuiet is false.
4026 *
4027 * Setting \a aQuiet to true is useful for methods that don't want to return
4028 * the failed result code to the caller when this method fails (e.g. need to
4029 * silently check for the mpVM avaliability).
4030 *
4031 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
4032 * returned instead of asserting. Having it false is intended as a sanity check
4033 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
4034 *
4035 * @param aQuiet true to suppress setting error info
4036 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
4037 * (otherwise this method will assert if mpVM is NULL)
4038 *
4039 * @note Locks this object for writing.
4040 */
4041HRESULT Console::addVMCaller (bool aQuiet /* = false */,
4042 bool aAllowNullVM /* = false */)
4043{
4044 AutoCaller autoCaller (this);
4045 AssertComRCReturnRC (autoCaller.rc());
4046
4047 AutoWriteLock alock (this);
4048
4049 if (mVMDestroying)
4050 {
4051 /* powerDown() is waiting for all callers to finish */
4052 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
4053 tr ("Virtual machine is being powered down"));
4054 }
4055
4056 if (mpVM == NULL)
4057 {
4058 Assert (aAllowNullVM == true);
4059
4060 /* The machine is not powered up */
4061 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
4062 tr ("Virtual machine is not powered up"));
4063 }
4064
4065 ++ mVMCallers;
4066
4067 return S_OK;
4068}
4069
4070/**
4071 * Decreases the usage counter of the mpVM pointer. Must always complete
4072 * the addVMCaller() call after the mpVM pointer is no more necessary.
4073 *
4074 * @note Locks this object for writing.
4075 */
4076void Console::releaseVMCaller()
4077{
4078 AutoCaller autoCaller (this);
4079 AssertComRCReturnVoid (autoCaller.rc());
4080
4081 AutoWriteLock alock (this);
4082
4083 AssertReturnVoid (mpVM != NULL);
4084
4085 Assert (mVMCallers > 0);
4086 -- mVMCallers;
4087
4088 if (mVMCallers == 0 && mVMDestroying)
4089 {
4090 /* inform powerDown() there are no more callers */
4091 RTSemEventSignal (mVMZeroCallersSem);
4092 }
4093}
4094
4095/**
4096 * Initialize the release logging facility. In case something
4097 * goes wrong, there will be no release logging. Maybe in the future
4098 * we can add some logic to use different file names in this case.
4099 * Note that the logic must be in sync with Machine::DeleteSettings().
4100 */
4101HRESULT Console::consoleInitReleaseLog (const ComPtr <IMachine> aMachine)
4102{
4103 HRESULT hrc = S_OK;
4104
4105 Bstr logFolder;
4106 hrc = aMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
4107 CheckComRCReturnRC (hrc);
4108
4109 Utf8Str logDir = logFolder;
4110
4111 /* make sure the Logs folder exists */
4112 Assert (!logDir.isEmpty());
4113 if (!RTDirExists (logDir))
4114 RTDirCreateFullPath (logDir, 0777);
4115
4116 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
4117 logDir.raw(), RTPATH_DELIMITER);
4118 Utf8Str pngFile = Utf8StrFmt ("%s%cVBox.png",
4119 logDir.raw(), RTPATH_DELIMITER);
4120
4121 /*
4122 * Age the old log files
4123 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
4124 * Overwrite target files in case they exist.
4125 */
4126 ComPtr<IVirtualBox> virtualBox;
4127 aMachine->COMGETTER(Parent)(virtualBox.asOutParam());
4128 ComPtr <ISystemProperties> systemProperties;
4129 virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4130 ULONG uLogHistoryCount = 3;
4131 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4132 if (uLogHistoryCount)
4133 {
4134 for (int i = uLogHistoryCount-1; i >= 0; i--)
4135 {
4136 Utf8Str *files[] = { &logFile, &pngFile };
4137 Utf8Str oldName, newName;
4138
4139 for (unsigned int j = 0; j < ELEMENTS (files); ++ j)
4140 {
4141 if (i > 0)
4142 oldName = Utf8StrFmt ("%s.%d", files [j]->raw(), i);
4143 else
4144 oldName = *files [j];
4145 newName = Utf8StrFmt ("%s.%d", files [j]->raw(), i + 1);
4146 /* If the old file doesn't exist, delete the new file (if it
4147 * exists) to provide correct rotation even if the sequence is
4148 * broken */
4149 if ( RTFileRename (oldName, newName, RTFILEMOVE_FLAGS_REPLACE)
4150 == VERR_FILE_NOT_FOUND)
4151 RTFileDelete (newName);
4152 }
4153 }
4154 }
4155
4156 PRTLOGGER loggerRelease;
4157 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
4158 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
4159#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
4160 fFlags |= RTLOGFLAGS_USECRLF;
4161#endif
4162 char szError[RTPATH_MAX + 128] = "";
4163 int vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
4164 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
4165 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
4166 if (RT_SUCCESS(vrc))
4167 {
4168 /* some introductory information */
4169 RTTIMESPEC timeSpec;
4170 char szTmp[256];
4171 RTTimeSpecToString(RTTimeNow(&timeSpec), szTmp, sizeof(szTmp));
4172 RTLogRelLogger(loggerRelease, 0, ~0U,
4173 "VirtualBox %s r%d %s (%s %s) release log\n"
4174 "Log opened %s\n",
4175 VBOX_VERSION_STRING, VBoxSVNRev (), VBOX_BUILD_TARGET,
4176 __DATE__, __TIME__, szTmp);
4177
4178 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
4179 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4180 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Product: %s\n", szTmp);
4181 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
4182 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4183 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Release: %s\n", szTmp);
4184 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
4185 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4186 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Version: %s\n", szTmp);
4187 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
4188 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
4189 RTLogRelLogger(loggerRelease, 0, ~0U, "OS Service Pack: %s\n", szTmp);
4190 /* the package type is interesting for Linux distributions */
4191 RTLogRelLogger (loggerRelease, 0, ~0U, "Package type: %s"
4192#ifdef VBOX_OSE
4193 " (OSE)"
4194#endif
4195 "\n",
4196 VBOX_PACKAGE_STRING);
4197
4198 /* register this logger as the release logger */
4199 RTLogRelSetDefaultInstance(loggerRelease);
4200 hrc = S_OK;
4201 }
4202 else
4203 hrc = setError (E_FAIL,
4204 tr ("Failed to open release log (%s, %Rrc)"), szError, vrc);
4205
4206 return hrc;
4207}
4208
4209/**
4210 * Common worker for PowerUp and PowerUpPaused.
4211 *
4212 * @returns COM status code.
4213 *
4214 * @param aProgress Where to return the progress object.
4215 * @param aPaused true if PowerUpPaused called.
4216 *
4217 * @todo move down to powerDown();
4218 */
4219HRESULT Console::powerUp (IProgress **aProgress, bool aPaused)
4220{
4221 if (aProgress == NULL)
4222 return E_POINTER;
4223
4224 LogFlowThisFuncEnter();
4225 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
4226
4227 AutoCaller autoCaller (this);
4228 CheckComRCReturnRC (autoCaller.rc());
4229
4230 AutoWriteLock alock (this);
4231
4232 if (mMachineState >= MachineState_Running)
4233 return setError(E_FAIL, tr ("Virtual machine is already running "
4234 "(machine state: %d)"),
4235 mMachineState);
4236
4237 /*
4238 * First check whether all disks are accessible. This is not a 100%
4239 * bulletproof approach (race condition, it might become inaccessible
4240 * right after the check) but it's convenient as it will cover 99.9%
4241 * of the cases and here, we're able to provide meaningful error
4242 * information.
4243 */
4244 ComPtr<IHardDiskAttachmentCollection> coll;
4245 mMachine->COMGETTER(HardDiskAttachments)(coll.asOutParam());
4246 ComPtr<IHardDiskAttachmentEnumerator> enumerator;
4247 coll->Enumerate(enumerator.asOutParam());
4248 BOOL fHasMore;
4249 while (SUCCEEDED(enumerator->HasMore(&fHasMore)) && fHasMore)
4250 {
4251 ComPtr<IHardDiskAttachment> attach;
4252 enumerator->GetNext(attach.asOutParam());
4253 ComPtr<IHardDisk> hdd;
4254 attach->COMGETTER(HardDisk)(hdd.asOutParam());
4255 Assert(hdd);
4256 BOOL fAccessible;
4257 HRESULT rc = hdd->COMGETTER(AllAccessible)(&fAccessible);
4258 CheckComRCReturnRC (rc);
4259 if (!fAccessible)
4260 {
4261 Bstr loc;
4262 hdd->COMGETTER(Location) (loc.asOutParam());
4263 Bstr errMsg;
4264 hdd->COMGETTER(LastAccessError) (errMsg.asOutParam());
4265 return setError (E_FAIL,
4266 tr ("VM cannot start because the hard disk '%ls' is not accessible "
4267 "(%ls)"),
4268 loc.raw(), errMsg.raw());
4269 }
4270 }
4271
4272 /* now perform the same check if a ISO is mounted */
4273 ComPtr<IDVDDrive> dvdDrive;
4274 mMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam());
4275 ComPtr<IDVDImage> dvdImage;
4276 dvdDrive->GetImage(dvdImage.asOutParam());
4277 if (dvdImage)
4278 {
4279 BOOL fAccessible;
4280 HRESULT rc = dvdImage->COMGETTER(Accessible)(&fAccessible);
4281 CheckComRCReturnRC (rc);
4282 if (!fAccessible)
4283 {
4284 Bstr filePath;
4285 dvdImage->COMGETTER(FilePath)(filePath.asOutParam());
4286 /// @todo (r=dmik) grab the last access error once
4287 // IDVDImage::lastAccessError is there
4288 return setError (E_FAIL,
4289 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"),
4290 filePath.raw());
4291 }
4292 }
4293
4294 /* now perform the same check if a floppy is mounted */
4295 ComPtr<IFloppyDrive> floppyDrive;
4296 mMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam());
4297 ComPtr<IFloppyImage> floppyImage;
4298 floppyDrive->GetImage(floppyImage.asOutParam());
4299 if (floppyImage)
4300 {
4301 BOOL fAccessible;
4302 HRESULT rc = floppyImage->COMGETTER(Accessible)(&fAccessible);
4303 CheckComRCReturnRC (rc);
4304 if (!fAccessible)
4305 {
4306 Bstr filePath;
4307 floppyImage->COMGETTER(FilePath)(filePath.asOutParam());
4308 /// @todo (r=dmik) grab the last access error once
4309 // IDVDImage::lastAccessError is there
4310 return setError (E_FAIL,
4311 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"),
4312 filePath.raw());
4313 }
4314 }
4315
4316 /* now the network cards will undergo a quick consistency check */
4317 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
4318 {
4319 ComPtr<INetworkAdapter> adapter;
4320 mMachine->GetNetworkAdapter (slot, adapter.asOutParam());
4321 BOOL enabled = FALSE;
4322 adapter->COMGETTER(Enabled) (&enabled);
4323 if (!enabled)
4324 continue;
4325
4326 NetworkAttachmentType_T netattach;
4327 adapter->COMGETTER(AttachmentType)(&netattach);
4328 switch (netattach)
4329 {
4330 case NetworkAttachmentType_HostInterface:
4331 {
4332#ifdef RT_OS_WINDOWS
4333 /* a valid host interface must have been set */
4334 Bstr hostif;
4335 adapter->COMGETTER(HostInterface)(hostif.asOutParam());
4336 if (!hostif)
4337 {
4338 return setError (E_FAIL,
4339 tr ("VM cannot start because host interface networking "
4340 "requires a host interface name to be set"));
4341 }
4342 ComPtr<IVirtualBox> virtualBox;
4343 mMachine->COMGETTER(Parent)(virtualBox.asOutParam());
4344 ComPtr<IHost> host;
4345 virtualBox->COMGETTER(Host)(host.asOutParam());
4346 ComPtr<IHostNetworkInterfaceCollection> coll;
4347 host->COMGETTER(NetworkInterfaces)(coll.asOutParam());
4348 ComPtr<IHostNetworkInterface> hostInterface;
4349 if (!SUCCEEDED(coll->FindByName(hostif, hostInterface.asOutParam())))
4350 {
4351 return setError (E_FAIL,
4352 tr ("VM cannot start because the host interface '%ls' "
4353 "does not exist"),
4354 hostif.raw());
4355 }
4356#endif /* RT_OS_WINDOWS */
4357 break;
4358 }
4359 default:
4360 break;
4361 }
4362 }
4363
4364 /* Read console data stored in the saved state file (if not yet done) */
4365 {
4366 HRESULT rc = loadDataFromSavedState();
4367 CheckComRCReturnRC (rc);
4368 }
4369
4370 /* Check all types of shared folders and compose a single list */
4371 SharedFolderDataMap sharedFolders;
4372 {
4373 /* first, insert global folders */
4374 for (SharedFolderDataMap::const_iterator it = mGlobalSharedFolders.begin();
4375 it != mGlobalSharedFolders.end(); ++ it)
4376 sharedFolders [it->first] = it->second;
4377
4378 /* second, insert machine folders */
4379 for (SharedFolderDataMap::const_iterator it = mMachineSharedFolders.begin();
4380 it != mMachineSharedFolders.end(); ++ it)
4381 sharedFolders [it->first] = it->second;
4382
4383 /* third, insert console folders */
4384 for (SharedFolderMap::const_iterator it = mSharedFolders.begin();
4385 it != mSharedFolders.end(); ++ it)
4386 sharedFolders [it->first] = SharedFolderData(it->second->hostPath(), it->second->writable());
4387 }
4388
4389 Bstr savedStateFile;
4390
4391 /*
4392 * Saved VMs will have to prove that their saved states are kosher.
4393 */
4394 if (mMachineState == MachineState_Saved)
4395 {
4396 HRESULT rc = mMachine->COMGETTER(StateFilePath) (savedStateFile.asOutParam());
4397 CheckComRCReturnRC (rc);
4398 ComAssertRet (!!savedStateFile, E_FAIL);
4399 int vrc = SSMR3ValidateFile (Utf8Str (savedStateFile));
4400 if (VBOX_FAILURE (vrc))
4401 return setError (E_FAIL,
4402 tr ("VM cannot start because the saved state file '%ls' is invalid (%Vrc). "
4403 "Discard the saved state prior to starting the VM"),
4404 savedStateFile.raw(), vrc);
4405 }
4406
4407 /* create an IProgress object to track progress of this operation */
4408 ComObjPtr <Progress> progress;
4409 progress.createObject();
4410 Bstr progressDesc;
4411 if (mMachineState == MachineState_Saved)
4412 progressDesc = tr ("Restoring virtual machine");
4413 else
4414 progressDesc = tr ("Starting virtual machine");
4415 progress->init (static_cast <IConsole *> (this),
4416 progressDesc, FALSE /* aCancelable */);
4417
4418 /* pass reference to caller if requested */
4419 if (aProgress)
4420 progress.queryInterfaceTo (aProgress);
4421
4422 /* setup task object and thread to carry out the operation asynchronously */
4423 std::auto_ptr <VMPowerUpTask> task (new VMPowerUpTask (this, progress));
4424 ComAssertComRCRetRC (task->rc());
4425
4426 task->mSetVMErrorCallback = setVMErrorCallback;
4427 task->mConfigConstructor = configConstructor;
4428 task->mSharedFolders = sharedFolders;
4429 task->mStartPaused = aPaused;
4430 if (mMachineState == MachineState_Saved)
4431 task->mSavedStateFile = savedStateFile;
4432
4433 HRESULT hrc = consoleInitReleaseLog (mMachine);
4434 if (FAILED (hrc))
4435 return hrc;
4436
4437 int vrc = RTThreadCreate (NULL, Console::powerUpThread, (void *) task.get(),
4438 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMPowerUp");
4439
4440 ComAssertMsgRCRet (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc),
4441 E_FAIL);
4442
4443 /* task is now owned by powerUpThread(), so release it */
4444 task.release();
4445
4446 if (mMachineState == MachineState_Saved)
4447 setMachineState (MachineState_Restoring);
4448 else
4449 setMachineState (MachineState_Starting);
4450
4451 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
4452 LogFlowThisFuncLeave();
4453 return S_OK;
4454}
4455
4456/**
4457 * Internal power off worker routine.
4458 *
4459 * This method may be called only at certain places with the folliwing meaning
4460 * as shown below:
4461 *
4462 * - if the machine state is either Running or Paused, a normal
4463 * Console-initiated powerdown takes place (e.g. PowerDown());
4464 * - if the machine state is Saving, saveStateThread() has successfully done its
4465 * job;
4466 * - if the machine state is Starting or Restoring, powerUpThread() has failed
4467 * to start/load the VM;
4468 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
4469 * as a result of the powerDown() call).
4470 *
4471 * Calling it in situations other than the above will cause unexpected behavior.
4472 *
4473 * Note that this method should be the only one that destroys mpVM and sets it
4474 * to NULL.
4475 *
4476 * @param aProgress Progress object to run (may be NULL).
4477 *
4478 * @note Locks this object for writing.
4479 *
4480 * @note Never call this method from a thread that called addVMCaller() or
4481 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
4482 * release(). Otherwise it will deadlock.
4483 */
4484HRESULT Console::powerDown (Progress *aProgress /*= NULL*/)
4485{
4486 LogFlowThisFuncEnter();
4487
4488 AutoCaller autoCaller (this);
4489 AssertComRCReturnRC (autoCaller.rc());
4490
4491 AutoWriteLock alock (this);
4492
4493 /* Total # of steps for the progress object. Must correspond to the
4494 * number of "advance percent count" comments in this method! */
4495 enum { StepCount = 7 };
4496 /* current step */
4497 size_t step = 0;
4498
4499 HRESULT rc = S_OK;
4500 int vrc = VINF_SUCCESS;
4501
4502 /* sanity */
4503 Assert (mVMDestroying == false);
4504
4505 Assert (mpVM != NULL);
4506
4507 AssertMsg (mMachineState == MachineState_Running ||
4508 mMachineState == MachineState_Paused ||
4509 mMachineState == MachineState_Stuck ||
4510 mMachineState == MachineState_Saving ||
4511 mMachineState == MachineState_Starting ||
4512 mMachineState == MachineState_Restoring ||
4513 mMachineState == MachineState_Stopping,
4514 ("Invalid machine state: %d\n", mMachineState));
4515
4516 LogRel (("Console::powerDown(): A request to power off the VM has been "
4517 "issued (mMachineState=%d, InUninit=%d)\n",
4518 mMachineState, autoCaller.state() == InUninit));
4519
4520 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
4521 * VM has already powered itself off in vmstateChangeCallback() and is just
4522 * notifying Console about that. In case of Starting or Restoring,
4523 * powerUpThread() is calling us on failure, so the VM is already off at
4524 * that point. */
4525 if (!mVMPoweredOff &&
4526 (mMachineState == MachineState_Starting ||
4527 mMachineState == MachineState_Restoring))
4528 mVMPoweredOff = true;
4529
4530 /* go to Stopping state if not already there. Note that we don't go from
4531 * Saving to Stopping because vmstateChangeCallback() needs it to set the
4532 * state to Saved on VMSTATE_TERMINATED. In terms of protecting from
4533 * inappropriate operations while leaving the lock below, Saving should be
4534 * fine too */
4535 if (mMachineState != MachineState_Saving &&
4536 mMachineState != MachineState_Stopping)
4537 setMachineState (MachineState_Stopping);
4538
4539 /* ----------------------------------------------------------------------
4540 * DONE with necessary state changes, perform the power down actions (it's
4541 * safe to leave the object lock now if needed)
4542 * ---------------------------------------------------------------------- */
4543
4544 /* Stop the VRDP server to prevent new clients connection while VM is being
4545 * powered off. */
4546 if (mConsoleVRDPServer)
4547 {
4548 LogFlowThisFunc (("Stopping VRDP server...\n"));
4549
4550 /* Leave the lock since EMT will call us back as addVMCaller()
4551 * in updateDisplayData(). */
4552 alock.leave();
4553
4554 mConsoleVRDPServer->Stop();
4555
4556 alock.enter();
4557 }
4558
4559 /* advance percent count */
4560 if (aProgress)
4561 aProgress->notifyProgress (99 * (++ step) / StepCount );
4562
4563#ifdef VBOX_WITH_HGCM
4564
4565 /* Shutdown HGCM services before stopping the guest, because they might
4566 * need a cleanup. */
4567 if (mVMMDev)
4568 {
4569 LogFlowThisFunc (("Shutdown HGCM...\n"));
4570
4571 /* Leave the lock since EMT will call us back as addVMCaller() */
4572 alock.leave();
4573
4574 mVMMDev->hgcmShutdown ();
4575
4576 alock.enter();
4577 }
4578
4579 /* advance percent count */
4580 if (aProgress)
4581 aProgress->notifyProgress (99 * (++ step) / StepCount );
4582
4583# ifdef VBOX_WITH_GUEST_PROPS
4584
4585 /* Save all guest property store entries to the machine XML file */
4586 PCFGMNODE pValues = CFGMR3GetChild (CFGMR3GetRoot (mpVM), "GuestProps/Values/");
4587 PCFGMNODE pTimestamps = CFGMR3GetChild (CFGMR3GetRoot (mpVM), "GuestProps/Timestamps/");
4588 PCFGMNODE pFlags = CFGMR3GetChild (CFGMR3GetRoot (mpVM), "GuestProps/Flags/");
4589
4590 /* Count the number of entries we have */
4591 unsigned cValues = 0;
4592 PCFGMLEAF pValue;
4593 for (pValue = CFGMR3GetFirstValue (pValues); pValue != NULL;
4594 pValue = CFGMR3GetNextValue (pValue))
4595 {
4596 char szPropName[guestProp::MAX_NAME_LEN + 1];
4597 vrc = CFGMR3GetValueName (pValue, szPropName, sizeof(szPropName));
4598 if (RT_SUCCESS(vrc))
4599 {
4600 /* Do not send transient properties unless we are saving state */
4601 uint32_t fFlags = guestProp::NILFLAG;
4602 CFGMR3QueryU32 (pFlags, szPropName, &fFlags);
4603 if (!(fFlags & guestProp::TRANSIENT) ||
4604 (mMachineState == MachineState_Saving))
4605 ++cValues;
4606 }
4607 }
4608
4609 /* And pack them into safe arrays */
4610 com::SafeArray <BSTR> names(cValues);
4611 com::SafeArray <BSTR> values(cValues);
4612 com::SafeArray <ULONG64> timestamps(cValues);
4613 com::SafeArray <BSTR> flags(cValues);
4614 pValue = CFGMR3GetFirstValue (pValues);
4615
4616 vrc = VINF_SUCCESS;
4617 unsigned iProp = 0;
4618 while (pValue != NULL && RT_SUCCESS (vrc))
4619 {
4620 using namespace guestProp;
4621
4622 char szPropName [MAX_NAME_LEN + 1];
4623 char szPropValue [MAX_VALUE_LEN + 1];
4624 char szPropFlags [MAX_FLAGS_LEN + 1];
4625 ULONG64 u64Timestamp = 0; /* default */
4626 vrc = CFGMR3GetValueName (pValue, szPropName, sizeof (szPropName));
4627 if (RT_SUCCESS(vrc))
4628 vrc = CFGMR3QueryString (pValues, szPropName, szPropValue,
4629 sizeof (szPropValue));
4630 if (RT_SUCCESS(vrc))
4631 {
4632 uint32_t fFlags = NILFLAG;
4633 CFGMR3QueryU32 (pFlags, szPropName, &fFlags);
4634 /* Skip transient properties unless we are saving state */
4635 if (!(fFlags & TRANSIENT) ||
4636 (mMachineState == MachineState_Saving))
4637 {
4638 writeFlags(fFlags, szPropFlags);
4639 CFGMR3QueryU64 (pTimestamps, szPropName, &u64Timestamp);
4640 Bstr(szPropName).cloneTo(&names[iProp]);
4641 Bstr(szPropValue).cloneTo(&values[iProp]);
4642 timestamps[iProp] = u64Timestamp;
4643 Bstr(szPropFlags).cloneTo(&flags[iProp]);
4644 ++iProp;
4645 if (iProp >= cValues)
4646 vrc = VERR_TOO_MUCH_DATA;
4647 }
4648 pValue = CFGMR3GetNextValue (pValue);
4649 }
4650 }
4651
4652 if (RT_SUCCESS(vrc) || (VERR_TOO_MUCH_DATA == vrc))
4653 {
4654 /* PushGuestProperties() calls DiscardSettings(), which calls us back */
4655 alock.leave();
4656 mControl->PushGuestProperties (ComSafeArrayAsInParam (names),
4657 ComSafeArrayAsInParam (values),
4658 ComSafeArrayAsInParam (timestamps),
4659 ComSafeArrayAsInParam (flags));
4660 alock.enter();
4661 }
4662
4663 /* advance percent count */
4664 if (aProgress)
4665 aProgress->notifyProgress (99 * (++ step) / StepCount );
4666
4667# endif /* VBOX_WITH_GUEST_PROPS defined */
4668
4669#endif /* VBOX_WITH_HGCM */
4670
4671 /* ----------------------------------------------------------------------
4672 * Now, wait for all mpVM callers to finish their work if there are still
4673 * some on other threads. NO methods that need mpVM (or initiate other calls
4674 * that need it) may be called after this point
4675 * ---------------------------------------------------------------------- */
4676
4677 if (mVMCallers > 0)
4678 {
4679 /* go to the destroying state to prevent from adding new callers */
4680 mVMDestroying = true;
4681
4682 /* lazy creation */
4683 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
4684 RTSemEventCreate (&mVMZeroCallersSem);
4685
4686 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
4687 mVMCallers));
4688
4689 alock.leave();
4690
4691 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
4692
4693 alock.enter();
4694 }
4695
4696 /* advance percent count */
4697 if (aProgress)
4698 aProgress->notifyProgress (99 * (++ step) / StepCount );
4699
4700 vrc = VINF_SUCCESS;
4701
4702 /* Power off the VM if not already done that */
4703 if (!mVMPoweredOff)
4704 {
4705 LogFlowThisFunc (("Powering off the VM...\n"));
4706
4707 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
4708 alock.leave();
4709
4710 vrc = VMR3PowerOff (mpVM);
4711
4712 /* Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
4713 * VM-(guest-)initiated power off happened in parallel a ms before this
4714 * call. So far, we let this error pop up on the user's side. */
4715
4716 alock.enter();
4717
4718 }
4719 else
4720 {
4721 /* reset the flag for further re-use */
4722 mVMPoweredOff = false;
4723 }
4724
4725 /* advance percent count */
4726 if (aProgress)
4727 aProgress->notifyProgress (99 * (++ step) / StepCount );
4728
4729 LogFlowThisFunc (("Ready for VM destruction.\n"));
4730
4731 /* If we are called from Console::uninit(), then try to destroy the VM even
4732 * on failure (this will most likely fail too, but what to do?..) */
4733 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
4734 {
4735 /* If the machine has an USB comtroller, release all USB devices
4736 * (symmetric to the code in captureUSBDevices()) */
4737 bool fHasUSBController = false;
4738 {
4739 PPDMIBASE pBase;
4740 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4741 if (VBOX_SUCCESS (vrc))
4742 {
4743 fHasUSBController = true;
4744 detachAllUSBDevices (false /* aDone */);
4745 }
4746 }
4747
4748 /* Now we've got to destroy the VM as well. (mpVM is not valid beyond
4749 * this point). We leave the lock before calling VMR3Destroy() because
4750 * it will result into calling destructors of drivers associated with
4751 * Console children which may in turn try to lock Console (e.g. by
4752 * instantiating SafeVMPtr to access mpVM). It's safe here because
4753 * mVMDestroying is set which should prevent any activity. */
4754
4755 /* Set mpVM to NULL early just in case if some old code is not using
4756 * addVMCaller()/releaseVMCaller(). */
4757 PVM pVM = mpVM;
4758 mpVM = NULL;
4759
4760 LogFlowThisFunc (("Destroying the VM...\n"));
4761
4762 alock.leave();
4763
4764 vrc = VMR3Destroy (pVM);
4765
4766 /* take the lock again */
4767 alock.enter();
4768
4769 /* advance percent count */
4770 if (aProgress)
4771 aProgress->notifyProgress (99 * (++ step) / StepCount );
4772
4773 if (VBOX_SUCCESS (vrc))
4774 {
4775 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
4776 mMachineState));
4777 /* Note: the Console-level machine state change happens on the
4778 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
4779 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
4780 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
4781 * occured yet. This is okay, because mMachineState is already
4782 * Stopping in this case, so any other attempt to call PowerDown()
4783 * will be rejected. */
4784 }
4785 else
4786 {
4787 /* bad bad bad, but what to do? */
4788 mpVM = pVM;
4789 rc = setError (E_FAIL,
4790 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
4791 }
4792
4793 /* Complete the detaching of the USB devices. */
4794 if (fHasUSBController)
4795 detachAllUSBDevices (true /* aDone */);
4796
4797 /* advance percent count */
4798 if (aProgress)
4799 aProgress->notifyProgress (99 * (++ step) / StepCount );
4800 }
4801 else
4802 {
4803 rc = setError (E_FAIL,
4804 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
4805 }
4806
4807 /* Finished with destruction. Note that if something impossible happened and
4808 * we've failed to destroy the VM, mVMDestroying will remain true and
4809 * mMachineState will be something like Stopping, so most Console methods
4810 * will return an error to the caller. */
4811 if (mpVM == NULL)
4812 mVMDestroying = false;
4813
4814 if (SUCCEEDED (rc))
4815 {
4816 /* uninit dynamically allocated members of mCallbackData */
4817 if (mCallbackData.mpsc.valid)
4818 {
4819 if (mCallbackData.mpsc.shape != NULL)
4820 RTMemFree (mCallbackData.mpsc.shape);
4821 }
4822 memset (&mCallbackData, 0, sizeof (mCallbackData));
4823 }
4824
4825 /* complete the progress */
4826 if (aProgress)
4827 aProgress->notifyComplete (rc);
4828
4829 LogFlowThisFuncLeave();
4830 return rc;
4831}
4832
4833/**
4834 * @note Locks this object for writing.
4835 */
4836HRESULT Console::setMachineState (MachineState_T aMachineState,
4837 bool aUpdateServer /* = true */)
4838{
4839 AutoCaller autoCaller (this);
4840 AssertComRCReturnRC (autoCaller.rc());
4841
4842 AutoWriteLock alock (this);
4843
4844 HRESULT rc = S_OK;
4845
4846 if (mMachineState != aMachineState)
4847 {
4848 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4849 mMachineState = aMachineState;
4850
4851 /// @todo (dmik)
4852 // possibly, we need to redo onStateChange() using the dedicated
4853 // Event thread, like it is done in VirtualBox. This will make it
4854 // much safer (no deadlocks possible if someone tries to use the
4855 // console from the callback), however, listeners will lose the
4856 // ability to synchronously react to state changes (is it really
4857 // necessary??)
4858 LogFlowThisFunc (("Doing onStateChange()...\n"));
4859 onStateChange (aMachineState);
4860 LogFlowThisFunc (("Done onStateChange()\n"));
4861
4862 if (aUpdateServer)
4863 {
4864 /*
4865 * Server notification MUST be done from under the lock; otherwise
4866 * the machine state here and on the server might go out of sync, that
4867 * can lead to various unexpected results (like the machine state being
4868 * >= MachineState_Running on the server, while the session state is
4869 * already SessionState_Closed at the same time there).
4870 *
4871 * Cross-lock conditions should be carefully watched out: calling
4872 * UpdateState we will require Machine and SessionMachine locks
4873 * (remember that here we're holding the Console lock here, and
4874 * also all locks that have been entered by the thread before calling
4875 * this method).
4876 */
4877 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4878 rc = mControl->UpdateState (aMachineState);
4879 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4880 }
4881 }
4882
4883 return rc;
4884}
4885
4886/**
4887 * Searches for a shared folder with the given logical name
4888 * in the collection of shared folders.
4889 *
4890 * @param aName logical name of the shared folder
4891 * @param aSharedFolder where to return the found object
4892 * @param aSetError whether to set the error info if the folder is
4893 * not found
4894 * @return
4895 * S_OK when found or E_INVALIDARG when not found
4896 *
4897 * @note The caller must lock this object for writing.
4898 */
4899HRESULT Console::findSharedFolder (const BSTR aName,
4900 ComObjPtr <SharedFolder> &aSharedFolder,
4901 bool aSetError /* = false */)
4902{
4903 /* sanity check */
4904 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4905
4906 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4907 if (it != mSharedFolders.end())
4908 {
4909 aSharedFolder = it->second;
4910 return S_OK;
4911 }
4912
4913 if (aSetError)
4914 setError (E_INVALIDARG,
4915 tr ("Could not find a shared folder named '%ls'."), aName);
4916
4917 return E_INVALIDARG;
4918}
4919
4920/**
4921 * Fetches the list of global or machine shared folders from the server.
4922 *
4923 * @param aGlobal true to fetch global folders.
4924 *
4925 * @note The caller must lock this object for writing.
4926 */
4927HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4928{
4929 /* sanity check */
4930 AssertReturn (AutoCaller (this).state() == InInit ||
4931 isWriteLockOnCurrentThread(), E_FAIL);
4932
4933 /* protect mpVM (if not NULL) */
4934 AutoVMCallerQuietWeak autoVMCaller (this);
4935
4936 HRESULT rc = S_OK;
4937
4938 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4939
4940 if (aGlobal)
4941 {
4942 /// @todo grab & process global folders when they are done
4943 }
4944 else
4945 {
4946 SharedFolderDataMap oldFolders;
4947 if (online)
4948 oldFolders = mMachineSharedFolders;
4949
4950 mMachineSharedFolders.clear();
4951
4952 ComPtr <ISharedFolderCollection> coll;
4953 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
4954 AssertComRCReturnRC (rc);
4955
4956 ComPtr <ISharedFolderEnumerator> en;
4957 rc = coll->Enumerate (en.asOutParam());
4958 AssertComRCReturnRC (rc);
4959
4960 BOOL hasMore = FALSE;
4961 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
4962 {
4963 ComPtr <ISharedFolder> folder;
4964 rc = en->GetNext (folder.asOutParam());
4965 CheckComRCBreakRC (rc);
4966
4967 Bstr name;
4968 Bstr hostPath;
4969 BOOL writable;
4970
4971 rc = folder->COMGETTER(Name) (name.asOutParam());
4972 CheckComRCBreakRC (rc);
4973 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
4974 CheckComRCBreakRC (rc);
4975 rc = folder->COMGETTER(Writable) (&writable);
4976
4977 mMachineSharedFolders.insert (std::make_pair (name, SharedFolderData (hostPath, writable)));
4978
4979 /* send changes to HGCM if the VM is running */
4980 /// @todo report errors as runtime warnings through VMSetError
4981 if (online)
4982 {
4983 SharedFolderDataMap::iterator it = oldFolders.find (name);
4984 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
4985 {
4986 /* a new machine folder is added or
4987 * the existing machine folder is changed */
4988 if (mSharedFolders.find (name) != mSharedFolders.end())
4989 ; /* the console folder exists, nothing to do */
4990 else
4991 {
4992 /* remove the old machhine folder (when changed)
4993 * or the global folder if any (when new) */
4994 if (it != oldFolders.end() ||
4995 mGlobalSharedFolders.find (name) !=
4996 mGlobalSharedFolders.end())
4997 rc = removeSharedFolder (name);
4998 /* create the new machine folder */
4999 rc = createSharedFolder (name, SharedFolderData (hostPath, writable));
5000 }
5001 }
5002 /* forget the processed (or identical) folder */
5003 if (it != oldFolders.end())
5004 oldFolders.erase (it);
5005
5006 rc = S_OK;
5007 }
5008 }
5009
5010 AssertComRCReturnRC (rc);
5011
5012 /* process outdated (removed) folders */
5013 /// @todo report errors as runtime warnings through VMSetError
5014 if (online)
5015 {
5016 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
5017 it != oldFolders.end(); ++ it)
5018 {
5019 if (mSharedFolders.find (it->first) != mSharedFolders.end())
5020 ; /* the console folder exists, nothing to do */
5021 else
5022 {
5023 /* remove the outdated machine folder */
5024 rc = removeSharedFolder (it->first);
5025 /* create the global folder if there is any */
5026 SharedFolderDataMap::const_iterator git =
5027 mGlobalSharedFolders.find (it->first);
5028 if (git != mGlobalSharedFolders.end())
5029 rc = createSharedFolder (git->first, git->second);
5030 }
5031 }
5032
5033 rc = S_OK;
5034 }
5035 }
5036
5037 return rc;
5038}
5039
5040/**
5041 * Searches for a shared folder with the given name in the list of machine
5042 * shared folders and then in the list of the global shared folders.
5043 *
5044 * @param aName Name of the folder to search for.
5045 * @param aIt Where to store the pointer to the found folder.
5046 * @return @c true if the folder was found and @c false otherwise.
5047 *
5048 * @note The caller must lock this object for reading.
5049 */
5050bool Console::findOtherSharedFolder (INPTR BSTR aName,
5051 SharedFolderDataMap::const_iterator &aIt)
5052{
5053 /* sanity check */
5054 AssertReturn (isWriteLockOnCurrentThread(), false);
5055
5056 /* first, search machine folders */
5057 aIt = mMachineSharedFolders.find (aName);
5058 if (aIt != mMachineSharedFolders.end())
5059 return true;
5060
5061 /* second, search machine folders */
5062 aIt = mGlobalSharedFolders.find (aName);
5063 if (aIt != mGlobalSharedFolders.end())
5064 return true;
5065
5066 return false;
5067}
5068
5069/**
5070 * Calls the HGCM service to add a shared folder definition.
5071 *
5072 * @param aName Shared folder name.
5073 * @param aHostPath Shared folder path.
5074 *
5075 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5076 * @note Doesn't lock anything.
5077 */
5078HRESULT Console::createSharedFolder (INPTR BSTR aName, SharedFolderData aData)
5079{
5080 ComAssertRet (aName && *aName, E_FAIL);
5081 ComAssertRet (aData.mHostPath, E_FAIL);
5082
5083 /* sanity checks */
5084 AssertReturn (mpVM, E_FAIL);
5085 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
5086
5087 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
5088 SHFLSTRING *pFolderName, *pMapName;
5089 size_t cbString;
5090
5091 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
5092
5093 cbString = (RTUtf16Len (aData.mHostPath) + 1) * sizeof (RTUTF16);
5094 if (cbString >= UINT16_MAX)
5095 return setError (E_INVALIDARG, tr ("The name is too long"));
5096 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
5097 Assert (pFolderName);
5098 memcpy (pFolderName->String.ucs2, aData.mHostPath, cbString);
5099
5100 pFolderName->u16Size = (uint16_t)cbString;
5101 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5102
5103 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5104 parms[0].u.pointer.addr = pFolderName;
5105 parms[0].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
5106
5107 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
5108 if (cbString >= UINT16_MAX)
5109 {
5110 RTMemFree (pFolderName);
5111 return setError (E_INVALIDARG, tr ("The host path is too long"));
5112 }
5113 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
5114 Assert (pMapName);
5115 memcpy (pMapName->String.ucs2, aName, cbString);
5116
5117 pMapName->u16Size = (uint16_t)cbString;
5118 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
5119
5120 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5121 parms[1].u.pointer.addr = pMapName;
5122 parms[1].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
5123
5124 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
5125 parms[2].u.uint32 = aData.mWritable;
5126
5127 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
5128 SHFL_FN_ADD_MAPPING,
5129 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
5130 RTMemFree (pFolderName);
5131 RTMemFree (pMapName);
5132
5133 if (VBOX_FAILURE (vrc))
5134 return setError (E_FAIL,
5135 tr ("Could not create a shared folder '%ls' "
5136 "mapped to '%ls' (%Vrc)"),
5137 aName, aData.mHostPath.raw(), vrc);
5138
5139 return S_OK;
5140}
5141
5142/**
5143 * Calls the HGCM service to remove the shared folder definition.
5144 *
5145 * @param aName Shared folder name.
5146 *
5147 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5148 * @note Doesn't lock anything.
5149 */
5150HRESULT Console::removeSharedFolder (INPTR BSTR aName)
5151{
5152 ComAssertRet (aName && *aName, E_FAIL);
5153
5154 /* sanity checks */
5155 AssertReturn (mpVM, E_FAIL);
5156 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
5157
5158 VBOXHGCMSVCPARM parms;
5159 SHFLSTRING *pMapName;
5160 size_t cbString;
5161
5162 Log (("Removing shared folder '%ls'\n", aName));
5163
5164 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
5165 if (cbString >= UINT16_MAX)
5166 return setError (E_INVALIDARG, tr ("The name is too long"));
5167 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
5168 Assert (pMapName);
5169 memcpy (pMapName->String.ucs2, aName, cbString);
5170
5171 pMapName->u16Size = (uint16_t)cbString;
5172 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
5173
5174 parms.type = VBOX_HGCM_SVC_PARM_PTR;
5175 parms.u.pointer.addr = pMapName;
5176 parms.u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
5177
5178 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
5179 SHFL_FN_REMOVE_MAPPING,
5180 1, &parms);
5181 RTMemFree(pMapName);
5182 if (VBOX_FAILURE (vrc))
5183 return setError (E_FAIL,
5184 tr ("Could not remove the shared folder '%ls' (%Vrc)"),
5185 aName, vrc);
5186
5187 return S_OK;
5188}
5189
5190/**
5191 * VM state callback function. Called by the VMM
5192 * using its state machine states.
5193 *
5194 * Primarily used to handle VM initiated power off, suspend and state saving,
5195 * but also for doing termination completed work (VMSTATE_TERMINATE).
5196 *
5197 * In general this function is called in the context of the EMT.
5198 *
5199 * @param aVM The VM handle.
5200 * @param aState The new state.
5201 * @param aOldState The old state.
5202 * @param aUser The user argument (pointer to the Console object).
5203 *
5204 * @note Locks the Console object for writing.
5205 */
5206DECLCALLBACK(void)
5207Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
5208 void *aUser)
5209{
5210 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
5211 aOldState, aState, aVM));
5212
5213 Console *that = static_cast <Console *> (aUser);
5214 AssertReturnVoid (that);
5215
5216 AutoCaller autoCaller (that);
5217
5218 /* Note that we must let this method proceed even if Console::uninit() has
5219 * been already called. In such case this VMSTATE change is a result of:
5220 * 1) powerDown() called from uninit() itself, or
5221 * 2) VM-(guest-)initiated power off. */
5222 AssertReturnVoid (autoCaller.isOk() ||
5223 autoCaller.state() == InUninit);
5224
5225 switch (aState)
5226 {
5227 /*
5228 * The VM has terminated
5229 */
5230 case VMSTATE_OFF:
5231 {
5232 AutoWriteLock alock (that);
5233
5234 if (that->mVMStateChangeCallbackDisabled)
5235 break;
5236
5237 /* Do we still think that it is running? It may happen if this is a
5238 * VM-(guest-)initiated shutdown/poweroff.
5239 */
5240 if (that->mMachineState != MachineState_Stopping &&
5241 that->mMachineState != MachineState_Saving &&
5242 that->mMachineState != MachineState_Restoring)
5243 {
5244 LogFlowFunc (("VM has powered itself off but Console still "
5245 "thinks it is running. Notifying.\n"));
5246
5247 /* prevent powerDown() from calling VMR3PowerOff() again */
5248 Assert (that->mVMPoweredOff == false);
5249 that->mVMPoweredOff = true;
5250
5251 /* we are stopping now */
5252 that->setMachineState (MachineState_Stopping);
5253
5254 /* Setup task object and thread to carry out the operation
5255 * asynchronously (if we call powerDown() right here but there
5256 * is one or more mpVM callers (added with addVMCaller()) we'll
5257 * deadlock).
5258 */
5259 std::auto_ptr <VMProgressTask> task (
5260 new VMProgressTask (that, NULL /* aProgress */,
5261 true /* aUsesVMPtr */));
5262
5263 /* If creating a task is falied, this can currently mean one of
5264 * two: either Console::uninit() has been called just a ms
5265 * before (so a powerDown() call is already on the way), or
5266 * powerDown() itself is being already executed. Just do
5267 * nothing.
5268 */
5269 if (!task->isOk())
5270 {
5271 LogFlowFunc (("Console is already being uninitialized.\n"));
5272 break;
5273 }
5274
5275 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
5276 (void *) task.get(), 0,
5277 RTTHREADTYPE_MAIN_WORKER, 0,
5278 "VMPowerDown");
5279
5280 AssertMsgRCBreak (vrc,
5281 ("Could not create VMPowerDown thread (%Vrc)\n", vrc));
5282
5283 /* task is now owned by powerDownThread(), so release it */
5284 task.release();
5285 }
5286 break;
5287 }
5288
5289 /* The VM has been completely destroyed.
5290 *
5291 * Note: This state change can happen at two points:
5292 * 1) At the end of VMR3Destroy() if it was not called from EMT.
5293 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
5294 * called by EMT.
5295 */
5296 case VMSTATE_TERMINATED:
5297 {
5298 AutoWriteLock alock (that);
5299
5300 if (that->mVMStateChangeCallbackDisabled)
5301 break;
5302
5303 /* Terminate host interface networking. If aVM is NULL, we've been
5304 * manually called from powerUpThread() either before calling
5305 * VMR3Create() or after VMR3Create() failed, so no need to touch
5306 * networking.
5307 */
5308 if (aVM)
5309 that->powerDownHostInterfaces();
5310
5311 /* From now on the machine is officially powered down or remains in
5312 * the Saved state.
5313 */
5314 switch (that->mMachineState)
5315 {
5316 default:
5317 AssertFailed();
5318 /* fall through */
5319 case MachineState_Stopping:
5320 /* successfully powered down */
5321 that->setMachineState (MachineState_PoweredOff);
5322 break;
5323 case MachineState_Saving:
5324 /* successfully saved (note that the machine is already in
5325 * the Saved state on the server due to EndSavingState()
5326 * called from saveStateThread(), so only change the local
5327 * state) */
5328 that->setMachineStateLocally (MachineState_Saved);
5329 break;
5330 case MachineState_Starting:
5331 /* failed to start, but be patient: set back to PoweredOff
5332 * (for similarity with the below) */
5333 that->setMachineState (MachineState_PoweredOff);
5334 break;
5335 case MachineState_Restoring:
5336 /* failed to load the saved state file, but be patient: set
5337 * back to Saved (to preserve the saved state file) */
5338 that->setMachineState (MachineState_Saved);
5339 break;
5340 }
5341
5342 break;
5343 }
5344
5345 case VMSTATE_SUSPENDED:
5346 {
5347 if (aOldState == VMSTATE_RUNNING)
5348 {
5349 AutoWriteLock alock (that);
5350
5351 if (that->mVMStateChangeCallbackDisabled)
5352 break;
5353
5354 /* Change the machine state from Running to Paused */
5355 Assert (that->mMachineState == MachineState_Running);
5356 that->setMachineState (MachineState_Paused);
5357 }
5358
5359 break;
5360 }
5361
5362 case VMSTATE_RUNNING:
5363 {
5364 if (aOldState == VMSTATE_CREATED ||
5365 aOldState == VMSTATE_SUSPENDED)
5366 {
5367 AutoWriteLock alock (that);
5368
5369 if (that->mVMStateChangeCallbackDisabled)
5370 break;
5371
5372 /* Change the machine state from Starting, Restoring or Paused
5373 * to Running */
5374 Assert ( ( ( that->mMachineState == MachineState_Starting
5375 || that->mMachineState == MachineState_Paused)
5376 && aOldState == VMSTATE_CREATED)
5377 || ( ( that->mMachineState == MachineState_Restoring
5378 || that->mMachineState == MachineState_Paused)
5379 && aOldState == VMSTATE_SUSPENDED));
5380
5381 that->setMachineState (MachineState_Running);
5382 }
5383
5384 break;
5385 }
5386
5387 case VMSTATE_GURU_MEDITATION:
5388 {
5389 AutoWriteLock alock (that);
5390
5391 if (that->mVMStateChangeCallbackDisabled)
5392 break;
5393
5394 /* Guru respects only running VMs */
5395 Assert ((that->mMachineState >= MachineState_Running));
5396
5397 that->setMachineState (MachineState_Stuck);
5398
5399 break;
5400 }
5401
5402 default: /* shut up gcc */
5403 break;
5404 }
5405}
5406
5407#ifdef VBOX_WITH_USB
5408
5409/**
5410 * Sends a request to VMM to attach the given host device.
5411 * After this method succeeds, the attached device will appear in the
5412 * mUSBDevices collection.
5413 *
5414 * @param aHostDevice device to attach
5415 *
5416 * @note Synchronously calls EMT.
5417 * @note Must be called from under this object's lock.
5418 */
5419HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, ULONG aMaskedIfs)
5420{
5421 AssertReturn (aHostDevice, E_FAIL);
5422 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5423
5424 /* still want a lock object because we need to leave it */
5425 AutoWriteLock alock (this);
5426
5427 HRESULT hrc;
5428
5429 /*
5430 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
5431 * method in EMT (using usbAttachCallback()).
5432 */
5433 Bstr BstrAddress;
5434 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
5435 ComAssertComRCRetRC (hrc);
5436
5437 Utf8Str Address (BstrAddress);
5438
5439 Guid Uuid;
5440 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
5441 ComAssertComRCRetRC (hrc);
5442
5443 BOOL fRemote = FALSE;
5444 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
5445 ComAssertComRCRetRC (hrc);
5446
5447 /* protect mpVM */
5448 AutoVMCaller autoVMCaller (this);
5449 CheckComRCReturnRC (autoVMCaller.rc());
5450
5451 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
5452 Address.raw(), Uuid.ptr()));
5453
5454 /* leave the lock before a VMR3* call (EMT will call us back)! */
5455 alock.leave();
5456
5457/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5458 PVMREQ pReq = NULL;
5459 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5460 (PFNRT) usbAttachCallback, 6, this, aHostDevice, Uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
5461 if (VBOX_SUCCESS (vrc))
5462 vrc = pReq->iStatus;
5463 VMR3ReqFree (pReq);
5464
5465 /* restore the lock */
5466 alock.enter();
5467
5468 /* hrc is S_OK here */
5469
5470 if (VBOX_FAILURE (vrc))
5471 {
5472 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
5473 Address.raw(), Uuid.ptr(), vrc));
5474
5475 switch (vrc)
5476 {
5477 case VERR_VUSB_NO_PORTS:
5478 hrc = setError (E_FAIL,
5479 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
5480 break;
5481 case VERR_VUSB_USBFS_PERMISSION:
5482 hrc = setError (E_FAIL,
5483 tr ("Not permitted to open the USB device, check usbfs options"));
5484 break;
5485 default:
5486 hrc = setError (E_FAIL,
5487 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
5488 break;
5489 }
5490 }
5491
5492 return hrc;
5493}
5494
5495/**
5496 * USB device attach callback used by AttachUSBDevice().
5497 * Note that AttachUSBDevice() doesn't return until this callback is executed,
5498 * so we don't use AutoCaller and don't care about reference counters of
5499 * interface pointers passed in.
5500 *
5501 * @thread EMT
5502 * @note Locks the console object for writing.
5503 */
5504//static
5505DECLCALLBACK(int)
5506Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
5507{
5508 LogFlowFuncEnter();
5509 LogFlowFunc (("that={%p}\n", that));
5510
5511 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5512
5513 void *pvRemoteBackend = NULL;
5514 if (aRemote)
5515 {
5516 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
5517 Guid guid (*aUuid);
5518
5519 pvRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
5520 if (!pvRemoteBackend)
5521 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
5522 }
5523
5524 USHORT portVersion = 1;
5525 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
5526 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
5527 Assert(portVersion == 1 || portVersion == 2);
5528
5529 int vrc = PDMR3USBCreateProxyDevice (that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
5530 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
5531 if (VBOX_SUCCESS (vrc))
5532 {
5533 /* Create a OUSBDevice and add it to the device list */
5534 ComObjPtr <OUSBDevice> device;
5535 device.createObject();
5536 HRESULT hrc = device->init (aHostDevice);
5537 AssertComRC (hrc);
5538
5539 AutoWriteLock alock (that);
5540 that->mUSBDevices.push_back (device);
5541 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
5542
5543 /* notify callbacks */
5544 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
5545 }
5546
5547 LogFlowFunc (("vrc=%Vrc\n", vrc));
5548 LogFlowFuncLeave();
5549 return vrc;
5550}
5551
5552/**
5553 * Sends a request to VMM to detach the given host device. After this method
5554 * succeeds, the detached device will disappear from the mUSBDevices
5555 * collection.
5556 *
5557 * @param aIt Iterator pointing to the device to detach.
5558 *
5559 * @note Synchronously calls EMT.
5560 * @note Must be called from under this object's lock.
5561 */
5562HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
5563{
5564 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5565
5566 /* still want a lock object because we need to leave it */
5567 AutoWriteLock alock (this);
5568
5569 /* protect mpVM */
5570 AutoVMCaller autoVMCaller (this);
5571 CheckComRCReturnRC (autoVMCaller.rc());
5572
5573 /* if the device is attached, then there must at least one USB hub. */
5574 AssertReturn (PDMR3USBHasHub (mpVM), E_FAIL);
5575
5576 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
5577 (*aIt)->id().raw()));
5578
5579 /* leave the lock before a VMR3* call (EMT will call us back)! */
5580 alock.leave();
5581
5582 PVMREQ pReq;
5583/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5584 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5585 (PFNRT) usbDetachCallback, 4,
5586 this, &aIt, (*aIt)->id().raw());
5587 if (VBOX_SUCCESS (vrc))
5588 vrc = pReq->iStatus;
5589 VMR3ReqFree (pReq);
5590
5591 ComAssertRCRet (vrc, E_FAIL);
5592
5593 return S_OK;
5594}
5595
5596/**
5597 * USB device detach callback used by DetachUSBDevice().
5598 * Note that DetachUSBDevice() doesn't return until this callback is executed,
5599 * so we don't use AutoCaller and don't care about reference counters of
5600 * interface pointers passed in.
5601 *
5602 * @thread EMT
5603 * @note Locks the console object for writing.
5604 */
5605//static
5606DECLCALLBACK(int)
5607Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
5608{
5609 LogFlowFuncEnter();
5610 LogFlowFunc (("that={%p}\n", that));
5611
5612 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5613 ComObjPtr <OUSBDevice> device = **aIt;
5614
5615 /*
5616 * If that was a remote device, release the backend pointer.
5617 * The pointer was requested in usbAttachCallback.
5618 */
5619 BOOL fRemote = FALSE;
5620
5621 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
5622 ComAssertComRC (hrc2);
5623
5624 if (fRemote)
5625 {
5626 Guid guid (*aUuid);
5627 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
5628 }
5629
5630 int vrc = PDMR3USBDetachDevice (that->mpVM, aUuid);
5631
5632 if (VBOX_SUCCESS (vrc))
5633 {
5634 AutoWriteLock alock (that);
5635
5636 /* Remove the device from the collection */
5637 that->mUSBDevices.erase (*aIt);
5638 LogFlowFunc (("Detached device {%Vuuid}\n", device->id().raw()));
5639
5640 /* notify callbacks */
5641 that->onUSBDeviceStateChange (device, false /* aAttached */, NULL);
5642 }
5643
5644 LogFlowFunc (("vrc=%Vrc\n", vrc));
5645 LogFlowFuncLeave();
5646 return vrc;
5647}
5648
5649#endif /* VBOX_WITH_USB */
5650
5651/**
5652 * Call the initialisation script for a dynamic TAP interface.
5653 *
5654 * The initialisation script should create a TAP interface, set it up and write its name to
5655 * standard output followed by a carriage return. Anything further written to standard
5656 * output will be ignored. If it returns a non-zero exit code, or does not write an
5657 * intelligable interface name to standard output, it will be treated as having failed.
5658 * For now, this method only works on Linux.
5659 *
5660 * @returns COM status code
5661 * @param tapDevice string to store the name of the tap device created to
5662 * @param tapSetupApplication the name of the setup script
5663 */
5664HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5665 Bstr &tapSetupApplication)
5666{
5667 LogFlowThisFunc(("\n"));
5668#ifdef RT_OS_LINUX
5669 /* Command line to start the script with. */
5670 char szCommand[4096];
5671 /* Result code */
5672 int rc;
5673
5674 /* Get the script name. */
5675 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5676 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5677 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5678 /*
5679 * Create the process and read its output.
5680 */
5681 Log2(("About to start the TAP setup script with the following command line: %s\n",
5682 szCommand));
5683 FILE *pfScriptHandle = popen(szCommand, "r");
5684 if (pfScriptHandle == 0)
5685 {
5686 int iErr = errno;
5687 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5688 szCommand, strerror(iErr)));
5689 LogFlowThisFunc(("rc=E_FAIL\n"));
5690 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5691 szCommand, strerror(iErr));
5692 }
5693 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5694 if (!isStatic)
5695 {
5696 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5697 interested in the first few (normally 5 or 6) bytes. */
5698 char acBuffer[64];
5699 /* The length of the string returned by the application. We only accept strings of 63
5700 characters or less. */
5701 size_t cBufSize;
5702
5703 /* Read the name of the device from the application. */
5704 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5705 cBufSize = strlen(acBuffer);
5706 /* The script must return the name of the interface followed by a carriage return as the
5707 first line of its output. We need a null-terminated string. */
5708 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5709 {
5710 pclose(pfScriptHandle);
5711 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5712 LogFlowThisFunc(("rc=E_FAIL\n"));
5713 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5714 }
5715 /* Overwrite the terminating newline character. */
5716 acBuffer[cBufSize - 1] = 0;
5717 tapDevice = acBuffer;
5718 }
5719 rc = pclose(pfScriptHandle);
5720 if (!WIFEXITED(rc))
5721 {
5722 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5723 LogFlowThisFunc(("rc=E_FAIL\n"));
5724 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5725 }
5726 if (WEXITSTATUS(rc) != 0)
5727 {
5728 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5729 LogFlowThisFunc(("rc=E_FAIL\n"));
5730 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5731 }
5732 LogFlowThisFunc(("rc=S_OK\n"));
5733 return S_OK;
5734#else /* RT_OS_LINUX not defined */
5735 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5736 return E_NOTIMPL; /* not yet supported */
5737#endif
5738}
5739
5740/**
5741 * Helper function to handle host interface device creation and attachment.
5742 *
5743 * @param networkAdapter the network adapter which attachment should be reset
5744 * @return COM status code
5745 *
5746 * @note The caller must lock this object for writing.
5747 */
5748HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5749{
5750#if !defined(RT_OS_LINUX)
5751 /*
5752 * Nothing to do here.
5753 *
5754 * Note, the reason for this method in the first place a memory / fork
5755 * bug on linux. All this code belongs in DrvTAP and similar places.
5756 */
5757 NOREF(networkAdapter);
5758 return S_OK;
5759
5760#else /* RT_OS_LINUX */
5761 LogFlowThisFunc(("\n"));
5762 /* sanity check */
5763 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5764
5765# ifdef VBOX_STRICT
5766 /* paranoia */
5767 NetworkAttachmentType_T attachment;
5768 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5769 Assert(attachment == NetworkAttachmentType_HostInterface);
5770# endif /* VBOX_STRICT */
5771
5772 HRESULT rc = S_OK;
5773
5774 ULONG slot = 0;
5775 rc = networkAdapter->COMGETTER(Slot)(&slot);
5776 AssertComRC(rc);
5777
5778 /*
5779 * Try get the FD.
5780 */
5781 LONG ltapFD;
5782 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5783 if (SUCCEEDED(rc))
5784 maTapFD[slot] = (RTFILE)ltapFD;
5785 else
5786 maTapFD[slot] = NIL_RTFILE;
5787
5788 /*
5789 * Are we supposed to use an existing TAP interface?
5790 */
5791 if (maTapFD[slot] != NIL_RTFILE)
5792 {
5793 /* nothing to do */
5794 Assert(ltapFD >= 0);
5795 Assert((LONG)maTapFD[slot] == ltapFD);
5796 rc = S_OK;
5797 }
5798 else
5799 {
5800 /*
5801 * Allocate a host interface device
5802 */
5803 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5804 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5805 if (VBOX_SUCCESS(rcVBox))
5806 {
5807 /*
5808 * Set/obtain the tap interface.
5809 */
5810 bool isStatic = false;
5811 struct ifreq IfReq;
5812 memset(&IfReq, 0, sizeof(IfReq));
5813 /* The name of the TAP interface we are using and the TAP setup script resp. */
5814 Bstr tapDeviceName, tapSetupApplication;
5815 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5816 if (FAILED(rc))
5817 {
5818 tapDeviceName.setNull(); /* Is this necessary? */
5819 }
5820 else if (!tapDeviceName.isEmpty())
5821 {
5822 isStatic = true;
5823 /* If we are using a static TAP device then try to open it. */
5824 Utf8Str str(tapDeviceName);
5825 if (str.length() <= sizeof(IfReq.ifr_name))
5826 strcpy(IfReq.ifr_name, str.raw());
5827 else
5828 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5829 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5830 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5831 if (rcVBox != 0)
5832 {
5833 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5834 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5835 tapDeviceName.raw());
5836 }
5837 }
5838 if (SUCCEEDED(rc))
5839 {
5840 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5841 if (tapSetupApplication.isEmpty())
5842 {
5843 if (tapDeviceName.isEmpty())
5844 {
5845 LogRel(("No setup application was supplied for the TAP interface.\n"));
5846 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5847 }
5848 }
5849 else
5850 {
5851 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5852 tapSetupApplication);
5853 }
5854 }
5855 if (SUCCEEDED(rc))
5856 {
5857 if (!isStatic)
5858 {
5859 Utf8Str str(tapDeviceName);
5860 if (str.length() <= sizeof(IfReq.ifr_name))
5861 strcpy(IfReq.ifr_name, str.raw());
5862 else
5863 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5864 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5865 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5866 if (rcVBox != 0)
5867 {
5868 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5869 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5870 }
5871 }
5872 if (SUCCEEDED(rc))
5873 {
5874 /*
5875 * Make it pollable.
5876 */
5877 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5878 {
5879 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5880
5881 /*
5882 * Here is the right place to communicate the TAP file descriptor and
5883 * the host interface name to the server if/when it becomes really
5884 * necessary.
5885 */
5886 maTAPDeviceName[slot] = tapDeviceName;
5887 rcVBox = VINF_SUCCESS;
5888 }
5889 else
5890 {
5891 int iErr = errno;
5892
5893 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5894 rcVBox = VERR_HOSTIF_BLOCKING;
5895 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5896 strerror(errno));
5897 }
5898 }
5899 }
5900 }
5901 else
5902 {
5903 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5904 switch (rcVBox)
5905 {
5906 case VERR_ACCESS_DENIED:
5907 /* will be handled by our caller */
5908 rc = rcVBox;
5909 break;
5910 default:
5911 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
5912 break;
5913 }
5914 }
5915 /* in case of failure, cleanup. */
5916 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5917 {
5918 LogRel(("General failure attaching to host interface\n"));
5919 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5920 }
5921 }
5922 LogFlowThisFunc(("rc=%d\n", rc));
5923 return rc;
5924#endif /* RT_OS_LINUX */
5925}
5926
5927/**
5928 * Helper function to handle detachment from a host interface
5929 *
5930 * @param networkAdapter the network adapter which attachment should be reset
5931 * @return COM status code
5932 *
5933 * @note The caller must lock this object for writing.
5934 */
5935HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5936{
5937#if !defined(RT_OS_LINUX)
5938
5939 /*
5940 * Nothing to do here.
5941 */
5942 NOREF(networkAdapter);
5943 return S_OK;
5944
5945#else /* RT_OS_LINUX */
5946
5947 /* sanity check */
5948 LogFlowThisFunc(("\n"));
5949 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5950
5951 HRESULT rc = S_OK;
5952# ifdef VBOX_STRICT
5953 /* paranoia */
5954 NetworkAttachmentType_T attachment;
5955 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5956 Assert(attachment == NetworkAttachmentType_HostInterface);
5957# endif /* VBOX_STRICT */
5958
5959 ULONG slot = 0;
5960 rc = networkAdapter->COMGETTER(Slot)(&slot);
5961 AssertComRC(rc);
5962
5963 /* is there an open TAP device? */
5964 if (maTapFD[slot] != NIL_RTFILE)
5965 {
5966 /*
5967 * Close the file handle.
5968 */
5969 Bstr tapDeviceName, tapTerminateApplication;
5970 bool isStatic = true;
5971 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5972 if (FAILED(rc) || tapDeviceName.isEmpty())
5973 {
5974 /* If the name is empty, this is a dynamic TAP device, so close it now,
5975 so that the termination script can remove the interface. Otherwise we still
5976 need the FD to pass to the termination script. */
5977 isStatic = false;
5978 int rcVBox = RTFileClose(maTapFD[slot]);
5979 AssertRC(rcVBox);
5980 maTapFD[slot] = NIL_RTFILE;
5981 }
5982 /*
5983 * Execute the termination command.
5984 */
5985 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5986 if (tapTerminateApplication)
5987 {
5988 /* Get the program name. */
5989 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5990
5991 /* Build the command line. */
5992 char szCommand[4096];
5993 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
5994 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
5995 /** @todo check for overflow or use RTStrAPrintf! */
5996
5997 /*
5998 * Create the process and wait for it to complete.
5999 */
6000 Log(("Calling the termination command: %s\n", szCommand));
6001 int rcCommand = system(szCommand);
6002 if (rcCommand == -1)
6003 {
6004 LogRel(("Failed to execute the clean up script for the TAP interface"));
6005 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
6006 }
6007 if (!WIFEXITED(rc))
6008 {
6009 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
6010 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
6011 }
6012 if (WEXITSTATUS(rc) != 0)
6013 {
6014 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
6015 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
6016 }
6017 }
6018
6019 if (isStatic)
6020 {
6021 /* If we are using a static TAP device, we close it now, after having called the
6022 termination script. */
6023 int rcVBox = RTFileClose(maTapFD[slot]);
6024 AssertRC(rcVBox);
6025 }
6026 /* the TAP device name and handle are no longer valid */
6027 maTapFD[slot] = NIL_RTFILE;
6028 maTAPDeviceName[slot] = "";
6029 }
6030 LogFlowThisFunc(("returning %d\n", rc));
6031 return rc;
6032#endif /* RT_OS_LINUX */
6033
6034}
6035
6036
6037/**
6038 * Called at power down to terminate host interface networking.
6039 *
6040 * @note The caller must lock this object for writing.
6041 */
6042HRESULT Console::powerDownHostInterfaces()
6043{
6044 LogFlowThisFunc (("\n"));
6045
6046 /* sanity check */
6047 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
6048
6049 /*
6050 * host interface termination handling
6051 */
6052 HRESULT rc;
6053 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
6054 {
6055 ComPtr<INetworkAdapter> networkAdapter;
6056 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
6057 CheckComRCBreakRC (rc);
6058
6059 BOOL enabled = FALSE;
6060 networkAdapter->COMGETTER(Enabled) (&enabled);
6061 if (!enabled)
6062 continue;
6063
6064 NetworkAttachmentType_T attachment;
6065 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6066 if (attachment == NetworkAttachmentType_HostInterface)
6067 {
6068 HRESULT rc2 = detachFromHostInterface(networkAdapter);
6069 if (FAILED(rc2) && SUCCEEDED(rc))
6070 rc = rc2;
6071 }
6072 }
6073
6074 return rc;
6075}
6076
6077
6078/**
6079 * Process callback handler for VMR3Load and VMR3Save.
6080 *
6081 * @param pVM The VM handle.
6082 * @param uPercent Completetion precentage (0-100).
6083 * @param pvUser Pointer to the VMProgressTask structure.
6084 * @return VINF_SUCCESS.
6085 */
6086/*static*/ DECLCALLBACK (int)
6087Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
6088{
6089 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6090 AssertReturn (task, VERR_INVALID_PARAMETER);
6091
6092 /* update the progress object */
6093 if (task->mProgress)
6094 task->mProgress->notifyProgress (uPercent);
6095
6096 return VINF_SUCCESS;
6097}
6098
6099/**
6100 * VM error callback function. Called by the various VM components.
6101 *
6102 * @param pVM VM handle. Can be NULL if an error occurred before
6103 * successfully creating a VM.
6104 * @param pvUser Pointer to the VMProgressTask structure.
6105 * @param rc VBox status code.
6106 * @param pszFormat Printf-like error message.
6107 * @param args Various number of argumens for the error message.
6108 *
6109 * @thread EMT, VMPowerUp...
6110 *
6111 * @note The VMProgressTask structure modified by this callback is not thread
6112 * safe.
6113 */
6114/* static */ DECLCALLBACK (void)
6115Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
6116 const char *pszFormat, va_list args)
6117{
6118 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6119 AssertReturnVoid (task);
6120
6121 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
6122 va_list va2;
6123 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
6124 Utf8Str errorMsg = Utf8StrFmt (tr ("%N.\n"
6125 "VBox status code: %d (%Vrc)"),
6126 pszFormat, &va2, rc, rc);
6127 va_end(va2);
6128
6129 /* For now, this may be called only once. Ignore subsequent calls. */
6130 if (!task->mErrorMsg.isNull())
6131 {
6132#if !defined(DEBUG_bird)
6133 AssertMsgFailed (("Cannot set error to '%s': it is already set to '%s'",
6134 errorMsg.raw(), task->mErrorMsg.raw()));
6135#endif
6136 return;
6137 }
6138
6139 task->mErrorMsg = errorMsg;
6140}
6141
6142/**
6143 * VM runtime error callback function.
6144 * See VMSetRuntimeError for the detailed description of parameters.
6145 *
6146 * @param pVM The VM handle.
6147 * @param pvUser The user argument.
6148 * @param fFatal Whether it is a fatal error or not.
6149 * @param pszErrorID Error ID string.
6150 * @param pszFormat Error message format string.
6151 * @param args Error message arguments.
6152 * @thread EMT.
6153 */
6154/* static */ DECLCALLBACK(void)
6155Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
6156 const char *pszErrorID,
6157 const char *pszFormat, va_list args)
6158{
6159 LogFlowFuncEnter();
6160
6161 Console *that = static_cast <Console *> (pvUser);
6162 AssertReturnVoid (that);
6163
6164 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
6165
6166 LogRel (("Console: VM runtime error: fatal=%RTbool, "
6167 "errorID=%s message=\"%s\"\n",
6168 fFatal, pszErrorID, message.raw()));
6169
6170 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
6171
6172 LogFlowFuncLeave();
6173}
6174
6175/**
6176 * Captures USB devices that match filters of the VM.
6177 * Called at VM startup.
6178 *
6179 * @param pVM The VM handle.
6180 *
6181 * @note The caller must lock this object for writing.
6182 */
6183HRESULT Console::captureUSBDevices (PVM pVM)
6184{
6185 LogFlowThisFunc (("\n"));
6186
6187 /* sanity check */
6188 ComAssertRet (isWriteLockOnCurrentThread(), E_FAIL);
6189
6190 /* If the machine has an USB controller, ask the USB proxy service to
6191 * capture devices */
6192 PPDMIBASE pBase;
6193 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
6194 if (VBOX_SUCCESS (vrc))
6195 {
6196 /* leave the lock before calling Host in VBoxSVC since Host may call
6197 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6198 * produce an inter-process dead-lock otherwise. */
6199 AutoWriteLock alock (this);
6200 alock.leave();
6201
6202 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6203 ComAssertComRCRetRC (hrc);
6204 }
6205 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6206 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6207 vrc = VINF_SUCCESS;
6208 else
6209 AssertRC (vrc);
6210
6211 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
6212}
6213
6214
6215/**
6216 * Detach all USB device which are attached to the VM for the
6217 * purpose of clean up and such like.
6218 *
6219 * @note The caller must lock this object for writing.
6220 */
6221void Console::detachAllUSBDevices (bool aDone)
6222{
6223 LogFlowThisFunc (("aDone=%RTbool\n", aDone));
6224
6225 /* sanity check */
6226 AssertReturnVoid (isWriteLockOnCurrentThread());
6227
6228 mUSBDevices.clear();
6229
6230 /* leave the lock before calling Host in VBoxSVC since Host may call
6231 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6232 * produce an inter-process dead-lock otherwise. */
6233 AutoWriteLock alock (this);
6234 alock.leave();
6235
6236 mControl->DetachAllUSBDevices (aDone);
6237}
6238
6239/**
6240 * @note Locks this object for writing.
6241 */
6242void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6243{
6244 LogFlowThisFuncEnter();
6245 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6246
6247 AutoCaller autoCaller (this);
6248 if (!autoCaller.isOk())
6249 {
6250 /* Console has been already uninitialized, deny request */
6251 AssertMsgFailed (("Temporary assertion to prove that it happens, "
6252 "please report to dmik\n"));
6253 LogFlowThisFunc (("Console is already uninitialized\n"));
6254 LogFlowThisFuncLeave();
6255 return;
6256 }
6257
6258 AutoWriteLock alock (this);
6259
6260 /*
6261 * Mark all existing remote USB devices as dirty.
6262 */
6263 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6264 while (it != mRemoteUSBDevices.end())
6265 {
6266 (*it)->dirty (true);
6267 ++ it;
6268 }
6269
6270 /*
6271 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6272 */
6273 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6274 VRDPUSBDEVICEDESC *e = pDevList;
6275
6276 /* The cbDevList condition must be checked first, because the function can
6277 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6278 */
6279 while (cbDevList >= 2 && e->oNext)
6280 {
6281 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6282 e->idVendor, e->idProduct,
6283 e->oProduct? (char *)e + e->oProduct: ""));
6284
6285 bool fNewDevice = true;
6286
6287 it = mRemoteUSBDevices.begin();
6288 while (it != mRemoteUSBDevices.end())
6289 {
6290 if ((*it)->devId () == e->id
6291 && (*it)->clientId () == u32ClientId)
6292 {
6293 /* The device is already in the list. */
6294 (*it)->dirty (false);
6295 fNewDevice = false;
6296 break;
6297 }
6298
6299 ++ it;
6300 }
6301
6302 if (fNewDevice)
6303 {
6304 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6305 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6306 ));
6307
6308 /* Create the device object and add the new device to list. */
6309 ComObjPtr <RemoteUSBDevice> device;
6310 device.createObject();
6311 device->init (u32ClientId, e);
6312
6313 mRemoteUSBDevices.push_back (device);
6314
6315 /* Check if the device is ok for current USB filters. */
6316 BOOL fMatched = FALSE;
6317 ULONG fMaskedIfs = 0;
6318
6319 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
6320
6321 AssertComRC (hrc);
6322
6323 LogFlowThisFunc (("USB filters return %d %#x\n", fMatched, fMaskedIfs));
6324
6325 if (fMatched)
6326 {
6327 hrc = onUSBDeviceAttach (device, NULL, fMaskedIfs);
6328
6329 /// @todo (r=dmik) warning reporting subsystem
6330
6331 if (hrc == S_OK)
6332 {
6333 LogFlowThisFunc (("Device attached\n"));
6334 device->captured (true);
6335 }
6336 }
6337 }
6338
6339 if (cbDevList < e->oNext)
6340 {
6341 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6342 cbDevList, e->oNext));
6343 break;
6344 }
6345
6346 cbDevList -= e->oNext;
6347
6348 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6349 }
6350
6351 /*
6352 * Remove dirty devices, that is those which are not reported by the server anymore.
6353 */
6354 for (;;)
6355 {
6356 ComObjPtr <RemoteUSBDevice> device;
6357
6358 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6359 while (it != mRemoteUSBDevices.end())
6360 {
6361 if ((*it)->dirty ())
6362 {
6363 device = *it;
6364 break;
6365 }
6366
6367 ++ it;
6368 }
6369
6370 if (!device)
6371 {
6372 break;
6373 }
6374
6375 USHORT vendorId = 0;
6376 device->COMGETTER(VendorId) (&vendorId);
6377
6378 USHORT productId = 0;
6379 device->COMGETTER(ProductId) (&productId);
6380
6381 Bstr product;
6382 device->COMGETTER(Product) (product.asOutParam());
6383
6384 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6385 vendorId, productId, product.raw ()
6386 ));
6387
6388 /* Detach the device from VM. */
6389 if (device->captured ())
6390 {
6391 Guid uuid;
6392 device->COMGETTER (Id) (uuid.asOutParam());
6393 onUSBDeviceDetach (uuid, NULL);
6394 }
6395
6396 /* And remove it from the list. */
6397 mRemoteUSBDevices.erase (it);
6398 }
6399
6400 LogFlowThisFuncLeave();
6401}
6402
6403/**
6404 * Thread function which starts the VM (also from saved state) and
6405 * track progress.
6406 *
6407 * @param Thread The thread id.
6408 * @param pvUser Pointer to a VMPowerUpTask structure.
6409 * @return VINF_SUCCESS (ignored).
6410 *
6411 * @note Locks the Console object for writing.
6412 */
6413/*static*/
6414DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6415{
6416 LogFlowFuncEnter();
6417
6418 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6419 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6420
6421 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6422 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6423
6424#if defined(RT_OS_WINDOWS)
6425 {
6426 /* initialize COM */
6427 HRESULT hrc = CoInitializeEx (NULL,
6428 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6429 COINIT_SPEED_OVER_MEMORY);
6430 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6431 }
6432#endif
6433
6434 HRESULT hrc = S_OK;
6435 int vrc = VINF_SUCCESS;
6436
6437 /* Set up a build identifier so that it can be seen from core dumps what
6438 * exact build was used to produce the core. */
6439 static char saBuildID[40];
6440 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
6441 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBoxSVNRev (), "BU", "IL", "DI", "D");
6442
6443 ComObjPtr <Console> console = task->mConsole;
6444
6445 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6446
6447 AutoWriteLock alock (console);
6448
6449 /* sanity */
6450 Assert (console->mpVM == NULL);
6451
6452 do
6453 {
6454#ifdef VBOX_WITH_VRDP
6455 /* Create the VRDP server. In case of headless operation, this will
6456 * also create the framebuffer, required at VM creation.
6457 */
6458 ConsoleVRDPServer *server = console->consoleVRDPServer();
6459 Assert (server);
6460 /// @todo (dmik)
6461 // does VRDP server call Console from the other thread?
6462 // Not sure, so leave the lock just in case
6463 alock.leave();
6464 vrc = server->Launch();
6465 alock.enter();
6466 if (VBOX_FAILURE (vrc))
6467 {
6468 Utf8Str errMsg;
6469 switch (vrc)
6470 {
6471 case VERR_NET_ADDRESS_IN_USE:
6472 {
6473 ULONG port = 0;
6474 console->mVRDPServer->COMGETTER(Port) (&port);
6475 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6476 port);
6477 break;
6478 }
6479 case VERR_FILE_NOT_FOUND:
6480 {
6481 errMsg = Utf8StrFmt (tr ("Could not load the VRDP library"));
6482 break;
6483 }
6484 default:
6485 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6486 vrc);
6487 }
6488 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6489 vrc, errMsg.raw()));
6490 hrc = setError (E_FAIL, errMsg);
6491 break;
6492 }
6493#endif /* VBOX_WITH_VRDP */
6494
6495 /*
6496 * Create the VM
6497 */
6498 PVM pVM;
6499 /*
6500 * leave the lock since EMT will call Console. It's safe because
6501 * mMachineState is either Starting or Restoring state here.
6502 */
6503 alock.leave();
6504
6505 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6506 task->mConfigConstructor, static_cast <Console *> (console),
6507 &pVM);
6508
6509 alock.enter();
6510
6511#ifdef VBOX_WITH_VRDP
6512 /* Enable client connections to the server. */
6513 console->consoleVRDPServer()->EnableConnections ();
6514#endif /* VBOX_WITH_VRDP */
6515
6516 if (VBOX_SUCCESS (vrc))
6517 {
6518 do
6519 {
6520 /*
6521 * Register our load/save state file handlers
6522 */
6523 vrc = SSMR3RegisterExternal (pVM,
6524 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6525 0 /* cbGuess */,
6526 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6527 static_cast <Console *> (console));
6528 AssertRC (vrc);
6529 if (VBOX_FAILURE (vrc))
6530 break;
6531
6532 /*
6533 * Synchronize debugger settings
6534 */
6535 MachineDebugger *machineDebugger = console->getMachineDebugger();
6536 if (machineDebugger)
6537 {
6538 machineDebugger->flushQueuedSettings();
6539 }
6540
6541 /*
6542 * Shared Folders
6543 */
6544 if (console->getVMMDev()->isShFlActive())
6545 {
6546 /// @todo (dmik)
6547 // does the code below call Console from the other thread?
6548 // Not sure, so leave the lock just in case
6549 alock.leave();
6550
6551 for (SharedFolderDataMap::const_iterator
6552 it = task->mSharedFolders.begin();
6553 it != task->mSharedFolders.end();
6554 ++ it)
6555 {
6556 hrc = console->createSharedFolder ((*it).first, (*it).second);
6557 CheckComRCBreakRC (hrc);
6558 }
6559
6560 /* enter the lock again */
6561 alock.enter();
6562
6563 CheckComRCBreakRC (hrc);
6564 }
6565
6566 /*
6567 * Capture USB devices.
6568 */
6569 hrc = console->captureUSBDevices (pVM);
6570 CheckComRCBreakRC (hrc);
6571
6572 /* leave the lock before a lengthy operation */
6573 alock.leave();
6574
6575 /* Load saved state? */
6576 if (!!task->mSavedStateFile)
6577 {
6578 LogFlowFunc (("Restoring saved state from '%s'...\n",
6579 task->mSavedStateFile.raw()));
6580
6581 vrc = VMR3Load (pVM, task->mSavedStateFile,
6582 Console::stateProgressCallback,
6583 static_cast <VMProgressTask *> (task.get()));
6584
6585 if (VBOX_SUCCESS (vrc))
6586 {
6587 if (task->mStartPaused)
6588 /* done */
6589 console->setMachineState (MachineState_Paused);
6590 else
6591 {
6592 /* Start/Resume the VM execution */
6593 vrc = VMR3Resume (pVM);
6594 AssertRC (vrc);
6595 }
6596 }
6597
6598 /* Power off in case we failed loading or resuming the VM */
6599 if (VBOX_FAILURE (vrc))
6600 {
6601 int vrc2 = VMR3PowerOff (pVM);
6602 AssertRC (vrc2);
6603 }
6604 }
6605 else if (task->mStartPaused)
6606 /* done */
6607 console->setMachineState (MachineState_Paused);
6608 else
6609 {
6610 /* Power on the VM (i.e. start executing) */
6611 vrc = VMR3PowerOn(pVM);
6612 AssertRC (vrc);
6613 }
6614
6615 /* enter the lock again */
6616 alock.enter();
6617 }
6618 while (0);
6619
6620 /* On failure, destroy the VM */
6621 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6622 {
6623 /* preserve existing error info */
6624 ErrorInfoKeeper eik;
6625
6626 /* powerDown() will call VMR3Destroy() and do all necessary
6627 * cleanup (VRDP, USB devices) */
6628 HRESULT hrc2 = console->powerDown();
6629 AssertComRC (hrc2);
6630 }
6631 }
6632 else
6633 {
6634 /*
6635 * If VMR3Create() failed it has released the VM memory.
6636 */
6637 console->mpVM = NULL;
6638 }
6639
6640 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6641 {
6642 /* If VMR3Create() or one of the other calls in this function fail,
6643 * an appropriate error message has been set in task->mErrorMsg.
6644 * However since that happens via a callback, the hrc status code in
6645 * this function is not updated.
6646 */
6647 if (task->mErrorMsg.isNull())
6648 {
6649 /* If the error message is not set but we've got a failure,
6650 * convert the VBox status code into a meaningfulerror message.
6651 * This becomes unused once all the sources of errors set the
6652 * appropriate error message themselves.
6653 */
6654 AssertMsgFailed (("Missing error message during powerup for "
6655 "status code %Vrc\n", vrc));
6656 task->mErrorMsg = Utf8StrFmt (
6657 tr ("Failed to start VM execution (%Vrc)"), vrc);
6658 }
6659
6660 /* Set the error message as the COM error.
6661 * Progress::notifyComplete() will pick it up later. */
6662 hrc = setError (E_FAIL, task->mErrorMsg);
6663 break;
6664 }
6665 }
6666 while (0);
6667
6668 if (console->mMachineState == MachineState_Starting ||
6669 console->mMachineState == MachineState_Restoring)
6670 {
6671 /* We are still in the Starting/Restoring state. This means one of:
6672 *
6673 * 1) we failed before VMR3Create() was called;
6674 * 2) VMR3Create() failed.
6675 *
6676 * In both cases, there is no need to call powerDown(), but we still
6677 * need to go back to the PoweredOff/Saved state. Reuse
6678 * vmstateChangeCallback() for that purpose.
6679 */
6680
6681 /* preserve existing error info */
6682 ErrorInfoKeeper eik;
6683
6684 Assert (console->mpVM == NULL);
6685 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6686 console);
6687 }
6688
6689 /*
6690 * Evaluate the final result. Note that the appropriate mMachineState value
6691 * is already set by vmstateChangeCallback() in all cases.
6692 */
6693
6694 /* leave the lock, don't need it any more */
6695 alock.leave();
6696
6697 if (SUCCEEDED (hrc))
6698 {
6699 /* Notify the progress object of the success */
6700 task->mProgress->notifyComplete (S_OK);
6701 }
6702 else
6703 {
6704 /* The progress object will fetch the current error info */
6705 task->mProgress->notifyComplete (hrc);
6706
6707 LogRel (("Power up failed (vrc=%Vrc, hrc=%Rhrc (%#08X))\n", vrc, hrc, hrc));
6708 }
6709
6710#if defined(RT_OS_WINDOWS)
6711 /* uninitialize COM */
6712 CoUninitialize();
6713#endif
6714
6715 LogFlowFuncLeave();
6716
6717 return VINF_SUCCESS;
6718}
6719
6720
6721/**
6722 * Reconfigures a VDI.
6723 *
6724 * @param pVM The VM handle.
6725 * @param hda The harddisk attachment.
6726 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6727 * @return VBox status code.
6728 */
6729static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6730{
6731 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6732
6733 int rc;
6734 HRESULT hrc;
6735 char *psz = NULL;
6736 BSTR str = NULL;
6737 *phrc = S_OK;
6738#define STR_CONV() do { rc = RTUtf16ToUtf8(str, &psz); RC_CHECK(); } while (0)
6739#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6740#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6741#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6742
6743 /*
6744 * Figure out which IDE device this is.
6745 */
6746 ComPtr<IHardDisk> hardDisk;
6747 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6748 StorageBus_T enmBus;
6749 hrc = hda->COMGETTER(Bus)(&enmBus); H();
6750 LONG lDev;
6751 hrc = hda->COMGETTER(Device)(&lDev); H();
6752 LONG lChannel;
6753 hrc = hda->COMGETTER(Channel)(&lChannel); H();
6754
6755 int iLUN;
6756 switch (enmBus)
6757 {
6758 case StorageBus_IDE:
6759 {
6760 if (lChannel >= 2)
6761 {
6762 AssertMsgFailed(("invalid controller channel number: %d\n", lChannel));
6763 return VERR_GENERAL_FAILURE;
6764 }
6765
6766 if (lDev >= 2)
6767 {
6768 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6769 return VERR_GENERAL_FAILURE;
6770 }
6771 iLUN = 2*lChannel + lDev;
6772 }
6773 break;
6774 case StorageBus_SATA:
6775 iLUN = lChannel;
6776 break;
6777 default:
6778 AssertMsgFailed(("invalid disk controller type: %d\n", enmBus));
6779 return VERR_GENERAL_FAILURE;
6780 }
6781
6782 /*
6783 * Is there an existing LUN? If not create it.
6784 * We ASSUME that this will NEVER collide with the DVD.
6785 */
6786 PCFGMNODE pCfg;
6787 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", iLUN);
6788 if (!pLunL1)
6789 {
6790 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6791 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6792
6793 PCFGMNODE pLunL0;
6794 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", iLUN); RC_CHECK();
6795 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6796 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6797 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6798 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6799
6800 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6801 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6802 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6803 }
6804 else
6805 {
6806#ifdef VBOX_STRICT
6807 char *pszDriver;
6808 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6809 Assert(!strcmp(pszDriver, "VBoxHDD"));
6810 MMR3HeapFree(pszDriver);
6811#endif
6812
6813 /*
6814 * Check if things has changed.
6815 */
6816 pCfg = CFGMR3GetChild(pLunL1, "Config");
6817 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6818
6819 /* the image */
6820 /// @todo (dmik) we temporarily use the location property to
6821 // determine the image file name. This is subject to change
6822 // when iSCSI disks are here (we should either query a
6823 // storage-specific interface from IHardDisk, or "standardize"
6824 // the location property)
6825 hrc = hardDisk->COMGETTER(Location)(&str); H();
6826 STR_CONV();
6827 char *pszPath;
6828 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6829 if (!strcmp(psz, pszPath))
6830 {
6831 /* parent images. */
6832 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6833 for (PCFGMNODE pParent = pCfg;;)
6834 {
6835 MMR3HeapFree(pszPath);
6836 pszPath = NULL;
6837 STR_FREE();
6838
6839 /* get parent */
6840 ComPtr<IHardDisk> curHardDisk;
6841 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6842 PCFGMNODE pCur;
6843 pCur = CFGMR3GetChild(pParent, "Parent");
6844 if (!pCur && !curHardDisk)
6845 {
6846 /* no change */
6847 LogFlowFunc (("No change!\n"));
6848 return VINF_SUCCESS;
6849 }
6850 if (!pCur || !curHardDisk)
6851 break;
6852
6853 /* compare paths. */
6854 /// @todo (dmik) we temporarily use the location property to
6855 // determine the image file name. This is subject to change
6856 // when iSCSI disks are here (we should either query a
6857 // storage-specific interface from IHardDisk, or "standardize"
6858 // the location property)
6859 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6860 STR_CONV();
6861 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6862 if (strcmp(psz, pszPath))
6863 break;
6864
6865 /* next */
6866 pParent = pCur;
6867 parentHardDisk = curHardDisk;
6868 }
6869
6870 }
6871 else
6872 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", iLUN, pszPath));
6873
6874 MMR3HeapFree(pszPath);
6875 STR_FREE();
6876
6877 /*
6878 * Detach the driver and replace the config node.
6879 */
6880 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, iLUN); RC_CHECK();
6881 CFGMR3RemoveNode(pCfg);
6882 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6883 }
6884
6885 /*
6886 * Create the driver configuration.
6887 */
6888 /// @todo (dmik) we temporarily use the location property to
6889 // determine the image file name. This is subject to change
6890 // when iSCSI disks are here (we should either query a
6891 // storage-specific interface from IHardDisk, or "standardize"
6892 // the location property)
6893 hrc = hardDisk->COMGETTER(Location)(&str); H();
6894 STR_CONV();
6895 LogFlowFunc (("LUN#%d: leaf image '%s'\n", iLUN, psz));
6896 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6897 STR_FREE();
6898 /* Create an inversed tree of parents. */
6899 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6900 for (PCFGMNODE pParent = pCfg;;)
6901 {
6902 ComPtr<IHardDisk> curHardDisk;
6903 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6904 if (!curHardDisk)
6905 break;
6906
6907 PCFGMNODE pCur;
6908 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6909 /// @todo (dmik) we temporarily use the location property to
6910 // determine the image file name. This is subject to change
6911 // when iSCSI disks are here (we should either query a
6912 // storage-specific interface from IHardDisk, or "standardize"
6913 // the location property)
6914 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6915 STR_CONV();
6916 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6917 STR_FREE();
6918
6919 /* next */
6920 pParent = pCur;
6921 parentHardDisk = curHardDisk;
6922 }
6923
6924 /*
6925 * Attach the new driver.
6926 */
6927 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, iLUN, NULL); RC_CHECK();
6928
6929 LogFlowFunc (("Returns success\n"));
6930 return rc;
6931}
6932
6933
6934/**
6935 * Thread for executing the saved state operation.
6936 *
6937 * @param Thread The thread handle.
6938 * @param pvUser Pointer to a VMSaveTask structure.
6939 * @return VINF_SUCCESS (ignored).
6940 *
6941 * @note Locks the Console object for writing.
6942 */
6943/*static*/
6944DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6945{
6946 LogFlowFuncEnter();
6947
6948 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6949 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6950
6951 Assert (!task->mSavedStateFile.isNull());
6952 Assert (!task->mProgress.isNull());
6953
6954 const ComObjPtr <Console> &that = task->mConsole;
6955
6956 /*
6957 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6958 * protect mpVM because VMSaveTask does that
6959 */
6960
6961 Utf8Str errMsg;
6962 HRESULT rc = S_OK;
6963
6964 if (task->mIsSnapshot)
6965 {
6966 Assert (!task->mServerProgress.isNull());
6967 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6968
6969 rc = task->mServerProgress->WaitForCompletion (-1);
6970 if (SUCCEEDED (rc))
6971 {
6972 HRESULT result = S_OK;
6973 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6974 if (SUCCEEDED (rc))
6975 rc = result;
6976 }
6977 }
6978
6979 if (SUCCEEDED (rc))
6980 {
6981 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6982
6983 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6984 Console::stateProgressCallback,
6985 static_cast <VMProgressTask *> (task.get()));
6986 if (VBOX_FAILURE (vrc))
6987 {
6988 errMsg = Utf8StrFmt (
6989 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6990 task->mSavedStateFile.raw(), vrc);
6991 rc = E_FAIL;
6992 }
6993 }
6994
6995 /* lock the console sonce we're going to access it */
6996 AutoWriteLock thatLock (that);
6997
6998 if (SUCCEEDED (rc))
6999 {
7000 if (task->mIsSnapshot)
7001 do
7002 {
7003 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
7004
7005 ComPtr <IHardDiskAttachmentCollection> hdaColl;
7006 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
7007 if (FAILED (rc))
7008 break;
7009 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
7010 rc = hdaColl->Enumerate (hdaEn.asOutParam());
7011 if (FAILED (rc))
7012 break;
7013 BOOL more = FALSE;
7014 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
7015 {
7016 ComPtr <IHardDiskAttachment> hda;
7017 rc = hdaEn->GetNext (hda.asOutParam());
7018 if (FAILED (rc))
7019 break;
7020
7021 PVMREQ pReq;
7022 IHardDiskAttachment *pHda = hda;
7023 /*
7024 * don't leave the lock since reconfigureVDI isn't going to
7025 * access Console.
7026 */
7027 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
7028 (PFNRT)reconfigureVDI, 3, that->mpVM,
7029 pHda, &rc);
7030 if (VBOX_SUCCESS (rc))
7031 rc = pReq->iStatus;
7032 VMR3ReqFree (pReq);
7033 if (FAILED (rc))
7034 break;
7035 if (VBOX_FAILURE (vrc))
7036 {
7037 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
7038 rc = E_FAIL;
7039 break;
7040 }
7041 }
7042 }
7043 while (0);
7044 }
7045
7046 /* finalize the procedure regardless of the result */
7047 if (task->mIsSnapshot)
7048 {
7049 /*
7050 * finalize the requested snapshot object.
7051 * This will reset the machine state to the state it had right
7052 * before calling mControl->BeginTakingSnapshot().
7053 */
7054 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
7055 }
7056 else
7057 {
7058 /*
7059 * finalize the requested save state procedure.
7060 * In case of success, the server will set the machine state to Saved;
7061 * in case of failure it will reset the it to the state it had right
7062 * before calling mControl->BeginSavingState().
7063 */
7064 that->mControl->EndSavingState (SUCCEEDED (rc));
7065 }
7066
7067 /* synchronize the state with the server */
7068 if (task->mIsSnapshot || FAILED (rc))
7069 {
7070 if (task->mLastMachineState == MachineState_Running)
7071 {
7072 /* restore the paused state if appropriate */
7073 that->setMachineStateLocally (MachineState_Paused);
7074 /* restore the running state if appropriate */
7075 that->Resume();
7076 }
7077 else
7078 that->setMachineStateLocally (task->mLastMachineState);
7079 }
7080 else
7081 {
7082 /*
7083 * The machine has been successfully saved, so power it down
7084 * (vmstateChangeCallback() will set state to Saved on success).
7085 * Note: we release the task's VM caller, otherwise it will
7086 * deadlock.
7087 */
7088 task->releaseVMCaller();
7089
7090 rc = that->powerDown();
7091 }
7092
7093 /* notify the progress object about operation completion */
7094 if (SUCCEEDED (rc))
7095 task->mProgress->notifyComplete (S_OK);
7096 else
7097 {
7098 if (!errMsg.isNull())
7099 task->mProgress->notifyComplete (rc,
7100 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
7101 else
7102 task->mProgress->notifyComplete (rc);
7103 }
7104
7105 LogFlowFuncLeave();
7106 return VINF_SUCCESS;
7107}
7108
7109/**
7110 * Thread for powering down the Console.
7111 *
7112 * @param Thread The thread handle.
7113 * @param pvUser Pointer to the VMTask structure.
7114 * @return VINF_SUCCESS (ignored).
7115 *
7116 * @note Locks the Console object for writing.
7117 */
7118/*static*/
7119DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
7120{
7121 LogFlowFuncEnter();
7122
7123 std::auto_ptr <VMProgressTask> task (static_cast <VMProgressTask *> (pvUser));
7124 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7125
7126 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
7127
7128 const ComObjPtr <Console> &that = task->mConsole;
7129
7130 /* Note: no need to use addCaller() to protect Console because VMTask does
7131 * that */
7132
7133 /* wait until the method tat started us returns */
7134 AutoWriteLock thatLock (that);
7135
7136 /* release VM caller to avoid the powerDown() deadlock */
7137 task->releaseVMCaller();
7138
7139 that->powerDown (task->mProgress);
7140
7141 LogFlowFuncLeave();
7142 return VINF_SUCCESS;
7143}
7144
7145/**
7146 * The Main status driver instance data.
7147 */
7148typedef struct DRVMAINSTATUS
7149{
7150 /** The LED connectors. */
7151 PDMILEDCONNECTORS ILedConnectors;
7152 /** Pointer to the LED ports interface above us. */
7153 PPDMILEDPORTS pLedPorts;
7154 /** Pointer to the array of LED pointers. */
7155 PPDMLED *papLeds;
7156 /** The unit number corresponding to the first entry in the LED array. */
7157 RTUINT iFirstLUN;
7158 /** The unit number corresponding to the last entry in the LED array.
7159 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7160 RTUINT iLastLUN;
7161} DRVMAINSTATUS, *PDRVMAINSTATUS;
7162
7163
7164/**
7165 * Notification about a unit which have been changed.
7166 *
7167 * The driver must discard any pointers to data owned by
7168 * the unit and requery it.
7169 *
7170 * @param pInterface Pointer to the interface structure containing the called function pointer.
7171 * @param iLUN The unit number.
7172 */
7173DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7174{
7175 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7176 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7177 {
7178 PPDMLED pLed;
7179 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7180 if (VBOX_FAILURE(rc))
7181 pLed = NULL;
7182 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7183 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7184 }
7185}
7186
7187
7188/**
7189 * Queries an interface to the driver.
7190 *
7191 * @returns Pointer to interface.
7192 * @returns NULL if the interface was not supported by the driver.
7193 * @param pInterface Pointer to this interface structure.
7194 * @param enmInterface The requested interface identification.
7195 */
7196DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7197{
7198 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7199 PDRVMAINSTATUS pDrv = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7200 switch (enmInterface)
7201 {
7202 case PDMINTERFACE_BASE:
7203 return &pDrvIns->IBase;
7204 case PDMINTERFACE_LED_CONNECTORS:
7205 return &pDrv->ILedConnectors;
7206 default:
7207 return NULL;
7208 }
7209}
7210
7211
7212/**
7213 * Destruct a status driver instance.
7214 *
7215 * @returns VBox status.
7216 * @param pDrvIns The driver instance data.
7217 */
7218DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7219{
7220 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7221 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7222 if (pData->papLeds)
7223 {
7224 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7225 while (iLed-- > 0)
7226 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7227 }
7228}
7229
7230
7231/**
7232 * Construct a status driver instance.
7233 *
7234 * @returns VBox status.
7235 * @param pDrvIns The driver instance data.
7236 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7237 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7238 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7239 * iInstance it's expected to be used a bit in this function.
7240 */
7241DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7242{
7243 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7244 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7245
7246 /*
7247 * Validate configuration.
7248 */
7249 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7250 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7251 PPDMIBASE pBaseIgnore;
7252 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7253 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7254 {
7255 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7256 return VERR_PDM_DRVINS_NO_ATTACH;
7257 }
7258
7259 /*
7260 * Data.
7261 */
7262 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7263 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7264
7265 /*
7266 * Read config.
7267 */
7268 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7269 if (VBOX_FAILURE(rc))
7270 {
7271 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7272 return rc;
7273 }
7274
7275 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7276 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7277 pData->iFirstLUN = 0;
7278 else if (VBOX_FAILURE(rc))
7279 {
7280 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7281 return rc;
7282 }
7283
7284 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7285 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7286 pData->iLastLUN = 0;
7287 else if (VBOX_FAILURE(rc))
7288 {
7289 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7290 return rc;
7291 }
7292 if (pData->iFirstLUN > pData->iLastLUN)
7293 {
7294 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7295 return VERR_GENERAL_FAILURE;
7296 }
7297
7298 /*
7299 * Get the ILedPorts interface of the above driver/device and
7300 * query the LEDs we want.
7301 */
7302 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7303 if (!pData->pLedPorts)
7304 {
7305 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7306 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7307 }
7308
7309 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7310 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7311
7312 return VINF_SUCCESS;
7313}
7314
7315
7316/**
7317 * Keyboard driver registration record.
7318 */
7319const PDMDRVREG Console::DrvStatusReg =
7320{
7321 /* u32Version */
7322 PDM_DRVREG_VERSION,
7323 /* szDriverName */
7324 "MainStatus",
7325 /* pszDescription */
7326 "Main status driver (Main as in the API).",
7327 /* fFlags */
7328 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7329 /* fClass. */
7330 PDM_DRVREG_CLASS_STATUS,
7331 /* cMaxInstances */
7332 ~0,
7333 /* cbInstance */
7334 sizeof(DRVMAINSTATUS),
7335 /* pfnConstruct */
7336 Console::drvStatus_Construct,
7337 /* pfnDestruct */
7338 Console::drvStatus_Destruct,
7339 /* pfnIOCtl */
7340 NULL,
7341 /* pfnPowerOn */
7342 NULL,
7343 /* pfnReset */
7344 NULL,
7345 /* pfnSuspend */
7346 NULL,
7347 /* pfnResume */
7348 NULL,
7349 /* pfnDetach */
7350 NULL
7351};
7352
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use