VirtualBox

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

Last change on this file since 78352 was 78234, checked in by vboxsync, 6 years ago

Main/GuestCtrl: Fixed three i_waitForStatusChange() methods that would return VERR_GSTCTL_GUEST_ERROR without setting prcGuest, making the caller use uninitialized stack as status code for the operation. bugref:9320

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