VirtualBox

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

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

Main: Rework storage controller handling to allow an arbitrary number of different storage controllers and remove code duplication:

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

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