VirtualBox

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

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

Main: Reset differencing hard disks for which auto-reset is set to true (#3425).

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

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