VirtualBox

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

Last change on this file since 92916 was 92916, checked in by vboxsync, 3 years ago

Guest Control/Main: Added lots of missing docs [Doxygen fixes].

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