VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestProcessImpl.cpp@ 47798

Last change on this file since 47798 was 47630, checked in by vboxsync, 11 years ago

build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 70.1 KB
Line 
1
2/* $Id: GuestProcessImpl.cpp 47630 2013-08-09 09:45:09Z vboxsync $ */
3/** @file
4 * VirtualBox Main - Guest process handling.
5 */
6
7/*
8 * Copyright (C) 2012-2013 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19/**
20 * Locking rules:
21 * - When the main dispatcher (callbackDispatcher) is called it takes the
22 * WriteLock while dispatching to the various on* methods.
23 * - All other outer functions (accessible by Main) must not own a lock
24 * while waiting for a callback or for an event.
25 * - Only keep Read/WriteLocks as short as possible and only when necessary.
26 */
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include "GuestProcessImpl.h"
32#include "GuestSessionImpl.h"
33#include "GuestCtrlImplPrivate.h"
34#include "ConsoleImpl.h"
35#include "VirtualBoxErrorInfoImpl.h"
36
37#include "Global.h"
38#include "AutoCaller.h"
39#include "VBoxEvents.h"
40
41#include <memory> /* For auto_ptr. */
42
43#include <iprt/asm.h>
44#include <iprt/cpp/utils.h> /* For unconst(). */
45#include <iprt/getopt.h>
46
47#include <VBox/com/listeners.h>
48
49#include <VBox/com/array.h>
50
51#ifdef LOG_GROUP
52 #undef LOG_GROUP
53#endif
54#define LOG_GROUP LOG_GROUP_GUEST_CONTROL
55#include <VBox/log.h>
56
57
58class GuestProcessTask
59{
60public:
61
62 GuestProcessTask(GuestProcess *pProcess)
63 : mProcess(pProcess),
64 mRC(VINF_SUCCESS) { }
65
66 virtual ~GuestProcessTask(void) { }
67
68 int rc(void) const { return mRC; }
69 bool isOk(void) const { return RT_SUCCESS(mRC); }
70 const ComObjPtr<GuestProcess> &Process(void) const { return mProcess; }
71
72protected:
73
74 const ComObjPtr<GuestProcess> mProcess;
75 int mRC;
76};
77
78class GuestProcessStartTask : public GuestProcessTask
79{
80public:
81
82 GuestProcessStartTask(GuestProcess *pProcess)
83 : GuestProcessTask(pProcess) { }
84};
85
86/**
87 * Internal listener class to serve events in an
88 * active manner, e.g. without polling delays.
89 */
90class GuestProcessListener
91{
92public:
93
94 GuestProcessListener(void)
95 {
96 }
97
98 HRESULT init(GuestProcess *pProcess)
99 {
100 mProcess = pProcess;
101 return S_OK;
102 }
103
104 void uninit(void)
105 {
106 mProcess.setNull();
107 }
108
109 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
110 {
111 switch (aType)
112 {
113 case VBoxEventType_OnGuestProcessStateChanged:
114 case VBoxEventType_OnGuestProcessInputNotify:
115 case VBoxEventType_OnGuestProcessOutput:
116 {
117 Assert(!mProcess.isNull());
118 int rc2 = mProcess->signalWaitEvents(aType, aEvent);
119#ifdef DEBUG_andy
120 LogFlowThisFunc(("Signalling events of type=%ld, process=%p resulted in rc=%Rrc\n",
121 aType, mProcess, rc2));
122#endif
123 break;
124 }
125
126 default:
127 AssertMsgFailed(("Unhandled event %ld\n", aType));
128 break;
129 }
130
131 return S_OK;
132 }
133
134private:
135
136 ComObjPtr<GuestProcess> mProcess;
137};
138typedef ListenerImpl<GuestProcessListener, GuestProcess*> GuestProcessListenerImpl;
139
140VBOX_LISTENER_DECLARE(GuestProcessListenerImpl)
141
142// constructor / destructor
143/////////////////////////////////////////////////////////////////////////////
144
145DEFINE_EMPTY_CTOR_DTOR(GuestProcess)
146
147HRESULT GuestProcess::FinalConstruct(void)
148{
149 LogFlowThisFuncEnter();
150 return BaseFinalConstruct();
151}
152
153void GuestProcess::FinalRelease(void)
154{
155 LogFlowThisFuncEnter();
156 uninit();
157 BaseFinalRelease();
158 LogFlowThisFuncLeave();
159}
160
161// public initializer/uninitializer for internal purposes only
162/////////////////////////////////////////////////////////////////////////////
163
164int GuestProcess::init(Console *aConsole, GuestSession *aSession,
165 ULONG aProcessID, const GuestProcessStartupInfo &aProcInfo)
166{
167 LogFlowThisFunc(("aConsole=%p, aSession=%p, aProcessID=%RU32\n",
168 aConsole, aSession, aProcessID));
169
170 AssertPtrReturn(aConsole, VERR_INVALID_POINTER);
171 AssertPtrReturn(aSession, VERR_INVALID_POINTER);
172
173 /* Enclose the state transition NotReady->InInit->Ready. */
174 AutoInitSpan autoInitSpan(this);
175 AssertReturn(autoInitSpan.isOk(), VERR_OBJECT_DESTROYED);
176
177#ifndef VBOX_WITH_GUEST_CONTROL
178 autoInitSpan.setSucceeded();
179 return VINF_SUCCESS;
180#else
181 HRESULT hr;
182
183 int vrc = bindToSession(aConsole, aSession, aProcessID /* Object ID */);
184 if (RT_SUCCESS(vrc))
185 {
186 hr = unconst(mEventSource).createObject();
187 if (FAILED(hr))
188 vrc = VERR_NO_MEMORY;
189 else
190 {
191 hr = mEventSource->init(static_cast<IGuestProcess*>(this));
192 if (FAILED(hr))
193 vrc = VERR_COM_UNEXPECTED;
194 }
195 }
196
197 if (RT_SUCCESS(vrc))
198 {
199 try
200 {
201 GuestProcessListener *pListener = new GuestProcessListener();
202 ComObjPtr<GuestProcessListenerImpl> thisListener;
203 hr = thisListener.createObject();
204 if (SUCCEEDED(hr))
205 hr = thisListener->init(pListener, this);
206
207 if (SUCCEEDED(hr))
208 {
209 com::SafeArray <VBoxEventType_T> eventTypes;
210 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
211 eventTypes.push_back(VBoxEventType_OnGuestProcessInputNotify);
212 eventTypes.push_back(VBoxEventType_OnGuestProcessOutput);
213 hr = mEventSource->RegisterListener(thisListener,
214 ComSafeArrayAsInParam(eventTypes),
215 TRUE /* Active listener */);
216 if (SUCCEEDED(hr))
217 {
218 vrc = baseInit();
219 if (RT_SUCCESS(vrc))
220 {
221 mLocalListener = thisListener;
222 }
223 }
224 else
225 vrc = VERR_COM_UNEXPECTED;
226 }
227 else
228 vrc = VERR_COM_UNEXPECTED;
229 }
230 catch(std::bad_alloc &)
231 {
232 vrc = VERR_NO_MEMORY;
233 }
234 }
235
236 if (RT_SUCCESS(vrc))
237 {
238 mData.mProcess = aProcInfo;
239 mData.mExitCode = 0;
240 mData.mPID = 0;
241 mData.mRC = VINF_SUCCESS;
242 mData.mStatus = ProcessStatus_Undefined;
243 /* Everything else will be set by the actual starting routine. */
244
245 /* Confirm a successful initialization when it's the case. */
246 autoInitSpan.setSucceeded();
247
248 return vrc;
249 }
250
251 autoInitSpan.setFailed();
252 return vrc;
253#endif
254}
255
256/**
257 * Uninitializes the instance.
258 * Called from FinalRelease().
259 */
260void GuestProcess::uninit(void)
261{
262 LogFlowThisFuncEnter();
263
264 /* Enclose the state transition Ready->InUninit->NotReady. */
265 AutoUninitSpan autoUninitSpan(this);
266 if (autoUninitSpan.uninitDone())
267 return;
268
269 LogFlowThisFunc(("mCmd=%s, PID=%RU32\n",
270 mData.mProcess.mCommand.c_str(), mData.mPID));
271
272 /* Terminate process if not already done yet. */
273 int guestRc = VINF_SUCCESS;
274 int vrc = terminateProcess(30 * 1000, &guestRc); /** @todo Make timeouts configurable. */
275 /* Note: Don't return here yet; first uninit all other stuff in
276 * case of failure. */
277
278#ifdef VBOX_WITH_GUEST_CONTROL
279 baseUninit();
280
281 mEventSource->UnregisterListener(mLocalListener);
282
283 mLocalListener.setNull();
284 unconst(mEventSource).setNull();
285#endif
286
287 LogFlowThisFunc(("Returning rc=%Rrc, guestRc=%Rrc\n",
288 vrc, guestRc));
289}
290
291// implementation of public getters/setters for attributes
292/////////////////////////////////////////////////////////////////////////////
293
294STDMETHODIMP GuestProcess::COMGETTER(Arguments)(ComSafeArrayOut(BSTR, aArguments))
295{
296#ifndef VBOX_WITH_GUEST_CONTROL
297 ReturnComNotImplemented();
298#else
299 LogFlowThisFuncEnter();
300
301 CheckComArgOutSafeArrayPointerValid(aArguments);
302
303 AutoCaller autoCaller(this);
304 if (FAILED(autoCaller.rc())) return autoCaller.rc();
305
306 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
307
308 com::SafeArray<BSTR> collection(mData.mProcess.mArguments.size());
309 size_t s = 0;
310 for (ProcessArguments::const_iterator it = mData.mProcess.mArguments.begin();
311 it != mData.mProcess.mArguments.end();
312 it++, s++)
313 {
314 Bstr tmp = *it;
315 tmp.cloneTo(&collection[s]);
316 }
317
318 collection.detachTo(ComSafeArrayOutArg(aArguments));
319
320 return S_OK;
321#endif /* VBOX_WITH_GUEST_CONTROL */
322}
323
324STDMETHODIMP GuestProcess::COMGETTER(Environment)(ComSafeArrayOut(BSTR, aEnvironment))
325{
326#ifndef VBOX_WITH_GUEST_CONTROL
327 ReturnComNotImplemented();
328#else
329 LogFlowThisFuncEnter();
330
331 CheckComArgOutSafeArrayPointerValid(aEnvironment);
332
333 AutoCaller autoCaller(this);
334 if (FAILED(autoCaller.rc())) return autoCaller.rc();
335
336 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
337
338 com::SafeArray<BSTR> arguments(mData.mProcess.mEnvironment.Size());
339 for (size_t i = 0; i < arguments.size(); i++)
340 {
341 Bstr tmp = mData.mProcess.mEnvironment.Get(i);
342 tmp.cloneTo(&arguments[i]);
343 }
344 arguments.detachTo(ComSafeArrayOutArg(aEnvironment));
345
346 return S_OK;
347#endif /* VBOX_WITH_GUEST_CONTROL */
348}
349
350STDMETHODIMP GuestProcess::COMGETTER(EventSource)(IEventSource ** aEventSource)
351{
352#ifndef VBOX_WITH_GUEST_CONTROL
353 ReturnComNotImplemented();
354#else
355 LogFlowThisFuncEnter();
356
357 CheckComArgOutPointerValid(aEventSource);
358
359 AutoCaller autoCaller(this);
360 if (FAILED(autoCaller.rc())) return autoCaller.rc();
361
362 // no need to lock - lifetime constant
363 mEventSource.queryInterfaceTo(aEventSource);
364
365 LogFlowThisFuncLeave();
366 return S_OK;
367#endif /* VBOX_WITH_GUEST_CONTROL */
368}
369
370STDMETHODIMP GuestProcess::COMGETTER(ExecutablePath)(BSTR *aExecutablePath)
371{
372#ifndef VBOX_WITH_GUEST_CONTROL
373 ReturnComNotImplemented();
374#else
375 LogFlowThisFuncEnter();
376
377 CheckComArgOutPointerValid(aExecutablePath);
378
379 AutoCaller autoCaller(this);
380 if (FAILED(autoCaller.rc())) return autoCaller.rc();
381
382 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
383
384 mData.mProcess.mCommand.cloneTo(aExecutablePath);
385
386 return S_OK;
387#endif /* VBOX_WITH_GUEST_CONTROL */
388}
389
390STDMETHODIMP GuestProcess::COMGETTER(ExitCode)(LONG *aExitCode)
391{
392#ifndef VBOX_WITH_GUEST_CONTROL
393 ReturnComNotImplemented();
394#else
395 LogFlowThisFuncEnter();
396
397 CheckComArgOutPointerValid(aExitCode);
398
399 AutoCaller autoCaller(this);
400 if (FAILED(autoCaller.rc())) return autoCaller.rc();
401
402 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
403
404 *aExitCode = mData.mExitCode;
405
406 return S_OK;
407#endif /* VBOX_WITH_GUEST_CONTROL */
408}
409
410STDMETHODIMP GuestProcess::COMGETTER(Name)(BSTR *aName)
411{
412#ifndef VBOX_WITH_GUEST_CONTROL
413 ReturnComNotImplemented();
414#else
415 LogFlowThisFuncEnter();
416
417 CheckComArgOutPointerValid(aName);
418
419 AutoCaller autoCaller(this);
420 if (FAILED(autoCaller.rc())) return autoCaller.rc();
421
422 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
423
424 mData.mProcess.mName.cloneTo(aName);
425
426 return S_OK;
427#endif /* VBOX_WITH_GUEST_CONTROL */
428}
429
430STDMETHODIMP GuestProcess::COMGETTER(PID)(ULONG *aPID)
431{
432#ifndef VBOX_WITH_GUEST_CONTROL
433 ReturnComNotImplemented();
434#else
435 LogFlowThisFuncEnter();
436
437 CheckComArgOutPointerValid(aPID);
438
439 AutoCaller autoCaller(this);
440 if (FAILED(autoCaller.rc())) return autoCaller.rc();
441
442 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
443
444 *aPID = mData.mPID;
445
446 return S_OK;
447#endif /* VBOX_WITH_GUEST_CONTROL */
448}
449
450STDMETHODIMP GuestProcess::COMGETTER(Status)(ProcessStatus_T *aStatus)
451{
452#ifndef VBOX_WITH_GUEST_CONTROL
453 ReturnComNotImplemented();
454#else
455 LogFlowThisFuncEnter();
456
457 AutoCaller autoCaller(this);
458 if (FAILED(autoCaller.rc())) return autoCaller.rc();
459
460 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
461
462 *aStatus = mData.mStatus;
463
464 return S_OK;
465#endif /* VBOX_WITH_GUEST_CONTROL */
466}
467
468// private methods
469/////////////////////////////////////////////////////////////////////////////
470
471int GuestProcess::callbackDispatcher(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
472{
473 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
474 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
475#ifdef DEBUG
476 LogFlowThisFunc(("uPID=%RU32, uContextID=%RU32, uFunction=%RU32, pSvcCb=%p\n",
477 mData.mPID, pCbCtx->uContextID, pCbCtx->uFunction, pSvcCb));
478#endif
479
480 int vrc;
481 switch (pCbCtx->uFunction)
482 {
483 case GUEST_DISCONNECTED:
484 {
485 vrc = onGuestDisconnected(pCbCtx, pSvcCb);
486 break;
487 }
488
489 case GUEST_EXEC_STATUS:
490 {
491 vrc = onProcessStatusChange(pCbCtx, pSvcCb);
492 break;
493 }
494
495 case GUEST_EXEC_OUTPUT:
496 {
497 vrc = onProcessOutput(pCbCtx, pSvcCb);
498 break;
499 }
500
501 case GUEST_EXEC_INPUT_STATUS:
502 {
503 vrc = onProcessInputStatus(pCbCtx, pSvcCb);
504 break;
505 }
506
507 default:
508 /* Silently ignore not implemented functions. */
509 vrc = VERR_NOT_SUPPORTED;
510 break;
511 }
512
513#ifdef DEBUG
514 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
515#endif
516 return vrc;
517}
518
519/**
520 * Checks if the current assigned PID matches another PID (from a callback).
521 *
522 * In protocol v1 we don't have the possibility to terminate/kill
523 * processes so it can happen that a formerly started process A
524 * (which has the context ID 0 (session=0, process=0, count=0) will
525 * send a delayed message to the host if this process has already
526 * been discarded there and the same context ID was reused by
527 * a process B. Process B in turn then has a different guest PID.
528 *
529 * @return IPRT status code.
530 * @param uPID PID to check.
531 */
532inline int GuestProcess::checkPID(uint32_t uPID)
533{
534 /* Was there a PID assigned yet? */
535 if (mData.mPID)
536 {
537 /*
538
539 */
540 if (mSession->getProtocolVersion() < 2)
541 {
542 /* Simply ignore the stale requests. */
543 return (mData.mPID == uPID)
544 ? VINF_SUCCESS : VERR_NOT_FOUND;
545 }
546#ifndef DEBUG_andy
547 /* This should never happen! */
548 AssertReleaseMsg(mData.mPID == uPID, ("Unterminated guest process (guest PID %RU32) sent data to a newly started process (host PID %RU32)\n",
549 uPID, mData.mPID));
550#endif
551 }
552
553 return VINF_SUCCESS;
554}
555
556/* static */
557Utf8Str GuestProcess::guestErrorToString(int guestRc)
558{
559 Utf8Str strError;
560
561 /** @todo pData->u32Flags: int vs. uint32 -- IPRT errors are *negative* !!! */
562 switch (guestRc)
563 {
564 case VERR_FILE_NOT_FOUND: /* This is the most likely error. */
565 strError += Utf8StrFmt(tr("The specified file was not found on guest"));
566 break;
567
568 case VERR_INVALID_VM_HANDLE:
569 strError += Utf8StrFmt(tr("VMM device is not available (is the VM running?)"));
570 break;
571
572 case VERR_HGCM_SERVICE_NOT_FOUND:
573 strError += Utf8StrFmt(tr("The guest execution service is not available"));
574 break;
575
576 case VERR_PATH_NOT_FOUND:
577 strError += Utf8StrFmt(tr("Could not resolve path to specified file was not found on guest"));
578 break;
579
580 case VERR_BAD_EXE_FORMAT:
581 strError += Utf8StrFmt(tr("The specified file is not an executable format on guest"));
582 break;
583
584 case VERR_AUTHENTICATION_FAILURE:
585 strError += Utf8StrFmt(tr("The specified user was not able to logon on guest"));
586 break;
587
588 case VERR_INVALID_NAME:
589 strError += Utf8StrFmt(tr("The specified file is an invalid name"));
590 break;
591
592 case VERR_TIMEOUT:
593 strError += Utf8StrFmt(tr("The guest did not respond within time"));
594 break;
595
596 case VERR_CANCELLED:
597 strError += Utf8StrFmt(tr("The execution operation was canceled"));
598 break;
599
600 case VERR_PERMISSION_DENIED:
601 strError += Utf8StrFmt(tr("Invalid user/password credentials"));
602 break;
603
604 case VERR_MAX_PROCS_REACHED:
605 strError += Utf8StrFmt(tr("Maximum number of concurrent guest processes has been reached"));
606 break;
607
608 case VERR_NOT_EQUAL: /** @todo Imprecise to the user; can mean anything and all. */
609 strError += Utf8StrFmt(tr("Unable to retrieve requested information"));
610 break;
611
612 case VERR_NOT_FOUND:
613 strError += Utf8StrFmt(tr("The guest execution service is not ready (yet)"));
614 break;
615
616 default:
617 strError += Utf8StrFmt("%Rrc", guestRc);
618 break;
619 }
620
621 return strError;
622}
623
624inline bool GuestProcess::isAlive(void)
625{
626 return ( mData.mStatus == ProcessStatus_Started
627 || mData.mStatus == ProcessStatus_Paused
628 || mData.mStatus == ProcessStatus_Terminating);
629}
630
631inline bool GuestProcess::hasEnded(void)
632{
633 return ( mData.mStatus == ProcessStatus_TerminatedNormally
634 || mData.mStatus == ProcessStatus_TerminatedSignal
635 || mData.mStatus == ProcessStatus_TerminatedAbnormally
636 || mData.mStatus == ProcessStatus_TimedOutKilled
637 || mData.mStatus == ProcessStatus_TimedOutAbnormally
638 || mData.mStatus == ProcessStatus_Down
639 || mData.mStatus == ProcessStatus_Error);
640}
641
642int GuestProcess::onGuestDisconnected(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
643{
644 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
645 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
646
647 int vrc = setProcessStatus(ProcessStatus_Down, VINF_SUCCESS);
648
649 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
650 return vrc;
651}
652
653int GuestProcess::onProcessInputStatus(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
654{
655 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
656 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
657 /* pCallback is optional. */
658
659 if (pSvcCbData->mParms < 5)
660 return VERR_INVALID_PARAMETER;
661
662 CALLBACKDATA_PROC_INPUT dataCb;
663 /* pSvcCb->mpaParms[0] always contains the context ID. */
664 int vrc = pSvcCbData->mpaParms[1].getUInt32(&dataCb.uPID);
665 AssertRCReturn(vrc, vrc);
666 vrc = pSvcCbData->mpaParms[2].getUInt32(&dataCb.uStatus);
667 AssertRCReturn(vrc, vrc);
668 vrc = pSvcCbData->mpaParms[3].getUInt32(&dataCb.uFlags);
669 AssertRCReturn(vrc, vrc);
670 vrc = pSvcCbData->mpaParms[4].getUInt32(&dataCb.uProcessed);
671 AssertRCReturn(vrc, vrc);
672
673 LogFlowThisFunc(("uPID=%RU32, uStatus=%RU32, uFlags=%RI32, cbProcessed=%RU32\n",
674 dataCb.uPID, dataCb.uStatus, dataCb.uFlags, dataCb.uProcessed));
675
676 vrc = checkPID(dataCb.uPID);
677 if (RT_SUCCESS(vrc))
678 {
679 ProcessInputStatus_T inputStatus = ProcessInputStatus_Undefined;
680 switch (dataCb.uStatus)
681 {
682 case INPUT_STS_WRITTEN:
683 inputStatus = ProcessInputStatus_Written;
684 break;
685 case INPUT_STS_ERROR:
686 inputStatus = ProcessInputStatus_Broken;
687 break;
688 case INPUT_STS_TERMINATED:
689 inputStatus = ProcessInputStatus_Broken;
690 break;
691 case INPUT_STS_OVERFLOW:
692 inputStatus = ProcessInputStatus_Overflow;
693 break;
694 case INPUT_STS_UNDEFINED:
695 /* Fall through is intentional. */
696 default:
697 AssertMsg(!dataCb.uProcessed, ("Processed data is not 0 in undefined input state\n"));
698 break;
699 }
700
701 if (inputStatus != ProcessInputStatus_Undefined)
702 {
703 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
704
705 /* Copy over necessary data before releasing lock again. */
706 uint32_t uPID = mData.mPID;
707 /** @todo Also handle mSession? */
708
709 alock.release(); /* Release lock before firing off event. */
710
711 fireGuestProcessInputNotifyEvent(mEventSource, mSession, this,
712 uPID, 0 /* StdIn */, dataCb.uProcessed, inputStatus);
713 }
714 }
715
716 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
717 return vrc;
718}
719
720int GuestProcess::onProcessNotifyIO(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
721{
722 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
723 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
724
725 return VERR_NOT_IMPLEMENTED;
726}
727
728int GuestProcess::onProcessStatusChange(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
729{
730 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
731 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
732
733 if (pSvcCbData->mParms < 5)
734 return VERR_INVALID_PARAMETER;
735
736 CALLBACKDATA_PROC_STATUS dataCb;
737 /* pSvcCb->mpaParms[0] always contains the context ID. */
738 int vrc = pSvcCbData->mpaParms[1].getUInt32(&dataCb.uPID);
739 AssertRCReturn(vrc, vrc);
740 vrc = pSvcCbData->mpaParms[2].getUInt32(&dataCb.uStatus);
741 AssertRCReturn(vrc, vrc);
742 vrc = pSvcCbData->mpaParms[3].getUInt32(&dataCb.uFlags);
743 AssertRCReturn(vrc, vrc);
744 vrc = pSvcCbData->mpaParms[4].getPointer(&dataCb.pvData, &dataCb.cbData);
745 AssertRCReturn(vrc, vrc);
746
747 LogFlowThisFunc(("uPID=%RU32, uStatus=%RU32, uFlags=%RU32\n",
748 dataCb.uPID, dataCb.uStatus, dataCb.uFlags));
749
750 vrc = checkPID(dataCb.uPID);
751 if (RT_SUCCESS(vrc))
752 {
753 ProcessStatus_T procStatus = ProcessStatus_Undefined;
754 int procRc = VINF_SUCCESS;
755
756 switch (dataCb.uStatus)
757 {
758 case PROC_STS_STARTED:
759 {
760 procStatus = ProcessStatus_Started;
761
762 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
763 mData.mPID = dataCb.uPID; /* Set the process PID. */
764 break;
765 }
766
767 case PROC_STS_TEN:
768 {
769 procStatus = ProcessStatus_TerminatedNormally;
770
771 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
772 mData.mExitCode = dataCb.uFlags; /* Contains the exit code. */
773 break;
774 }
775
776 case PROC_STS_TES:
777 {
778 procStatus = ProcessStatus_TerminatedSignal;
779
780 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
781 mData.mExitCode = dataCb.uFlags; /* Contains the signal. */
782 break;
783 }
784
785 case PROC_STS_TEA:
786 {
787 procStatus = ProcessStatus_TerminatedAbnormally;
788 break;
789 }
790
791 case PROC_STS_TOK:
792 {
793 procStatus = ProcessStatus_TimedOutKilled;
794 break;
795 }
796
797 case PROC_STS_TOA:
798 {
799 procStatus = ProcessStatus_TimedOutAbnormally;
800 break;
801 }
802
803 case PROC_STS_DWN:
804 {
805 procStatus = ProcessStatus_Down;
806 break;
807 }
808
809 case PROC_STS_ERROR:
810 {
811 procRc = dataCb.uFlags; /* mFlags contains the IPRT error sent from the guest. */
812 procStatus = ProcessStatus_Error;
813 break;
814 }
815
816 case PROC_STS_UNDEFINED:
817 default:
818 {
819 /* Silently skip this request. */
820 procStatus = ProcessStatus_Undefined;
821 break;
822 }
823 }
824
825 LogFlowThisFunc(("Got rc=%Rrc, procSts=%ld, procRc=%Rrc\n",
826 vrc, procStatus, procRc));
827
828 /* Set the process status. */
829 int rc2 = setProcessStatus(procStatus, procRc);
830 if (RT_SUCCESS(vrc))
831 vrc = rc2;
832 }
833
834 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
835 return vrc;
836}
837
838int GuestProcess::onProcessOutput(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
839{
840 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
841
842 if (pSvcCbData->mParms < 5)
843 return VERR_INVALID_PARAMETER;
844
845 CALLBACKDATA_PROC_OUTPUT dataCb;
846 /* pSvcCb->mpaParms[0] always contains the context ID. */
847 int vrc = pSvcCbData->mpaParms[1].getUInt32(&dataCb.uPID);
848 AssertRCReturn(vrc, vrc);
849 vrc = pSvcCbData->mpaParms[2].getUInt32(&dataCb.uHandle);
850 AssertRCReturn(vrc, vrc);
851 vrc = pSvcCbData->mpaParms[3].getUInt32(&dataCb.uFlags);
852 AssertRCReturn(vrc, vrc);
853 vrc = pSvcCbData->mpaParms[4].getPointer(&dataCb.pvData, &dataCb.cbData);
854 AssertRCReturn(vrc, vrc);
855
856 LogFlowThisFunc(("uPID=%RU32, uHandle=%RU32, uFlags=%RI32, pvData=%p, cbData=%RU32\n",
857 dataCb.uPID, dataCb.uHandle, dataCb.uFlags, dataCb.pvData, dataCb.cbData));
858
859 vrc = checkPID(dataCb.uPID);
860 if (RT_SUCCESS(vrc))
861 {
862 com::SafeArray<BYTE> data((size_t)dataCb.cbData);
863 if (dataCb.cbData)
864 data.initFrom((BYTE*)dataCb.pvData, dataCb.cbData);
865
866 fireGuestProcessOutputEvent(mEventSource, mSession, this,
867 mData.mPID, dataCb.uHandle, dataCb.cbData, ComSafeArrayAsInParam(data));
868 }
869
870 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
871 return vrc;
872}
873
874int GuestProcess::readData(uint32_t uHandle, uint32_t uSize, uint32_t uTimeoutMS,
875 void *pvData, size_t cbData, uint32_t *pcbRead, int *pGuestRc)
876{
877 LogFlowThisFunc(("uPID=%RU32, uHandle=%RU32, uSize=%RU32, uTimeoutMS=%RU32, pvData=%p, cbData=%RU32, pGuestRc=%p\n",
878 mData.mPID, uHandle, uSize, uTimeoutMS, pvData, cbData, pGuestRc));
879 AssertReturn(uSize, VERR_INVALID_PARAMETER);
880 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
881 AssertReturn(cbData >= uSize, VERR_INVALID_PARAMETER);
882 /* pcbRead is optional. */
883
884 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
885
886 if ( mData.mStatus != ProcessStatus_Started
887 /* Skip reading if the process wasn't started with the appropriate
888 * flags. */
889 || ( ( uHandle == OUTPUT_HANDLE_ID_STDOUT
890 || uHandle == OUTPUT_HANDLE_ID_STDOUT_DEPRECATED)
891 && !(mData.mProcess.mFlags & ProcessCreateFlag_WaitForStdOut))
892 || ( uHandle == OUTPUT_HANDLE_ID_STDERR
893 && !(mData.mProcess.mFlags & ProcessCreateFlag_WaitForStdErr))
894 )
895 {
896 if (pcbRead)
897 *pcbRead = 0;
898 if (pGuestRc)
899 *pGuestRc = VINF_SUCCESS;
900 return VINF_SUCCESS; /* Nothing to read anymore. */
901 }
902
903 int vrc;
904
905 GuestWaitEvent *pEvent = NULL;
906 std::list < VBoxEventType_T > eventTypes;
907 try
908 {
909 /*
910 * On Guest Additions < 4.3 there is no guarantee that the process status
911 * change arrives *after* the output event, e.g. if this was the last output
912 * block being read and the process will report status "terminate".
913 * So just skip checking for process status change and only wait for the
914 * output event.
915 */
916 if (mSession->getProtocolVersion() >= 2)
917 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
918 eventTypes.push_back(VBoxEventType_OnGuestProcessOutput);
919
920 vrc = registerWaitEvent(eventTypes, &pEvent);
921 }
922 catch (std::bad_alloc)
923 {
924 vrc = VERR_NO_MEMORY;
925 }
926
927 if (RT_FAILURE(vrc))
928 return vrc;
929
930 if (RT_SUCCESS(vrc))
931 {
932 VBOXHGCMSVCPARM paParms[8];
933 int i = 0;
934 paParms[i++].setUInt32(pEvent->ContextID());
935 paParms[i++].setUInt32(mData.mPID);
936 paParms[i++].setUInt32(uHandle);
937 paParms[i++].setUInt32(0 /* Flags, none set yet. */);
938
939 alock.release(); /* Drop the write lock before sending. */
940
941 vrc = sendCommand(HOST_EXEC_GET_OUTPUT, i, paParms);
942 }
943
944 if (RT_SUCCESS(vrc))
945 vrc = waitForOutput(pEvent, uHandle, uTimeoutMS,
946 pvData, cbData, pcbRead);
947
948 unregisterWaitEvent(pEvent);
949
950 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
951 return vrc;
952}
953
954/* Does not do locking; caller is responsible for that! */
955int GuestProcess::setProcessStatus(ProcessStatus_T procStatus, int procRc)
956{
957 LogFlowThisFuncEnter();
958
959 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
960
961 LogFlowThisFunc(("oldStatus=%ld, newStatus=%ld, procRc=%Rrc\n",
962 mData.mStatus, procStatus, procRc));
963
964 if (procStatus == ProcessStatus_Error)
965 {
966 AssertMsg(RT_FAILURE(procRc), ("Guest rc must be an error (%Rrc)\n", procRc));
967 /* Do not allow overwriting an already set error. If this happens
968 * this means we forgot some error checking/locking somewhere. */
969 AssertMsg(RT_SUCCESS(mData.mRC), ("Guest rc already set (to %Rrc)\n", mData.mRC));
970 }
971 else
972 AssertMsg(RT_SUCCESS(procRc), ("Guest rc must not be an error (%Rrc)\n", procRc));
973
974 int rc = VINF_SUCCESS;
975
976 if (mData.mStatus != procStatus) /* Was there a process status change? */
977 {
978 mData.mStatus = procStatus;
979 mData.mRC = procRc;
980
981 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
982 HRESULT hr = errorInfo.createObject();
983 ComAssertComRC(hr);
984 if (RT_FAILURE(mData.mRC))
985 {
986 int rc2 = errorInfo->initEx(VBOX_E_IPRT_ERROR, mData.mRC,
987 COM_IIDOF(IGuestProcess), getComponentName(),
988 guestErrorToString(mData.mRC));
989 AssertRC(rc2);
990 }
991
992 /* Copy over necessary data before releasing lock again. */
993 uint32_t uPID = mData.mPID;
994 ProcessStatus_T uStatus = mData.mStatus;
995 /** @todo Also handle mSession? */
996
997 alock.release(); /* Release lock before firing off event. */
998
999 fireGuestProcessStateChangedEvent(mEventSource, mSession, this,
1000 uPID, uStatus, errorInfo);
1001#if 0
1002 /*
1003 * On Guest Additions < 4.3 there is no guarantee that outstanding
1004 * requests will be delivered to the host after the process has ended,
1005 * so just cancel all waiting events here to not let clients run
1006 * into timeouts.
1007 */
1008 if ( mSession->getProtocolVersion() < 2
1009 && hasEnded())
1010 {
1011 LogFlowThisFunc(("Process ended, canceling outstanding wait events ...\n"));
1012 rc = cancelWaitEvents();
1013 }
1014#endif
1015 }
1016
1017 return rc;
1018}
1019
1020/* static */
1021HRESULT GuestProcess::setErrorExternal(VirtualBoxBase *pInterface, int guestRc)
1022{
1023 AssertPtr(pInterface);
1024 AssertMsg(RT_FAILURE(guestRc), ("Guest rc does not indicate a failure when setting error\n"));
1025
1026 return pInterface->setError(VBOX_E_IPRT_ERROR, GuestProcess::guestErrorToString(guestRc).c_str());
1027}
1028
1029int GuestProcess::startProcess(uint32_t uTimeoutMS, int *pGuestRc)
1030{
1031 LogFlowThisFunc(("uTimeoutMS=%RU32, procCmd=%s, procTimeoutMS=%RU32, procFlags=%x, sessionID=%RU32\n",
1032 uTimeoutMS, mData.mProcess.mCommand.c_str(), mData.mProcess.mTimeoutMS, mData.mProcess.mFlags,
1033 mSession->getId()));
1034
1035 /* Wait until the caller function (if kicked off by a thread)
1036 * has returned and continue operation. */
1037 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1038
1039 mData.mStatus = ProcessStatus_Starting;
1040
1041 int vrc;
1042
1043 GuestWaitEvent *pEvent = NULL;
1044 std::list < VBoxEventType_T > eventTypes;
1045 try
1046 {
1047 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1048
1049 vrc = registerWaitEvent(eventTypes, &pEvent);
1050 }
1051 catch (std::bad_alloc)
1052 {
1053 vrc = VERR_NO_MEMORY;
1054 }
1055
1056 if (RT_FAILURE(vrc))
1057 return vrc;
1058
1059 GuestSession *pSession = mSession;
1060 AssertPtr(pSession);
1061
1062 const GuestCredentials &sessionCreds = pSession->getCredentials();
1063
1064 /* Prepare arguments. */
1065 char *pszArgs = NULL;
1066 size_t cArgs = mData.mProcess.mArguments.size();
1067 if (cArgs >= UINT32_MAX)
1068 vrc = VERR_BUFFER_OVERFLOW;
1069
1070 if ( RT_SUCCESS(vrc)
1071 && cArgs)
1072 {
1073 char **papszArgv = (char**)RTMemAlloc((cArgs + 1) * sizeof(char*));
1074 AssertReturn(papszArgv, VERR_NO_MEMORY);
1075
1076 for (size_t i = 0; i < cArgs && RT_SUCCESS(vrc); i++)
1077 {
1078 const char *pszCurArg = mData.mProcess.mArguments[i].c_str();
1079 AssertPtr(pszCurArg);
1080 vrc = RTStrDupEx(&papszArgv[i], pszCurArg);
1081 }
1082 papszArgv[cArgs] = NULL;
1083
1084 if (RT_SUCCESS(vrc))
1085 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, RTGETOPTARGV_CNV_QUOTE_MS_CRT);
1086
1087 if (papszArgv)
1088 {
1089 size_t i = 0;
1090 while (papszArgv[i])
1091 RTStrFree(papszArgv[i++]);
1092 RTMemFree(papszArgv);
1093 }
1094 }
1095
1096 /* Calculate arguments size (in bytes). */
1097 size_t cbArgs = 0;
1098 if (RT_SUCCESS(vrc))
1099 cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
1100
1101 /* Prepare environment. */
1102 void *pvEnv = NULL;
1103 size_t cbEnv = 0;
1104 if (RT_SUCCESS(vrc))
1105 vrc = mData.mProcess.mEnvironment.BuildEnvironmentBlock(&pvEnv, &cbEnv, NULL /* cEnv */);
1106
1107 if (RT_SUCCESS(vrc))
1108 {
1109 AssertPtr(mSession);
1110 uint32_t uProtocol = mSession->getProtocolVersion();
1111
1112 /* Prepare HGCM call. */
1113 VBOXHGCMSVCPARM paParms[16];
1114 int i = 0;
1115 paParms[i++].setUInt32(pEvent->ContextID());
1116 paParms[i++].setPointer((void*)mData.mProcess.mCommand.c_str(),
1117 (ULONG)mData.mProcess.mCommand.length() + 1);
1118 paParms[i++].setUInt32(mData.mProcess.mFlags);
1119 paParms[i++].setUInt32((uint32_t)mData.mProcess.mArguments.size());
1120 paParms[i++].setPointer((void*)pszArgs, (uint32_t)cbArgs);
1121 paParms[i++].setUInt32((uint32_t)mData.mProcess.mEnvironment.Size());
1122 paParms[i++].setUInt32((uint32_t)cbEnv);
1123 paParms[i++].setPointer((void*)pvEnv, (uint32_t)cbEnv);
1124 if (uProtocol < 2)
1125 {
1126 /* In protocol v1 (VBox < 4.3) the credentials were part of the execution
1127 * call. In newer protocols these credentials are part of the opened guest
1128 * session, so not needed anymore here. */
1129 paParms[i++].setPointer((void*)sessionCreds.mUser.c_str(), (ULONG)sessionCreds.mUser.length() + 1);
1130 paParms[i++].setPointer((void*)sessionCreds.mPassword.c_str(), (ULONG)sessionCreds.mPassword.length() + 1);
1131 }
1132 /*
1133 * If the WaitForProcessStartOnly flag is set, we only want to define and wait for a timeout
1134 * until the process was started - the process itself then gets an infinite timeout for execution.
1135 * This is handy when we want to start a process inside a worker thread within a certain timeout
1136 * but let the started process perform lengthly operations then.
1137 */
1138 if (mData.mProcess.mFlags & ProcessCreateFlag_WaitForProcessStartOnly)
1139 paParms[i++].setUInt32(UINT32_MAX /* Infinite timeout */);
1140 else
1141 paParms[i++].setUInt32(mData.mProcess.mTimeoutMS);
1142 if (uProtocol >= 2)
1143 {
1144 paParms[i++].setUInt32(mData.mProcess.mPriority);
1145 /* CPU affinity: We only support one CPU affinity block at the moment,
1146 * so that makes up to 64 CPUs total. This can be more in the future. */
1147 paParms[i++].setUInt32(1);
1148 /* The actual CPU affinity blocks. */
1149 paParms[i++].setPointer((void*)&mData.mProcess.mAffinity, sizeof(mData.mProcess.mAffinity));
1150 }
1151
1152 alock.release(); /* Drop the write lock before sending. */
1153
1154 vrc = sendCommand(HOST_EXEC_CMD, i, paParms);
1155 if (RT_FAILURE(vrc))
1156 {
1157 int rc2 = setProcessStatus(ProcessStatus_Error, vrc);
1158 AssertRC(rc2);
1159 }
1160 }
1161
1162 GuestEnvironment::FreeEnvironmentBlock(pvEnv);
1163 if (pszArgs)
1164 RTStrFree(pszArgs);
1165
1166 if (RT_SUCCESS(vrc))
1167 vrc = waitForStatusChange(pEvent, uTimeoutMS,
1168 NULL /* Process status */, pGuestRc);
1169 unregisterWaitEvent(pEvent);
1170
1171 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1172 return vrc;
1173}
1174
1175int GuestProcess::startProcessAsync(void)
1176{
1177 LogFlowThisFuncEnter();
1178
1179 int vrc;
1180
1181 try
1182 {
1183 /* Asynchronously start the process on the guest by kicking off a
1184 * worker thread. */
1185 std::auto_ptr<GuestProcessStartTask> pTask(new GuestProcessStartTask(this));
1186 AssertReturn(pTask->isOk(), pTask->rc());
1187
1188 vrc = RTThreadCreate(NULL, GuestProcess::startProcessThread,
1189 (void *)pTask.get(), 0,
1190 RTTHREADTYPE_MAIN_WORKER, 0,
1191 "gctlPrcStart");
1192 if (RT_SUCCESS(vrc))
1193 {
1194 /* pTask is now owned by startProcessThread(), so release it. */
1195 pTask.release();
1196 }
1197 }
1198 catch(std::bad_alloc &)
1199 {
1200 vrc = VERR_NO_MEMORY;
1201 }
1202
1203 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1204 return vrc;
1205}
1206
1207/* static */
1208DECLCALLBACK(int) GuestProcess::startProcessThread(RTTHREAD Thread, void *pvUser)
1209{
1210 LogFlowFunc(("pvUser=%p\n", pvUser));
1211
1212 std::auto_ptr<GuestProcessStartTask> pTask(static_cast<GuestProcessStartTask*>(pvUser));
1213 AssertPtr(pTask.get());
1214
1215 const ComObjPtr<GuestProcess> pProcess(pTask->Process());
1216 Assert(!pProcess.isNull());
1217
1218 AutoCaller autoCaller(pProcess);
1219 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1220
1221 int vrc = pProcess->startProcess(30 * 1000 /* 30s timeout */,
1222 NULL /* Guest rc, ignored */);
1223 /* Nothing to do here anymore. */
1224
1225 LogFlowFunc(("pProcess=%p returning rc=%Rrc\n", (GuestProcess *)pProcess, vrc));
1226 return vrc;
1227}
1228
1229int GuestProcess::terminateProcess(uint32_t uTimeoutMS, int *pGuestRc)
1230{
1231 /* pGuestRc is optional. */
1232 LogFlowThisFunc(("uTimeoutMS=%RU32\n", uTimeoutMS));
1233
1234 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1235
1236 if (mData.mStatus != ProcessStatus_Started)
1237 {
1238 LogFlowThisFunc(("Process not started (yet), nothing to terminate\n"));
1239 return VINF_SUCCESS; /* Nothing to do (anymore). */
1240 }
1241
1242 int vrc = VINF_SUCCESS;
1243
1244 AssertPtr(mSession);
1245 /* Note: VBox < 4.3 (aka protocol version 1) does not
1246 * support this, so just skip. */
1247 if (mSession->getProtocolVersion() < 2)
1248 vrc = VERR_NOT_SUPPORTED;
1249
1250 if (RT_SUCCESS(vrc))
1251 {
1252 GuestWaitEvent *pEvent = NULL;
1253 std::list < VBoxEventType_T > eventTypes;
1254 try
1255 {
1256 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1257
1258 vrc = registerWaitEvent(eventTypes, &pEvent);
1259 }
1260 catch (std::bad_alloc)
1261 {
1262 vrc = VERR_NO_MEMORY;
1263 }
1264
1265 if (RT_FAILURE(vrc))
1266 return vrc;
1267
1268 VBOXHGCMSVCPARM paParms[4];
1269 int i = 0;
1270 paParms[i++].setUInt32(pEvent->ContextID());
1271 paParms[i++].setUInt32(mData.mPID);
1272
1273 alock.release(); /* Drop the write lock before sending. */
1274
1275 vrc = sendCommand(HOST_EXEC_TERMINATE, i, paParms);
1276 if (RT_SUCCESS(vrc))
1277 vrc = waitForStatusChange(pEvent, uTimeoutMS,
1278 NULL /* ProcessStatus */, pGuestRc);
1279 unregisterWaitEvent(pEvent);
1280 }
1281
1282 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1283 return vrc;
1284}
1285
1286/* static */
1287ProcessWaitResult_T GuestProcess::waitFlagsToResultEx(uint32_t fWaitFlags,
1288 ProcessStatus_T procStatus, uint32_t uProcFlags,
1289 uint32_t uProtocol)
1290{
1291 ProcessWaitResult_T waitResult = ProcessWaitResult_None;
1292
1293 if ( (fWaitFlags & ProcessWaitForFlag_Terminate)
1294 || (fWaitFlags & ProcessWaitForFlag_StdIn)
1295 || (fWaitFlags & ProcessWaitForFlag_StdOut)
1296 || (fWaitFlags & ProcessWaitForFlag_StdErr))
1297 {
1298 switch (procStatus)
1299 {
1300 case ProcessStatus_TerminatedNormally:
1301 case ProcessStatus_TerminatedSignal:
1302 case ProcessStatus_TerminatedAbnormally:
1303 case ProcessStatus_Down:
1304 waitResult = ProcessWaitResult_Terminate;
1305 break;
1306
1307 case ProcessStatus_TimedOutKilled:
1308 case ProcessStatus_TimedOutAbnormally:
1309 waitResult = ProcessWaitResult_Timeout;
1310 break;
1311
1312 case ProcessStatus_Error:
1313 /* Handled above. */
1314 break;
1315
1316 case ProcessStatus_Started:
1317 {
1318 /*
1319 * If ProcessCreateFlag_WaitForProcessStartOnly was specified on process creation the
1320 * caller is not interested in getting further process statuses -- so just don't notify
1321 * anything here anymore and return.
1322 */
1323 if (uProcFlags & ProcessCreateFlag_WaitForProcessStartOnly)
1324 waitResult = ProcessWaitResult_Start;
1325 break;
1326 }
1327
1328 case ProcessStatus_Undefined:
1329 case ProcessStatus_Starting:
1330 /* No result available yet. */
1331 break;
1332
1333 default:
1334 AssertMsgFailed(("Unhandled process status %ld\n", procStatus));
1335 break;
1336 }
1337 }
1338 else if (fWaitFlags & ProcessWaitForFlag_Start)
1339 {
1340 switch (procStatus)
1341 {
1342 case ProcessStatus_Started:
1343 case ProcessStatus_Paused:
1344 case ProcessStatus_Terminating:
1345 case ProcessStatus_TerminatedNormally:
1346 case ProcessStatus_TerminatedSignal:
1347 case ProcessStatus_TerminatedAbnormally:
1348 case ProcessStatus_Down:
1349 waitResult = ProcessWaitResult_Start;
1350 break;
1351
1352 case ProcessStatus_Error:
1353 waitResult = ProcessWaitResult_Error;
1354 break;
1355
1356 case ProcessStatus_TimedOutKilled:
1357 case ProcessStatus_TimedOutAbnormally:
1358 waitResult = ProcessWaitResult_Timeout;
1359 break;
1360
1361 case ProcessStatus_Undefined:
1362 case ProcessStatus_Starting:
1363 /* No result available yet. */
1364 break;
1365
1366 default:
1367 AssertMsgFailed(("Unhandled process status %ld\n", procStatus));
1368 break;
1369 }
1370 }
1371
1372 /* Filter out waits which are *not* supported using
1373 * older guest control Guest Additions.
1374 *
1375 ** @todo ProcessWaitForFlag_Std* flags are not implemented yet.
1376 */
1377 if (uProtocol < 99) /* See @todo above. */
1378 {
1379 if ( waitResult == ProcessWaitResult_None
1380 /* We don't support waiting for stdin, out + err,
1381 * just skip waiting then. */
1382 && ( (fWaitFlags & ProcessWaitForFlag_StdIn)
1383 || (fWaitFlags & ProcessWaitForFlag_StdOut)
1384 || (fWaitFlags & ProcessWaitForFlag_StdErr)
1385 )
1386 )
1387 {
1388 /* Use _WaitFlagNotSupported because we don't know what to tell the caller. */
1389 waitResult = ProcessWaitResult_WaitFlagNotSupported;
1390 }
1391 }
1392
1393 return waitResult;
1394}
1395
1396ProcessWaitResult_T GuestProcess::waitFlagsToResult(uint32_t fWaitFlags)
1397{
1398 AssertPtr(mSession);
1399 return GuestProcess::waitFlagsToResultEx(fWaitFlags, mData.mStatus, mData.mProcess.mFlags,
1400 mSession->getProtocolVersion());
1401}
1402
1403int GuestProcess::waitFor(uint32_t fWaitFlags, ULONG uTimeoutMS, ProcessWaitResult_T &waitResult, int *pGuestRc)
1404{
1405 AssertReturn(fWaitFlags, VERR_INVALID_PARAMETER);
1406
1407 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1408
1409 LogFlowThisFunc(("fWaitFlags=0x%x, uTimeoutMS=%RU32, procStatus=%RU32, procRc=%Rrc, pGuestRc=%p\n",
1410 fWaitFlags, uTimeoutMS, mData.mStatus, mData.mRC, pGuestRc));
1411
1412 /* Did some error occur before? Then skip waiting and return. */
1413 if (mData.mStatus == ProcessStatus_Error)
1414 {
1415 waitResult = ProcessWaitResult_Error;
1416 AssertMsg(RT_FAILURE(mData.mRC), ("No error rc (%Rrc) set when guest process indicated an error\n", mData.mRC));
1417 if (pGuestRc)
1418 *pGuestRc = mData.mRC; /* Return last set error. */
1419 return VERR_GSTCTL_GUEST_ERROR;
1420 }
1421
1422 waitResult = waitFlagsToResult(fWaitFlags);
1423 LogFlowThisFunc(("waitFlagToResult=%ld\n", waitResult));
1424
1425 /* No waiting needed? Return immediately using the last set error. */
1426 if (waitResult != ProcessWaitResult_None)
1427 {
1428 if (pGuestRc)
1429 *pGuestRc = mData.mRC; /* Return last set error (if any). */
1430 return RT_SUCCESS(mData.mRC) ? VINF_SUCCESS : VERR_GSTCTL_GUEST_ERROR;
1431 }
1432
1433 alock.release(); /* Release lock before waiting. */
1434
1435 int vrc;
1436
1437 GuestWaitEvent *pEvent = NULL;
1438 std::list < VBoxEventType_T > eventTypes;
1439 try
1440 {
1441 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1442
1443 vrc = registerWaitEvent(eventTypes, &pEvent);
1444 }
1445 catch (std::bad_alloc)
1446 {
1447 vrc = VERR_NO_MEMORY;
1448 }
1449
1450 if (RT_FAILURE(vrc))
1451 return vrc;
1452
1453 /*
1454 * Do the actual waiting.
1455 */
1456 ProcessStatus_T processStatus = ProcessStatus_Undefined;
1457 uint64_t u64StartMS = RTTimeMilliTS();
1458 for (;;)
1459 {
1460 uint64_t u32ElapsedMS = RTTimeMilliTS() - u64StartMS;
1461 if ( uTimeoutMS != RT_INDEFINITE_WAIT
1462 && u32ElapsedMS >= uTimeoutMS)
1463 {
1464 vrc = VERR_TIMEOUT;
1465 break;
1466 }
1467
1468 vrc = waitForStatusChange(pEvent,
1469 uTimeoutMS == RT_INDEFINITE_WAIT
1470 ? RT_INDEFINITE_WAIT : uTimeoutMS - u32ElapsedMS,
1471 &processStatus, pGuestRc);
1472 if (RT_SUCCESS(vrc))
1473 {
1474 alock.acquire();
1475
1476 waitResult = waitFlagsToResultEx(fWaitFlags, processStatus,
1477 mData.mProcess.mFlags, mSession->getProtocolVersion());
1478 LogFlowThisFunc(("Got new status change: waitResult=%ld, processStatus=%ld\n",
1479 waitResult, processStatus));
1480 if (ProcessWaitResult_None != waitResult) /* We got a waiting result. */
1481 break;
1482 }
1483 else /* Waiting failed, bail out. */
1484 break;
1485
1486 alock.release(); /* Don't hold lock in next waiting round. */
1487 }
1488
1489 unregisterWaitEvent(pEvent);
1490
1491 LogFlowThisFunc(("Returned waitResult=%ld, processStatus=%ld, rc=%Rrc\n",
1492 waitResult, processStatus, vrc));
1493 return vrc;
1494}
1495
1496int GuestProcess::waitForInputNotify(GuestWaitEvent *pEvent, uint32_t uHandle, uint32_t uTimeoutMS,
1497 ProcessInputStatus_T *pInputStatus, uint32_t *pcbProcessed)
1498{
1499 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1500
1501 VBoxEventType_T evtType;
1502 ComPtr<IEvent> pIEvent;
1503 int vrc = waitForEvent(pEvent, uTimeoutMS,
1504 &evtType, pIEvent.asOutParam());
1505 if (RT_SUCCESS(vrc))
1506 {
1507 if (evtType == VBoxEventType_OnGuestProcessInputNotify)
1508 {
1509 ComPtr<IGuestProcessInputNotifyEvent> pProcessEvent = pIEvent;
1510 Assert(!pProcessEvent.isNull());
1511
1512 if (pInputStatus)
1513 {
1514 HRESULT hr2 = pProcessEvent->COMGETTER(Status)(pInputStatus);
1515 ComAssertComRC(hr2);
1516 }
1517 if (pcbProcessed)
1518 {
1519 HRESULT hr2 = pProcessEvent->COMGETTER(Processed)((ULONG*)pcbProcessed);
1520 ComAssertComRC(hr2);
1521 }
1522 }
1523 else
1524 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1525 }
1526
1527 LogFlowThisFunc(("Returning pEvent=%p, uHandle=%RU32, rc=%Rrc\n",
1528 pEvent, uHandle, vrc));
1529 return vrc;
1530}
1531
1532int GuestProcess::waitForOutput(GuestWaitEvent *pEvent, uint32_t uHandle, uint32_t uTimeoutMS,
1533 void *pvData, size_t cbData, uint32_t *pcbRead)
1534{
1535 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1536 /* pvData is optional. */
1537 /* cbData is optional. */
1538 /* pcbRead is optional. */
1539
1540 LogFlowThisFunc(("cEventTypes=%zu, pEvent=%p, uHandle=%RU32, uTimeoutMS=%RU32, pvData=%p, cbData=%zu, pcbRead=%p\n",
1541 pEvent->TypeCount(), pEvent, uHandle, uTimeoutMS, pvData, cbData, pcbRead));
1542
1543 int vrc;
1544
1545 VBoxEventType_T evtType;
1546 ComPtr<IEvent> pIEvent;
1547 do
1548 {
1549 vrc = waitForEvent(pEvent, uTimeoutMS,
1550 &evtType, pIEvent.asOutParam());
1551 if (RT_SUCCESS(vrc))
1552 {
1553#ifdef DEBUG_andy
1554 LogFlowThisFunc(("pEvent=%p, evtType=%ld\n", pEvent, evtType));
1555#endif
1556 if (evtType == VBoxEventType_OnGuestProcessOutput)
1557 {
1558 ComPtr<IGuestProcessOutputEvent> pProcessEvent = pIEvent;
1559 Assert(!pProcessEvent.isNull());
1560
1561 ULONG uHandleEvent;
1562 HRESULT hr = pProcessEvent->COMGETTER(Handle)(&uHandleEvent);
1563 LogFlowThisFunc(("Received output, uHandle=%RU32\n", uHandleEvent));
1564 if ( SUCCEEDED(hr)
1565 && uHandleEvent == uHandle)
1566 {
1567 if (pvData)
1568 {
1569 com::SafeArray <BYTE> data;
1570 hr = pProcessEvent->COMGETTER(Data)(ComSafeArrayAsOutParam(data));
1571 ComAssertComRC(hr);
1572 size_t cbRead = data.size();
1573 if (cbRead)
1574 {
1575 if (cbRead <= cbData)
1576 {
1577 /* Copy data from event into our buffer. */
1578 memcpy(pvData, data.raw(), data.size());
1579 }
1580 else
1581 vrc = VERR_BUFFER_OVERFLOW;
1582 }
1583 }
1584
1585 if ( RT_SUCCESS(vrc)
1586 && pcbRead)
1587 {
1588 ULONG cbRead;
1589 hr = pProcessEvent->COMGETTER(Processed)(&cbRead);
1590 ComAssertComRC(hr);
1591 *pcbRead = (uint32_t)cbRead;
1592 }
1593
1594 break;
1595 }
1596 else if (FAILED(hr))
1597 vrc = VERR_COM_UNEXPECTED;
1598 }
1599 else
1600 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1601 }
1602
1603 } while (vrc == VINF_SUCCESS);
1604
1605 if ( vrc != VINF_SUCCESS
1606 && pcbRead)
1607 {
1608 *pcbRead = 0;
1609 }
1610
1611 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1612 return vrc;
1613}
1614
1615int GuestProcess::waitForStatusChange(GuestWaitEvent *pEvent, uint32_t uTimeoutMS,
1616 ProcessStatus_T *pProcessStatus, int *pGuestRc)
1617{
1618 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1619 /* pProcessStatus is optional. */
1620 /* pGuestRc is optional. */
1621
1622 VBoxEventType_T evtType;
1623 ComPtr<IEvent> pIEvent;
1624 int vrc = waitForEvent(pEvent, uTimeoutMS,
1625 &evtType, pIEvent.asOutParam());
1626 if (RT_SUCCESS(vrc))
1627 {
1628 Assert(evtType == VBoxEventType_OnGuestProcessStateChanged);
1629 ComPtr<IGuestProcessStateChangedEvent> pProcessEvent = pIEvent;
1630 Assert(!pProcessEvent.isNull());
1631
1632 HRESULT hr;
1633 if (pProcessStatus)
1634 {
1635 hr = pProcessEvent->COMGETTER(Status)(pProcessStatus);
1636 ComAssertComRC(hr);
1637 }
1638
1639 ComPtr<IVirtualBoxErrorInfo> errorInfo;
1640 hr = pProcessEvent->COMGETTER(Error)(errorInfo.asOutParam());
1641 ComAssertComRC(hr);
1642
1643 LONG lGuestRc;
1644 hr = errorInfo->COMGETTER(ResultDetail)(&lGuestRc);
1645 ComAssertComRC(hr);
1646
1647 LogFlowThisFunc(("resultDetail=%RI32 (rc=%Rrc)\n",
1648 lGuestRc, lGuestRc));
1649
1650 if (RT_FAILURE((int)lGuestRc))
1651 vrc = VERR_GSTCTL_GUEST_ERROR;
1652
1653 if (pGuestRc)
1654 *pGuestRc = (int)lGuestRc;
1655 }
1656
1657 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1658 return vrc;
1659}
1660
1661/* static */
1662bool GuestProcess::waitResultImpliesEx(ProcessWaitResult_T waitResult,
1663 ProcessStatus_T procStatus, uint32_t uProcFlags,
1664 uint32_t uProtocol)
1665{
1666 bool fImplies;
1667
1668 switch (waitResult)
1669 {
1670 case ProcessWaitResult_Start:
1671 fImplies = procStatus == ProcessStatus_Started;
1672 break;
1673
1674 case ProcessWaitResult_Terminate:
1675 fImplies = ( procStatus == ProcessStatus_TerminatedNormally
1676 || procStatus == ProcessStatus_TerminatedSignal
1677 || procStatus == ProcessStatus_TerminatedAbnormally
1678 || procStatus == ProcessStatus_TimedOutKilled
1679 || procStatus == ProcessStatus_TimedOutAbnormally
1680 || procStatus == ProcessStatus_Down
1681 || procStatus == ProcessStatus_Error);
1682 break;
1683
1684 default:
1685 fImplies = false;
1686 break;
1687 }
1688
1689 return fImplies;
1690}
1691
1692int GuestProcess::writeData(uint32_t uHandle, uint32_t uFlags,
1693 void *pvData, size_t cbData, uint32_t uTimeoutMS, uint32_t *puWritten, int *pGuestRc)
1694{
1695 LogFlowThisFunc(("uPID=%RU32, uHandle=%RU32, uFlags=%RU32, pvData=%p, cbData=%RU32, uTimeoutMS=%RU32, puWritten=%p, pGuestRc=%p\n",
1696 mData.mPID, uHandle, uFlags, pvData, cbData, uTimeoutMS, puWritten, pGuestRc));
1697 /* All is optional. There can be 0 byte writes. */
1698
1699 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1700
1701 if (mData.mStatus != ProcessStatus_Started)
1702 {
1703 if (puWritten)
1704 *puWritten = 0;
1705 if (pGuestRc)
1706 *pGuestRc = VINF_SUCCESS;
1707 return VINF_SUCCESS; /* Not available for writing (anymore). */
1708 }
1709
1710 int vrc;
1711
1712 GuestWaitEvent *pEvent = NULL;
1713 std::list < VBoxEventType_T > eventTypes;
1714 try
1715 {
1716 /*
1717 * On Guest Additions < 4.3 there is no guarantee that the process status
1718 * change arrives *after* the input event, e.g. if this was the last input
1719 * block being written and the process will report status "terminate".
1720 * So just skip checking for process status change and only wait for the
1721 * input event.
1722 */
1723 if (mSession->getProtocolVersion() >= 2)
1724 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1725 eventTypes.push_back(VBoxEventType_OnGuestProcessInputNotify);
1726
1727 vrc = registerWaitEvent(eventTypes, &pEvent);
1728 }
1729 catch (std::bad_alloc)
1730 {
1731 vrc = VERR_NO_MEMORY;
1732 }
1733
1734 if (RT_FAILURE(vrc))
1735 return vrc;
1736
1737 VBOXHGCMSVCPARM paParms[5];
1738 int i = 0;
1739 paParms[i++].setUInt32(pEvent->ContextID());
1740 paParms[i++].setUInt32(mData.mPID);
1741 paParms[i++].setUInt32(uFlags);
1742 paParms[i++].setPointer(pvData, (uint32_t)cbData);
1743 paParms[i++].setUInt32((uint32_t)cbData);
1744
1745 alock.release(); /* Drop the write lock before sending. */
1746
1747 uint32_t cbProcessed = 0;
1748 vrc = sendCommand(HOST_EXEC_SET_INPUT, i, paParms);
1749 if (RT_SUCCESS(vrc))
1750 {
1751 ProcessInputStatus_T inputStatus;
1752 vrc = waitForInputNotify(pEvent, uHandle, uTimeoutMS,
1753 &inputStatus, &cbProcessed);
1754 if (RT_SUCCESS(vrc))
1755 {
1756 /** @todo Set guestRc. */
1757
1758 if (puWritten)
1759 *puWritten = cbProcessed;
1760 }
1761 /** @todo Error handling. */
1762 }
1763
1764 unregisterWaitEvent(pEvent);
1765
1766 LogFlowThisFunc(("Returning cbProcessed=%RU32, rc=%Rrc\n",
1767 cbProcessed, vrc));
1768 return vrc;
1769}
1770
1771// implementation of public methods
1772/////////////////////////////////////////////////////////////////////////////
1773
1774STDMETHODIMP GuestProcess::Read(ULONG aHandle, ULONG aToRead, ULONG aTimeoutMS, ComSafeArrayOut(BYTE, aData))
1775{
1776#ifndef VBOX_WITH_GUEST_CONTROL
1777 ReturnComNotImplemented();
1778#else
1779 if (aToRead == 0)
1780 return setError(E_INVALIDARG, tr("The size to read is zero"));
1781 CheckComArgOutSafeArrayPointerValid(aData);
1782
1783 AutoCaller autoCaller(this);
1784 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1785
1786 com::SafeArray<BYTE> data((size_t)aToRead);
1787 Assert(data.size() >= aToRead);
1788
1789 HRESULT hr = S_OK;
1790
1791 uint32_t cbRead; int guestRc;
1792 int vrc = readData(aHandle, aToRead, aTimeoutMS, data.raw(), aToRead, &cbRead, &guestRc);
1793 if (RT_SUCCESS(vrc))
1794 {
1795 if (data.size() != cbRead)
1796 data.resize(cbRead);
1797 data.detachTo(ComSafeArrayOutArg(aData));
1798 }
1799 else
1800 {
1801 switch (vrc)
1802 {
1803 case VERR_GSTCTL_GUEST_ERROR:
1804 hr = GuestProcess::setErrorExternal(this, guestRc);
1805 break;
1806
1807 default:
1808 hr = setError(VBOX_E_IPRT_ERROR,
1809 tr("Reading from process \"%s\" (PID %RU32) failed: %Rrc"),
1810 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1811 break;
1812 }
1813 }
1814
1815 LogFlowThisFunc(("rc=%Rrc, cbRead=%RU32\n", vrc, cbRead));
1816
1817 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1818 return hr;
1819#endif /* VBOX_WITH_GUEST_CONTROL */
1820}
1821
1822STDMETHODIMP GuestProcess::Terminate(void)
1823{
1824#ifndef VBOX_WITH_GUEST_CONTROL
1825 ReturnComNotImplemented();
1826#else
1827 LogFlowThisFuncEnter();
1828
1829 AutoCaller autoCaller(this);
1830 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1831
1832 HRESULT hr = S_OK;
1833
1834 int guestRc;
1835 int vrc = terminateProcess(30 * 1000 /* Timeout in ms */,
1836 &guestRc);
1837 if (RT_FAILURE(vrc))
1838 {
1839 switch (vrc)
1840 {
1841 case VERR_GSTCTL_GUEST_ERROR:
1842 hr = GuestProcess::setErrorExternal(this, guestRc);
1843 break;
1844
1845 case VERR_NOT_SUPPORTED:
1846 hr = setError(VBOX_E_IPRT_ERROR,
1847 tr("Terminating process \"%s\" (PID %RU32) not supported by installed Guest Additions"),
1848 mData.mProcess.mCommand.c_str(), mData.mPID);
1849 break;
1850
1851 default:
1852 hr = setError(VBOX_E_IPRT_ERROR,
1853 tr("Terminating process \"%s\" (PID %RU32) failed: %Rrc"),
1854 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1855 break;
1856 }
1857 }
1858
1859 /* Remove the process from our internal session list. Only an API client
1860 * now may hold references to it. */
1861 AssertPtr(mSession);
1862 mSession->processRemoveFromList(this);
1863
1864 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1865 return hr;
1866#endif /* VBOX_WITH_GUEST_CONTROL */
1867}
1868
1869STDMETHODIMP GuestProcess::WaitFor(ULONG aWaitFlags, ULONG aTimeoutMS, ProcessWaitResult_T *aReason)
1870{
1871#ifndef VBOX_WITH_GUEST_CONTROL
1872 ReturnComNotImplemented();
1873#else
1874 LogFlowThisFuncEnter();
1875
1876 CheckComArgOutPointerValid(aReason);
1877
1878 AutoCaller autoCaller(this);
1879 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1880
1881 /*
1882 * Note: Do not hold any locks here while waiting!
1883 */
1884 HRESULT hr = S_OK;
1885
1886 int guestRc; ProcessWaitResult_T waitResult;
1887 int vrc = waitFor(aWaitFlags, aTimeoutMS, waitResult, &guestRc);
1888 if (RT_SUCCESS(vrc))
1889 {
1890 *aReason = waitResult;
1891 }
1892 else
1893 {
1894 switch (vrc)
1895 {
1896 case VERR_GSTCTL_GUEST_ERROR:
1897 hr = GuestProcess::setErrorExternal(this, guestRc);
1898 break;
1899
1900 case VERR_TIMEOUT:
1901 *aReason = ProcessWaitResult_Timeout;
1902 break;
1903
1904 default:
1905 hr = setError(VBOX_E_IPRT_ERROR,
1906 tr("Waiting for process \"%s\" (PID %RU32) failed: %Rrc"),
1907 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1908 break;
1909 }
1910 }
1911
1912 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1913 return hr;
1914#endif /* VBOX_WITH_GUEST_CONTROL */
1915}
1916
1917STDMETHODIMP GuestProcess::WaitForArray(ComSafeArrayIn(ProcessWaitForFlag_T, aFlags), ULONG aTimeoutMS, ProcessWaitResult_T *aReason)
1918{
1919#ifndef VBOX_WITH_GUEST_CONTROL
1920 ReturnComNotImplemented();
1921#else
1922 LogFlowThisFuncEnter();
1923
1924 CheckComArgOutPointerValid(aReason);
1925
1926 AutoCaller autoCaller(this);
1927 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1928
1929 /*
1930 * Note: Do not hold any locks here while waiting!
1931 */
1932 uint32_t fWaitFor = ProcessWaitForFlag_None;
1933 com::SafeArray<ProcessWaitForFlag_T> flags(ComSafeArrayInArg(aFlags));
1934 for (size_t i = 0; i < flags.size(); i++)
1935 fWaitFor |= flags[i];
1936
1937 return WaitFor(fWaitFor, aTimeoutMS, aReason);
1938#endif /* VBOX_WITH_GUEST_CONTROL */
1939}
1940
1941STDMETHODIMP GuestProcess::Write(ULONG aHandle, ULONG aFlags,
1942 ComSafeArrayIn(BYTE, aData), ULONG aTimeoutMS, ULONG *aWritten)
1943{
1944#ifndef VBOX_WITH_GUEST_CONTROL
1945 ReturnComNotImplemented();
1946#else
1947 LogFlowThisFuncEnter();
1948
1949 CheckComArgOutPointerValid(aWritten);
1950
1951 AutoCaller autoCaller(this);
1952 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1953
1954 com::SafeArray<BYTE> data(ComSafeArrayInArg(aData));
1955
1956 HRESULT hr = S_OK;
1957
1958 uint32_t cbWritten; int guestRc;
1959 int vrc = writeData(aHandle, aFlags, data.raw(), data.size(), aTimeoutMS, &cbWritten, &guestRc);
1960 if (RT_FAILURE(vrc))
1961 {
1962 switch (vrc)
1963 {
1964 case VERR_GSTCTL_GUEST_ERROR:
1965 hr = GuestProcess::setErrorExternal(this, guestRc);
1966 break;
1967
1968 default:
1969 hr = setError(VBOX_E_IPRT_ERROR,
1970 tr("Writing to process \"%s\" (PID %RU32) failed: %Rrc"),
1971 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1972 break;
1973 }
1974 }
1975
1976 LogFlowThisFunc(("rc=%Rrc, aWritten=%RU32\n", vrc, cbWritten));
1977
1978 *aWritten = (ULONG)cbWritten;
1979
1980 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1981 return hr;
1982#endif /* VBOX_WITH_GUEST_CONTROL */
1983}
1984
1985STDMETHODIMP GuestProcess::WriteArray(ULONG aHandle, ComSafeArrayIn(ProcessInputFlag_T, aFlags),
1986 ComSafeArrayIn(BYTE, aData), ULONG aTimeoutMS, ULONG *aWritten)
1987{
1988#ifndef VBOX_WITH_GUEST_CONTROL
1989 ReturnComNotImplemented();
1990#else
1991 LogFlowThisFuncEnter();
1992
1993 CheckComArgOutPointerValid(aWritten);
1994
1995 AutoCaller autoCaller(this);
1996 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1997
1998 /*
1999 * Note: Do not hold any locks here while writing!
2000 */
2001 ULONG fWrite = ProcessInputFlag_None;
2002 com::SafeArray<ProcessInputFlag_T> flags(ComSafeArrayInArg(aFlags));
2003 for (size_t i = 0; i < flags.size(); i++)
2004 fWrite |= flags[i];
2005
2006 return Write(aHandle, fWrite, ComSafeArrayInArg(aData), aTimeoutMS, aWritten);
2007#endif /* VBOX_WITH_GUEST_CONTROL */
2008}
2009
2010///////////////////////////////////////////////////////////////////////////////
2011
2012GuestProcessTool::GuestProcessTool(void)
2013 : pSession(NULL)
2014{
2015}
2016
2017GuestProcessTool::~GuestProcessTool(void)
2018{
2019 Terminate(30 * 1000, NULL /* pGuestRc */);
2020}
2021
2022int GuestProcessTool::Init(GuestSession *pGuestSession, const GuestProcessStartupInfo &startupInfo,
2023 bool fAsync, int *pGuestRc)
2024{
2025 LogFlowThisFunc(("pGuestSession=%p, szCmd=%s, fAsync=%RTbool\n",
2026 pGuestSession, startupInfo.mCommand.c_str(), fAsync));
2027
2028 AssertPtrReturn(pGuestSession, VERR_INVALID_POINTER);
2029
2030 pSession = pGuestSession;
2031 mStartupInfo = startupInfo;
2032
2033 /* Make sure the process is hidden. */
2034 mStartupInfo.mFlags |= ProcessCreateFlag_Hidden;
2035
2036 int vrc = pSession->processCreateExInteral(mStartupInfo, pProcess);
2037 if (RT_SUCCESS(vrc))
2038 vrc = fAsync ? pProcess->startProcessAsync() : pProcess->startProcess(30 * 1000 /* 30s timeout */,
2039 pGuestRc);
2040
2041 if ( RT_SUCCESS(vrc)
2042 && !fAsync
2043 && ( pGuestRc
2044 && RT_FAILURE(*pGuestRc)
2045 )
2046 )
2047 {
2048 vrc = VERR_GSTCTL_GUEST_ERROR;
2049 }
2050
2051 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
2052 return vrc;
2053}
2054
2055int GuestProcessTool::GetCurrentBlock(uint32_t uHandle, GuestProcessStreamBlock &strmBlock)
2056{
2057 const GuestProcessStream *pStream = NULL;
2058 if (uHandle == OUTPUT_HANDLE_ID_STDOUT)
2059 pStream = &mStdOut;
2060 else if (uHandle == OUTPUT_HANDLE_ID_STDERR)
2061 pStream = &mStdErr;
2062
2063 if (!pStream)
2064 return VERR_INVALID_PARAMETER;
2065
2066 int vrc;
2067 do
2068 {
2069 /* Try parsing the data to see if the current block is complete. */
2070 vrc = mStdOut.ParseBlock(strmBlock);
2071 if (strmBlock.GetCount())
2072 break;
2073 } while (RT_SUCCESS(vrc));
2074
2075 LogFlowThisFunc(("rc=%Rrc, %RU64 pairs\n",
2076 vrc, strmBlock.GetCount()));
2077 return vrc;
2078}
2079
2080bool GuestProcessTool::IsRunning(void)
2081{
2082 AssertReturn(!pProcess.isNull(), true);
2083
2084 ProcessStatus_T procStatus = ProcessStatus_Undefined;
2085 HRESULT hr = pProcess->COMGETTER(Status(&procStatus));
2086 Assert(SUCCEEDED(hr));
2087
2088 if ( procStatus != ProcessStatus_Started
2089 && procStatus != ProcessStatus_Paused
2090 && procStatus != ProcessStatus_Terminating)
2091 {
2092 return false;
2093 }
2094
2095 return true;
2096}
2097
2098int GuestProcessTool::TerminatedOk(LONG *pExitCode)
2099{
2100 Assert(!pProcess.isNull());
2101 /* pExitCode is optional. */
2102
2103 if (!IsRunning())
2104 {
2105 LONG exitCode;
2106 HRESULT hr = pProcess->COMGETTER(ExitCode(&exitCode));
2107 Assert(SUCCEEDED(hr));
2108
2109 if (pExitCode)
2110 *pExitCode = exitCode;
2111
2112 if (exitCode != 0)
2113 return VERR_NOT_EQUAL; /** @todo Special guest control rc needed! */
2114 return VINF_SUCCESS;
2115 }
2116
2117 return VERR_INVALID_STATE; /** @todo Special guest control rc needed! */
2118}
2119
2120int GuestProcessTool::Wait(uint32_t fFlags, int *pGuestRc)
2121{
2122 return WaitEx(fFlags, NULL /* pStreamBlock */, pGuestRc);
2123}
2124
2125int GuestProcessTool::WaitEx(uint32_t fFlags, GuestProcessStreamBlock *pStreamBlock, int *pGuestRc)
2126{
2127 LogFlowThisFunc(("pSession=%p, fFlags=0x%x, pStreamBlock=%p, pGuestRc=%p\n",
2128 pSession, fFlags, pStreamBlock, pGuestRc));
2129
2130 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2131 Assert(!pProcess.isNull());
2132 /* Other parameters are optional. */
2133
2134 /* Can we parse the next block without waiting? */
2135 int vrc;
2136 if (fFlags & GUESTPROCESSTOOL_FLAG_STDOUT_BLOCK)
2137 {
2138 AssertPtr(pStreamBlock);
2139 vrc = GetCurrentBlock(OUTPUT_HANDLE_ID_STDOUT, *pStreamBlock);
2140 if (RT_SUCCESS(vrc))
2141 return vrc;
2142 /* else do the the waiting below. */
2143 }
2144
2145 /* Do the waiting. */
2146 uint32_t fWaitFlags = ProcessWaitForFlag_Terminate;
2147 if (mStartupInfo.mFlags & ProcessCreateFlag_WaitForStdOut)
2148 fWaitFlags |= ProcessWaitForFlag_StdOut;
2149 if (mStartupInfo.mFlags & ProcessCreateFlag_WaitForStdErr)
2150 fWaitFlags |= ProcessWaitForFlag_StdErr;
2151
2152 LogFlowThisFunc(("waitFlags=0x%x\n", fWaitFlags));
2153
2154 /** @todo Decrease timeout while running. */
2155 uint32_t uTimeoutMS = mStartupInfo.mTimeoutMS;
2156
2157 int guestRc;
2158 bool fDone = false;
2159
2160 BYTE byBuf[_64K];
2161 uint32_t cbRead;
2162
2163 bool fHandleStdOut = false;
2164 bool fHandleStdErr = false;
2165
2166 ProcessWaitResult_T waitRes;
2167 do
2168 {
2169 vrc = pProcess->waitFor(fWaitFlags,
2170 uTimeoutMS, waitRes, &guestRc);
2171 if (RT_FAILURE(vrc))
2172 break;
2173
2174 switch (waitRes)
2175 {
2176 case ProcessWaitResult_StdIn:
2177 vrc = VERR_NOT_IMPLEMENTED;
2178 break;
2179
2180 case ProcessWaitResult_StdOut:
2181 fHandleStdOut = true;
2182 break;
2183
2184 case ProcessWaitResult_StdErr:
2185 fHandleStdErr = true;
2186 break;
2187
2188 case ProcessWaitResult_WaitFlagNotSupported:
2189 if (fWaitFlags & ProcessWaitForFlag_StdOut)
2190 fHandleStdOut = true;
2191 if (fWaitFlags & ProcessWaitForFlag_StdErr)
2192 fHandleStdErr = true;
2193 /* Since waiting for stdout / stderr is not supported by the guest,
2194 * wait a bit to not hog the CPU too much when polling for data. */
2195 RTThreadSleep(1); /* Optional, don't check rc. */
2196 break;
2197
2198 case ProcessWaitResult_Error:
2199 vrc = VERR_GSTCTL_GUEST_ERROR;
2200 break;
2201
2202 case ProcessWaitResult_Terminate:
2203 fDone = true;
2204 break;
2205
2206 case ProcessWaitResult_Timeout:
2207 vrc = VERR_TIMEOUT;
2208 break;
2209
2210 case ProcessWaitResult_Start:
2211 case ProcessWaitResult_Status:
2212 /* Not used here, just skip. */
2213 break;
2214
2215 default:
2216 AssertReleaseMsgFailed(("Unhandled process wait result %ld\n", waitRes));
2217 break;
2218 }
2219
2220 if (fHandleStdOut)
2221 {
2222 cbRead = 0;
2223 vrc = pProcess->readData(OUTPUT_HANDLE_ID_STDOUT, sizeof(byBuf),
2224 uTimeoutMS, byBuf, sizeof(byBuf),
2225 &cbRead, &guestRc);
2226 if (RT_FAILURE(vrc))
2227 break;
2228
2229 if (cbRead)
2230 {
2231 LogFlowThisFunc(("Received %RU32 bytes from stdout\n", cbRead));
2232 vrc = mStdOut.AddData(byBuf, cbRead);
2233
2234 if ( RT_SUCCESS(vrc)
2235 && (fFlags & GUESTPROCESSTOOL_FLAG_STDOUT_BLOCK))
2236 {
2237 AssertPtr(pStreamBlock);
2238 vrc = GetCurrentBlock(OUTPUT_HANDLE_ID_STDOUT, *pStreamBlock);
2239 if (RT_SUCCESS(vrc))
2240 fDone = true;
2241 }
2242 }
2243
2244 fHandleStdOut = false;
2245 }
2246
2247 if (fHandleStdErr)
2248 {
2249 cbRead = 0;
2250 vrc = pProcess->readData(OUTPUT_HANDLE_ID_STDERR, sizeof(byBuf),
2251 uTimeoutMS, byBuf, sizeof(byBuf),
2252 &cbRead, &guestRc);
2253 if (RT_FAILURE(vrc))
2254 break;
2255
2256 if (cbRead)
2257 {
2258 LogFlowThisFunc(("Received %RU32 bytes from stderr\n", cbRead));
2259 vrc = mStdErr.AddData(byBuf, cbRead);
2260 }
2261
2262 fHandleStdErr = false;
2263 }
2264
2265 } while (!fDone && RT_SUCCESS(vrc));
2266
2267 LogFlowThisFunc(("Loop ended with rc=%Rrc, guestRc=%Rrc, waitRes=%ld\n",
2268 vrc, guestRc, waitRes));
2269 if (pGuestRc)
2270 *pGuestRc = guestRc;
2271
2272 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
2273 return vrc;
2274}
2275
2276int GuestProcessTool::Terminate(uint32_t uTimeoutMS, int *pGuestRc)
2277{
2278 LogFlowThisFuncEnter();
2279
2280 int rc = VINF_SUCCESS;
2281 if (!pProcess.isNull())
2282 {
2283 rc = pProcess->terminateProcess(uTimeoutMS, pGuestRc);
2284
2285 Assert(pSession);
2286 int rc2 = pSession->processRemoveFromList(pProcess);
2287 AssertRC(rc2);
2288
2289 pProcess.setNull();
2290 }
2291 else
2292 rc = VERR_NOT_FOUND;
2293
2294 LogFlowFuncLeaveRC(rc);
2295 return rc;
2296}
2297
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