VirtualBox

source: vbox/trunk/src/VBox/Main/GuestImpl.cpp@ 28533

Last change on this file since 28533 was 28529, checked in by vboxsync, 15 years ago

Main: added a note

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.4 KB
Line 
1/* $Id: GuestImpl.cpp 28529 2010-04-20 14:34:16Z vboxsync $ */
2
3/** @file
4 *
5 * VirtualBox COM class implementation
6 */
7
8/*
9 * Copyright (C) 2006-2008 Sun Microsystems, Inc.
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
20 * Clara, CA 95054 USA or visit http://www.sun.com if you need
21 * additional information or have any questions.
22 */
23
24#include "GuestImpl.h"
25
26#include "Global.h"
27#include "ConsoleImpl.h"
28#include "ProgressImpl.h"
29#include "VMMDev.h"
30
31#include "AutoCaller.h"
32#include "Logging.h"
33
34#include <VBox/VMMDev.h>
35#ifdef VBOX_WITH_GUEST_CONTROL
36# include <VBox/com/array.h>
37#endif
38#include <iprt/cpp/utils.h>
39#include <iprt/getopt.h>
40#include <VBox/pgm.h>
41
42// defines
43/////////////////////////////////////////////////////////////////////////////
44
45// constructor / destructor
46/////////////////////////////////////////////////////////////////////////////
47
48DEFINE_EMPTY_CTOR_DTOR (Guest)
49
50HRESULT Guest::FinalConstruct()
51{
52 return S_OK;
53}
54
55void Guest::FinalRelease()
56{
57 uninit ();
58}
59
60// public methods only for internal purposes
61/////////////////////////////////////////////////////////////////////////////
62
63/**
64 * Initializes the guest object.
65 */
66HRESULT Guest::init (Console *aParent)
67{
68 LogFlowThisFunc(("aParent=%p\n", aParent));
69
70 ComAssertRet(aParent, E_INVALIDARG);
71
72 /* Enclose the state transition NotReady->InInit->Ready */
73 AutoInitSpan autoInitSpan(this);
74 AssertReturn(autoInitSpan.isOk(), E_FAIL);
75
76 unconst(mParent) = aParent;
77
78 /* mData.mAdditionsActive is FALSE */
79
80 /* Confirm a successful initialization when it's the case */
81 autoInitSpan.setSucceeded();
82
83 ULONG aMemoryBalloonSize;
84 HRESULT ret = mParent->machine()->COMGETTER(MemoryBalloonSize)(&aMemoryBalloonSize);
85 if (ret == S_OK)
86 mMemoryBalloonSize = aMemoryBalloonSize;
87 else
88 mMemoryBalloonSize = 0; /* Default is no ballooning */
89
90 mStatUpdateInterval = 0; /* Default is not to report guest statistics at all */
91
92 /* Clear statistics. */
93 for (unsigned i = 0 ; i < GUESTSTATTYPE_MAX; i++)
94 mCurrentGuestStat[i] = 0;
95
96#ifdef VBOX_WITH_GUEST_CONTROL
97 /* Init the context ID counter at 1000. */
98 mNextContextID = 1000;
99#endif
100
101 return S_OK;
102}
103
104/**
105 * Uninitializes the instance and sets the ready flag to FALSE.
106 * Called either from FinalRelease() or by the parent when it gets destroyed.
107 */
108void Guest::uninit()
109{
110 LogFlowThisFunc(("\n"));
111
112#ifdef VBOX_WITH_GUEST_CONTROL
113 /* Clean up callback data. */
114 CallbackListIter it;
115 for (it = mCallbackList.begin(); it != mCallbackList.end(); it++)
116 removeCtrlCallbackContext(it);
117#endif
118
119 /* Enclose the state transition Ready->InUninit->NotReady */
120 AutoUninitSpan autoUninitSpan(this);
121 if (autoUninitSpan.uninitDone())
122 return;
123
124 unconst(mParent) = NULL;
125}
126
127// IGuest properties
128/////////////////////////////////////////////////////////////////////////////
129
130STDMETHODIMP Guest::COMGETTER(OSTypeId) (BSTR *aOSTypeId)
131{
132 CheckComArgOutPointerValid(aOSTypeId);
133
134 AutoCaller autoCaller(this);
135 if (FAILED(autoCaller.rc())) return autoCaller.rc();
136
137 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
138
139 // redirect the call to IMachine if no additions are installed
140 if (mData.mAdditionsVersion.isEmpty())
141 return mParent->machine()->COMGETTER(OSTypeId)(aOSTypeId);
142
143 mData.mOSTypeId.cloneTo(aOSTypeId);
144
145 return S_OK;
146}
147
148STDMETHODIMP Guest::COMGETTER(AdditionsActive) (BOOL *aAdditionsActive)
149{
150 CheckComArgOutPointerValid(aAdditionsActive);
151
152 AutoCaller autoCaller(this);
153 if (FAILED(autoCaller.rc())) return autoCaller.rc();
154
155 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
156
157 *aAdditionsActive = mData.mAdditionsActive;
158
159 return S_OK;
160}
161
162STDMETHODIMP Guest::COMGETTER(AdditionsVersion) (BSTR *aAdditionsVersion)
163{
164 CheckComArgOutPointerValid(aAdditionsVersion);
165
166 AutoCaller autoCaller(this);
167 if (FAILED(autoCaller.rc())) return autoCaller.rc();
168
169 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
170
171 mData.mAdditionsVersion.cloneTo(aAdditionsVersion);
172
173 return S_OK;
174}
175
176STDMETHODIMP Guest::COMGETTER(SupportsSeamless) (BOOL *aSupportsSeamless)
177{
178 CheckComArgOutPointerValid(aSupportsSeamless);
179
180 AutoCaller autoCaller(this);
181 if (FAILED(autoCaller.rc())) return autoCaller.rc();
182
183 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
184
185 *aSupportsSeamless = mData.mSupportsSeamless;
186
187 return S_OK;
188}
189
190STDMETHODIMP Guest::COMGETTER(SupportsGraphics) (BOOL *aSupportsGraphics)
191{
192 CheckComArgOutPointerValid(aSupportsGraphics);
193
194 AutoCaller autoCaller(this);
195 if (FAILED(autoCaller.rc())) return autoCaller.rc();
196
197 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
198
199 *aSupportsGraphics = mData.mSupportsGraphics;
200
201 return S_OK;
202}
203
204STDMETHODIMP Guest::COMGETTER(MemoryBalloonSize) (ULONG *aMemoryBalloonSize)
205{
206 CheckComArgOutPointerValid(aMemoryBalloonSize);
207
208 AutoCaller autoCaller(this);
209 if (FAILED(autoCaller.rc())) return autoCaller.rc();
210
211 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
212
213 *aMemoryBalloonSize = mMemoryBalloonSize;
214
215 return S_OK;
216}
217
218STDMETHODIMP Guest::COMSETTER(MemoryBalloonSize) (ULONG aMemoryBalloonSize)
219{
220 AutoCaller autoCaller(this);
221 if (FAILED(autoCaller.rc())) return autoCaller.rc();
222
223 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
224
225 /* We must be 100% sure that IMachine::COMSETTER(MemoryBalloonSize)
226 * does not call us back in any way! */
227 HRESULT ret = mParent->machine()->COMSETTER(MemoryBalloonSize)(aMemoryBalloonSize);
228 if (ret == S_OK)
229 {
230 mMemoryBalloonSize = aMemoryBalloonSize;
231 /* forward the information to the VMM device */
232 VMMDev *vmmDev = mParent->getVMMDev();
233 if (vmmDev)
234 vmmDev->getVMMDevPort()->pfnSetMemoryBalloon(vmmDev->getVMMDevPort(), aMemoryBalloonSize);
235 }
236
237 return ret;
238}
239
240STDMETHODIMP Guest::COMGETTER(StatisticsUpdateInterval)(ULONG *aUpdateInterval)
241{
242 CheckComArgOutPointerValid(aUpdateInterval);
243
244 AutoCaller autoCaller(this);
245 if (FAILED(autoCaller.rc())) return autoCaller.rc();
246
247 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
248
249 *aUpdateInterval = mStatUpdateInterval;
250 return S_OK;
251}
252
253STDMETHODIMP Guest::COMSETTER(StatisticsUpdateInterval)(ULONG aUpdateInterval)
254{
255 AutoCaller autoCaller(this);
256 if (FAILED(autoCaller.rc())) return autoCaller.rc();
257
258 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
259
260 mStatUpdateInterval = aUpdateInterval;
261 /* forward the information to the VMM device */
262 VMMDev *vmmDev = mParent->getVMMDev();
263 if (vmmDev)
264 vmmDev->getVMMDevPort()->pfnSetStatisticsInterval(vmmDev->getVMMDevPort(), aUpdateInterval);
265
266 return S_OK;
267}
268
269STDMETHODIMP Guest::InternalGetStatistics(ULONG *aCpuUser, ULONG *aCpuKernel, ULONG *aCpuIdle,
270 ULONG *aMemTotal, ULONG *aMemFree, ULONG *aMemBalloon,
271 ULONG *aMemCache, ULONG *aPageTotal,
272 ULONG *aMemAllocTotal, ULONG *aMemFreeTotal, ULONG *aMemBalloonTotal)
273{
274 CheckComArgOutPointerValid(aCpuUser);
275 CheckComArgOutPointerValid(aCpuKernel);
276 CheckComArgOutPointerValid(aCpuIdle);
277 CheckComArgOutPointerValid(aMemTotal);
278 CheckComArgOutPointerValid(aMemFree);
279 CheckComArgOutPointerValid(aMemBalloon);
280 CheckComArgOutPointerValid(aMemCache);
281 CheckComArgOutPointerValid(aPageTotal);
282
283 AutoCaller autoCaller(this);
284 if (FAILED(autoCaller.rc())) return autoCaller.rc();
285
286 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
287
288 *aCpuUser = mCurrentGuestStat[GUESTSTATTYPE_CPUUSER];
289 *aCpuKernel = mCurrentGuestStat[GUESTSTATTYPE_CPUKERNEL];
290 *aCpuIdle = mCurrentGuestStat[GUESTSTATTYPE_CPUIDLE];
291 *aMemTotal = mCurrentGuestStat[GUESTSTATTYPE_MEMTOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
292 *aMemFree = mCurrentGuestStat[GUESTSTATTYPE_MEMFREE] * (_4K/_1K); /* page (4K) -> 1KB units */
293 *aMemBalloon = mCurrentGuestStat[GUESTSTATTYPE_MEMBALLOON] * (_4K/_1K); /* page (4K) -> 1KB units */
294 *aMemCache = mCurrentGuestStat[GUESTSTATTYPE_MEMCACHE] * (_4K/_1K); /* page (4K) -> 1KB units */
295 *aPageTotal = mCurrentGuestStat[GUESTSTATTYPE_PAGETOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
296
297 Console::SafeVMPtr pVM (mParent);
298 if (pVM.isOk())
299 {
300 uint64_t uFreeTotal, uAllocTotal, uBalloonedTotal;
301 *aMemFreeTotal = 0;
302 int rc = PGMR3QueryVMMMemoryStats(pVM.raw(), &uAllocTotal, &uFreeTotal, &uBalloonedTotal);
303 AssertRC(rc);
304 if (rc == VINF_SUCCESS)
305 {
306 *aMemAllocTotal = (ULONG)(uAllocTotal / _1K); /* bytes -> KB */
307 *aMemFreeTotal = (ULONG)(uFreeTotal / _1K);
308 *aMemBalloonTotal = (ULONG)(uBalloonedTotal / _1K);
309 }
310 }
311 else
312 *aMemFreeTotal = 0;
313
314 return S_OK;
315}
316
317HRESULT Guest::SetStatistic(ULONG aCpuId, GUESTSTATTYPE enmType, ULONG aVal)
318{
319 AutoCaller autoCaller(this);
320 if (FAILED(autoCaller.rc())) return autoCaller.rc();
321
322 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
323
324 if (enmType >= GUESTSTATTYPE_MAX)
325 return E_INVALIDARG;
326
327 mCurrentGuestStat[enmType] = aVal;
328 return S_OK;
329}
330
331STDMETHODIMP Guest::SetCredentials(IN_BSTR aUserName, IN_BSTR aPassword,
332 IN_BSTR aDomain, BOOL aAllowInteractiveLogon)
333{
334 AutoCaller autoCaller(this);
335 if (FAILED(autoCaller.rc())) return autoCaller.rc();
336
337 /* forward the information to the VMM device */
338 VMMDev *vmmDev = mParent->getVMMDev();
339 if (vmmDev)
340 {
341 uint32_t u32Flags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
342 if (!aAllowInteractiveLogon)
343 u32Flags = VMMDEV_SETCREDENTIALS_NOLOCALLOGON;
344
345 vmmDev->getVMMDevPort()->pfnSetCredentials(vmmDev->getVMMDevPort(),
346 Utf8Str(aUserName).raw(), Utf8Str(aPassword).raw(),
347 Utf8Str(aDomain).raw(), u32Flags);
348 return S_OK;
349 }
350
351 return setError(VBOX_E_VM_ERROR,
352 tr("VMM device is not available (is the VM running?)"));
353}
354
355#ifdef VBOX_WITH_GUEST_CONTROL
356/**
357 * Creates the argument list as an array used for executing a program.
358 *
359 * @returns VBox status code.
360 *
361 * @todo
362 *
363 * @todo Respect spaces when quoting for arguments, e.g. "c:\\program files\\".
364 * @todo Handle empty ("") argguments.
365 */
366int Guest::prepareExecuteArgs(const char *pszArgs, void **ppvList, uint32_t *pcbList, uint32_t *pcArgs)
367{
368 char **ppaArg;
369 int iArgs;
370 int rc = RTGetOptArgvFromString(&ppaArg, &iArgs, pszArgs, NULL);
371 if (RT_SUCCESS(rc))
372 {
373 char *pszTemp = NULL;
374 *pcbList = 0;
375 for (int i=0; i<iArgs; i++)
376 {
377 if (i > 0) /* Insert space as delimiter. */
378 rc = RTStrAAppendN(&pszTemp, " ", 1);
379
380 if (RT_FAILURE(rc))
381 break;
382 else
383 {
384 rc = RTStrAAppendN(&pszTemp, ppaArg[i], strlen(ppaArg[i]));
385 if (RT_FAILURE(rc))
386 break;
387 }
388 }
389 RTGetOptArgvFree(ppaArg);
390 if (RT_SUCCESS(rc))
391 {
392 *ppvList = pszTemp;
393 *pcArgs = iArgs;
394 if (pszTemp)
395 *pcbList = strlen(pszTemp) + 1; /* Include zero termination. */
396 }
397 else
398 RTStrFree(pszTemp);
399 }
400 return rc;
401}
402
403/**
404 * Appends environment variables to the environment block. Each var=value pair is separated
405 * by NULL (\0) sequence. The whole block will be stored in one blob and disassembled on the
406 * guest side later to fit into the HGCM param structure.
407 *
408 * @returns VBox status code.
409 *
410 * @todo
411 *
412 */
413int Guest::prepareExecuteEnv(const char *pszEnv, void **ppvList, uint32_t *pcbList, uint32_t *pcEnv)
414{
415 int rc = VINF_SUCCESS;
416 uint32_t cbLen = strlen(pszEnv);
417 if (*ppvList)
418 {
419 uint32_t cbNewLen = *pcbList + cbLen + 1; /* Include zero termination. */
420 char *pvTmp = (char*)RTMemRealloc(*ppvList, cbNewLen);
421 if (NULL == pvTmp)
422 {
423 rc = VERR_NO_MEMORY;
424 }
425 else
426 {
427 memcpy(pvTmp + *pcbList, pszEnv, cbLen);
428 pvTmp[cbNewLen - 1] = '\0'; /* Add zero termination. */
429 *ppvList = (void**)pvTmp;
430 }
431 }
432 else
433 {
434 char *pcTmp;
435 if (RTStrAPrintf(&pcTmp, "%s", pszEnv) > 0)
436 {
437 *ppvList = (void**)pcTmp;
438 /* Reset counters. */
439 *pcEnv = 0;
440 *pcbList = 0;
441 }
442 }
443 if (RT_SUCCESS(rc))
444 {
445 *pcbList += cbLen + 1; /* Include zero termination. */
446 *pcEnv += 1; /* Increase env pairs count. */
447 }
448 return rc;
449}
450
451/**
452 * Static callback function for receiving updates on guest control commands
453 * from the guest. Acts as a dispatcher for the actual class instance.
454 *
455 * @returns VBox status code.
456 *
457 * @todo
458 *
459 */
460DECLCALLBACK(int) Guest::doGuestCtrlNotification(void *pvExtension,
461 uint32_t u32Function,
462 void *pvParms,
463 uint32_t cbParms)
464{
465 using namespace guestControl;
466
467 /*
468 * No locking, as this is purely a notification which does not make any
469 * changes to the object state.
470 */
471 LogFlowFunc(("pvExtension = %p, u32Function = %d, pvParms = %p, cbParms = %d\n",
472 pvExtension, u32Function, pvParms, cbParms));
473 ComObjPtr<Guest> pGuest = reinterpret_cast<Guest *>(pvExtension);
474
475 int rc = VINF_SUCCESS;
476 if (u32Function == GUEST_EXEC_SEND_STATUS)
477 {
478 LogFlowFunc(("GUEST_EXEC_SEND_STATUS\n"));
479
480 PHOSTEXECCALLBACKDATA pCBData = reinterpret_cast<PHOSTEXECCALLBACKDATA>(pvParms);
481 AssertPtr(pCBData);
482 AssertReturn(sizeof(HOSTEXECCALLBACKDATA) == cbParms, VERR_INVALID_PARAMETER);
483 AssertReturn(HOSTEXECCALLBACKDATAMAGIC == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
484
485 rc = pGuest->notifyCtrlExec(u32Function, pCBData);
486 }
487 else
488 rc = VERR_NOT_SUPPORTED;
489 return rc;
490}
491
492/* Notifier function for control execution stuff. */
493int Guest::notifyCtrlExec(uint32_t u32Function,
494 PHOSTEXECCALLBACKDATA pData)
495{
496 LogFlowFuncEnter();
497 int rc = VINF_SUCCESS;
498
499 AssertPtr(pData);
500 CallbackListIter it = getCtrlCallbackContext(pData->hdr.u32ContextID);
501 if (it != mCallbackList.end())
502 {
503 PHOSTEXECCALLBACKDATA pCBData = (HOSTEXECCALLBACKDATA*)it->pvData;
504 AssertPtr(pCBData);
505
506 pCBData->u32PID = pData->u32PID;
507 pCBData->u32Status = pData->u32Status;
508 pCBData->u32Flags = pData->u32Flags;
509 /* @todo Copy void* buffer contents! */
510
511 /* Do progress handling. */
512 Utf8Str errMsg;
513 HRESULT rc2 = S_OK;
514 switch (pData->u32Status)
515 {
516 case PROC_STS_STARTED:
517 break;
518
519 case PROC_STS_TEN: /* Terminated normally. */
520 it->pProgress->notifyComplete(S_OK);
521 break;
522
523 case PROC_STS_TEA: /* Terminated abnormally. */
524 errMsg = Utf8StrFmt(Guest::tr("Process terminated abnormally with status '%u'"),
525 pCBData->u32Flags);
526 break;
527
528 case PROC_STS_TES: /* Terminated through signal. */
529 errMsg = Utf8StrFmt(Guest::tr("Process terminated via signal with status '%u'"),
530 pCBData->u32Flags);
531 break;
532
533 case PROC_STS_TOK:
534 errMsg = Utf8StrFmt(Guest::tr("Process timed out and was killed"));
535 break;
536
537 case PROC_STS_TOA:
538 errMsg = Utf8StrFmt(Guest::tr("Process timed out and could not be killed"));
539 break;
540
541 case PROC_STS_DWN:
542 errMsg = Utf8StrFmt(Guest::tr("Process exited because system is shutting down"));
543 break;
544
545 default:
546 break;
547 }
548
549 if ( !it->pProgress.isNull()
550 && errMsg.length())
551 {
552 it->pProgress->notifyComplete(E_FAIL /** @todo Find a better rc! */, COM_IIDOF(IGuest),
553 (CBSTR)Guest::getComponentName(), errMsg.c_str());
554 }
555 ASMAtomicWriteBool(&it->bCalled, true);
556 }
557 LogFlowFuncLeave();
558 return rc;
559}
560
561Guest::CallbackListIter Guest::getCtrlCallbackContext(uint32_t u32ContextID)
562{
563 CallbackListIter it;
564 for (it = mCallbackList.begin(); it != mCallbackList.end(); it++)
565 {
566 if (it->mContextID == u32ContextID)
567 return (it);
568 }
569 return it;
570}
571
572void Guest::removeCtrlCallbackContext(Guest::CallbackListIter it)
573{
574 LogFlowFuncEnter();
575 if (it->cbData)
576 {
577 RTMemFree(it->pvData);
578 it->cbData = 0;
579 it->pvData = NULL;
580
581 /* Notify outstanding waits for progress ... */
582 if (!it->pProgress.isNull())
583 {
584 it->pProgress->notifyComplete(S_OK);
585 it->pProgress = NULL;
586 }
587 }
588 mCallbackList.erase(it);
589 LogFlowFuncLeave();
590}
591
592/* Adds a callback with a user provided data block and an optional progress object
593 * to the callback list. A callback is identified by a unique context ID which is used
594 * to identify a callback from the guest side. */
595uint32_t Guest::addCtrlCallbackContext(void *pvData, uint32_t cbData, Progress* pProgress)
596{
597 LogFlowFuncEnter();
598
599 uint32_t uNewContext = ASMAtomicIncU32(&mNextContextID);
600 if (uNewContext == UINT32_MAX)
601 ASMAtomicUoWriteU32(&mNextContextID, 1000);
602
603 CallbackContext context;
604 context.mContextID = uNewContext;
605 context.bCalled = false;
606 context.pvData = pvData;
607 context.cbData = cbData;
608 context.pProgress = pProgress;
609
610 mCallbackList.push_back(context);
611 if (mCallbackList.size() > 256) /* Don't let the container size get too big! */
612 removeCtrlCallbackContext(mCallbackList.begin());
613
614 LogFlowFuncLeave();
615 return uNewContext;
616}
617#endif /* VBOX_WITH_GUEST_CONTROL */
618
619STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
620 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
621 IN_BSTR aStdIn, IN_BSTR aStdOut, IN_BSTR aStdErr,
622 IN_BSTR aUserName, IN_BSTR aPassword,
623 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
624{
625#ifndef VBOX_WITH_GUEST_CONTROL
626 ReturnComNotImplemented();
627#else /* VBOX_WITH_GUEST_CONTROL */
628 using namespace guestControl;
629
630 CheckComArgStrNotEmptyOrNull(aCommand);
631 CheckComArgOutPointerValid(aPID);
632 CheckComArgOutPointerValid(aProgress);
633 if (aFlags != 0) /* Flags are not supported at the moment. */
634 return E_INVALIDARG;
635
636 HRESULT rc = S_OK;
637
638 try
639 {
640 AutoCaller autoCaller(this);
641 if (FAILED(autoCaller.rc())) return autoCaller.rc();
642
643 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
644
645 /*
646 * Create progress object.
647 */
648 ComObjPtr <Progress> progress;
649 rc = progress.createObject();
650 if (SUCCEEDED(rc))
651 {
652 rc = progress->init(static_cast<IGuest*>(this),
653 BstrFmt(tr("Executing process")),
654 FALSE);
655 }
656 if (FAILED(rc)) return rc;
657
658 /*
659 * Prepare process execution.
660 */
661 int vrc = VINF_SUCCESS;
662 Utf8Str Utf8Command(aCommand);
663
664 /* Adjust timeout */
665 if (aTimeoutMS == 0)
666 aTimeoutMS = UINT32_MAX;
667
668 /* Prepare arguments. */
669 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
670 uint32_t uNumArgs = args.size();
671 char **papszArgv = NULL;
672 if(uNumArgs > 0)
673 {
674 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
675 AssertPtr(papszArgv);
676 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
677 vrc = RTStrAPrintf(&papszArgv[i], "%s", Utf8Str(args[i]).raw());
678 papszArgv[uNumArgs] = NULL;
679 }
680
681 Utf8Str Utf8StdIn(aStdIn);
682 Utf8Str Utf8StdOut(aStdOut);
683 Utf8Str Utf8StdErr(aStdErr);
684 Utf8Str Utf8UserName(aUserName);
685 Utf8Str Utf8Password(aPassword);
686 if (RT_SUCCESS(vrc))
687 {
688 uint32_t uContextID = 0;
689
690 char *pszArgs = NULL;
691 if (uNumArgs > 0)
692 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, 0);
693 if (RT_SUCCESS(vrc))
694 {
695 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
696
697 /* Prepare environment. */
698 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
699
700 void *pvEnv = NULL;
701 uint32_t uNumEnv = 0;
702 uint32_t cbEnv = 0;
703
704 for (unsigned i = 0; i < env.size(); i++)
705 {
706 vrc = prepareExecuteEnv(Utf8Str(env[i]).raw(), &pvEnv, &cbEnv, &uNumEnv);
707 if (RT_FAILURE(vrc))
708 break;
709 }
710
711 if (RT_SUCCESS(vrc))
712 {
713 PHOSTEXECCALLBACKDATA pData = (HOSTEXECCALLBACKDATA*)RTMemAlloc(sizeof(HOSTEXECCALLBACKDATA));
714 AssertPtr(pData);
715 uContextID = addCtrlCallbackContext(pData, sizeof(HOSTEXECCALLBACKDATA), progress);
716 Assert(uContextID > 0);
717
718 VBOXHGCMSVCPARM paParms[15];
719 int i = 0;
720 paParms[i++].setUInt32(uContextID);
721 paParms[i++].setPointer((void*)Utf8Command.raw(), (uint32_t)strlen(Utf8Command.raw()) + 1);
722 paParms[i++].setUInt32(aFlags);
723 paParms[i++].setUInt32(uNumArgs);
724 paParms[i++].setPointer((void*)pszArgs, cbArgs);
725 paParms[i++].setUInt32(uNumEnv);
726 paParms[i++].setUInt32(cbEnv);
727 paParms[i++].setPointer((void*)pvEnv, cbEnv);
728 paParms[i++].setPointer((void*)Utf8StdIn.raw(), (uint32_t)strlen(Utf8StdIn.raw()) + 1);
729 paParms[i++].setPointer((void*)Utf8StdOut.raw(), (uint32_t)strlen(Utf8StdOut.raw()) + 1);
730 paParms[i++].setPointer((void*)Utf8StdErr.raw(), (uint32_t)strlen(Utf8StdErr.raw()) + 1);
731 paParms[i++].setPointer((void*)Utf8UserName.raw(), (uint32_t)strlen(Utf8UserName.raw()) + 1);
732 paParms[i++].setPointer((void*)Utf8Password.raw(), (uint32_t)strlen(Utf8Password.raw()) + 1);
733 paParms[i++].setUInt32(aTimeoutMS);
734
735 /* Forward the information to the VMM device. */
736 AssertPtr(mParent);
737 VMMDev *vmmDev = mParent->getVMMDev();
738 if (vmmDev)
739 {
740 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
741 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
742 i, paParms);
743 }
744 RTMemFree(pvEnv);
745 }
746 RTStrFree(pszArgs);
747 }
748 if (RT_SUCCESS(vrc))
749 {
750 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
751
752 /*
753 * Wait for the HGCM low level callback until the process
754 * has been started (or something went wrong). This is necessary to
755 * get the PID.
756 */
757 CallbackListIter it = getCtrlCallbackContext(uContextID);
758 uint64_t u64Started = RTTimeMilliTS();
759 do
760 {
761 unsigned cMsWait;
762 if (aTimeoutMS == RT_INDEFINITE_WAIT)
763 cMsWait = 1000;
764 else
765 {
766 uint64_t cMsElapsed = RTTimeMilliTS() - u64Started;
767 if (cMsElapsed >= aTimeoutMS)
768 break; /* timed out */
769 cMsWait = RT_MIN(1000, aTimeoutMS - (uint32_t)cMsElapsed);
770 }
771 RTThreadSleep(100);
772 } while (it != mCallbackList.end() && !it->bCalled);
773
774 /* Did we get some status? */
775 PHOSTEXECCALLBACKDATA pData = (HOSTEXECCALLBACKDATA*)it->pvData;
776 Assert(it->cbData == sizeof(HOSTEXECCALLBACKDATA));
777 AssertPtr(pData);
778 if (it->bCalled)
779 {
780 switch (pData->u32Status)
781 {
782 case PROC_STS_STARTED:
783 *aPID = pData->u32PID;
784 break;
785
786 case PROC_STS_ERROR:
787 vrc = pData->u32Flags; /* u32Flags member contains IPRT error code. */
788 break;
789
790 default:
791 vrc = VERR_INVALID_PARAMETER;
792 break;
793 }
794 }
795 else /* If callback not called within time ... well, that's a timeout! */
796 vrc = VERR_TIMEOUT;
797
798 /*
799 * Do *not* remove the callback yet - we might wait with the IProgress object on something
800 * else (like end of process) ...
801 */
802 if (RT_FAILURE(vrc))
803 {
804 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
805 {
806 rc = setError(VBOX_E_IPRT_ERROR,
807 tr("The file '%s' was not found on guest"), Utf8Command.raw());
808 }
809 else if (vrc == VERR_BAD_EXE_FORMAT)
810 {
811 rc = setError(VBOX_E_IPRT_ERROR,
812 tr("The file '%s' is not an executable format on guest"), Utf8Command.raw());
813 }
814 else if (vrc == VERR_LOGON_FAILURE)
815 {
816 rc = setError(VBOX_E_IPRT_ERROR,
817 tr("The specified user '%s' was not able to logon on guest"), Utf8UserName.raw());
818 }
819 else if (vrc == VERR_TIMEOUT)
820 {
821 rc = setError(VBOX_E_IPRT_ERROR,
822 tr("The guest did not respond within time (%ums)"), aTimeoutMS);
823 }
824 else
825 {
826 rc = setError(E_UNEXPECTED,
827 tr("The service call failed with error %Rrc"), vrc);
828 }
829 }
830 else
831 {
832 /* Return the progress to the caller. */
833 progress.queryInterfaceTo(aProgress);
834 }
835 }
836 else
837 {
838 /* HGCM call went wrong. */
839 rc = setError(E_UNEXPECTED,
840 tr("The service call failed with error %Rrc"), vrc);
841 }
842
843 for (unsigned i = 0; i < uNumArgs; i++)
844 RTMemFree(papszArgv[i]);
845 RTMemFree(papszArgv);
846 }
847 }
848 catch (std::bad_alloc &)
849 {
850 rc = E_OUTOFMEMORY;
851 }
852 return rc;
853#endif /* VBOX_WITH_GUEST_CONTROL */
854}
855
856STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
857{
858#ifndef VBOX_WITH_GUEST_CONTROL
859 ReturnComNotImplemented();
860#else /* VBOX_WITH_GUEST_CONTROL */
861 using namespace guestControl;
862
863 NOREF(aPID);
864 NOREF(aFlags);
865 NOREF(aSize);
866 NOREF(aData);
867
868 HRESULT rc = S_OK;
869
870 size_t cbData = (size_t)RT_MIN(aSize, _1K);
871 com::SafeArray<BYTE> outputData(cbData);
872
873 if (FAILED(rc))
874 outputData.resize(0);
875 outputData.detachTo(ComSafeArrayOutArg(aData));
876
877 return rc;
878#endif
879}
880
881// public methods only for internal purposes
882/////////////////////////////////////////////////////////////////////////////
883
884void Guest::setAdditionsVersion(Bstr aVersion, VBOXOSTYPE aOsType)
885{
886 AutoCaller autoCaller(this);
887 AssertComRCReturnVoid (autoCaller.rc());
888
889 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
890
891 mData.mAdditionsVersion = aVersion;
892 mData.mAdditionsActive = !aVersion.isEmpty();
893 /* Older Additions didn't have this finer grained capability bit,
894 * so enable it by default. Newer Additions will disable it immediately
895 * if relevant. */
896 mData.mSupportsGraphics = mData.mAdditionsActive;
897
898 mData.mOSTypeId = Global::OSTypeId (aOsType);
899}
900
901void Guest::setSupportsSeamless (BOOL aSupportsSeamless)
902{
903 AutoCaller autoCaller(this);
904 AssertComRCReturnVoid (autoCaller.rc());
905
906 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
907
908 mData.mSupportsSeamless = aSupportsSeamless;
909}
910
911void Guest::setSupportsGraphics (BOOL aSupportsGraphics)
912{
913 AutoCaller autoCaller(this);
914 AssertComRCReturnVoid (autoCaller.rc());
915
916 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
917
918 mData.mSupportsGraphics = aSupportsGraphics;
919}
920/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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