VirtualBox

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

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

Main: NLS: Better wording.

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

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