VirtualBox

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

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

Fixed a possible deadlock when VRDP server is enabled/disabled in runtime.

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

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