VirtualBox

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

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

#3551: “Main: Replace remaining collections with safe arrays”
Replaced HostUSBDeviceCollection. Reviewed/Okayed by dmik, sunlover.

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