VirtualBox

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

Last change on this file since 83640 was 83472, checked in by vboxsync, 5 years ago

Guest Control/Main: Don't spin forever in GuestProcessTool::runExErrorInfo() if waiting for output failed for whatever reason. bugref:9320

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