VirtualBox

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

Last change on this file since 31301 was 31270, checked in by vboxsync, 14 years ago

Main: A little bit more logging.

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

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