Stroika Library 3.0d22
 
Loading...
Searching...
No Matches
ProcessRunner.cpp
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#include "Stroika/Foundation/StroikaPreComp.h"
5
6#include <sstream>
7
8#if qStroika_Foundation_Common_Platform_POSIX
9#include <fcntl.h>
10#include <signal.h>
11#include <sys/resource.h>
12#include <sys/stat.h>
13#include <sys/types.h>
14#include <sys/wait.h>
15#include <unistd.h>
16#endif
17
23#include "Stroika/Foundation/Containers/Sequence.h"
25#if qStroika_Foundation_Common_Platform_Windows
26#include "Platform/Windows/Exception.h"
27#endif
28#include "Stroika/Foundation/Execution/Activity.h"
29#include "Stroika/Foundation/Execution/CommandLine.h"
30#include "Stroika/Foundation/Execution/Exceptions.h"
32#include "Stroika/Foundation/Execution/Module.h"
35#include "Stroika/Foundation/IO/FileSystem/FileUtils.h"
38#include "Stroika/Foundation/Memory/Common.h"
41#include "Stroika/Foundation/Streams/MemoryStream.h"
42#include "Stroika/Foundation/Streams/TextToBinary.h"
43
44#include "Sleep.h"
45#include "Thread.h"
46
47#include "ProcessRunner.h"
48
49using std::byte;
50
51using namespace Stroika::Foundation;
54using namespace Stroika::Foundation::Debug;
55using namespace Stroika::Foundation::Execution;
56using namespace Stroika::Foundation::Streams;
57using namespace Stroika::Foundation::Traversal;
58
60using Memory::MakeSharedPtr;
62
63// Comment this in to turn on aggressive noisy DbgTrace in this module
64// #define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
65
66#if USE_NOISY_TRACE_IN_THIS_MODULE_
67#include <fstream>
68#endif
69
70#if qStroika_Foundation_Common_Platform_POSIX
71namespace {
72 // no-except cuz the exception will show up in tracelog, and nothing useful to do, and could be quite bad to except cuz mostly used
73 // in cleanup, and could cause leaks
74 inline void CLOSE_ (int& fd) noexcept
75 {
76 if (fd >= 0) [[likely]] {
77 IgnoreExceptionsForCall (Handle_ErrNoResultInterruption ([fd] () -> int { return ::close (fd); }));
78 fd = -1;
79 }
80 }
81}
82#endif
83
84#if qStroika_Foundation_Common_Platform_POSIX
85namespace {
86 static const int kMaxFD_ = [] () -> int {
87 int result{};
88 constexpr bool kUseSysConf_ = true;
89#if _BSD_SOURCE || _XOPEN_SOURCE >= 500
90 [[maybe_unused]] constexpr bool kUseGetDTableSize_ = true;
91#else
92 [[maybe_unused]] constexpr bool kUseGetDTableSize_ = false;
93#endif
94 constexpr bool kUseGetRLimit_ = true;
95 if constexpr (kUseSysConf_) {
96 result = ::sysconf (_SC_OPEN_MAX);
97 Assert (result > 20); // from http://man7.org/linux/man-pages/man3/sysconf.3.html - Must not be less than _POSIX_OPEN_MAX (20).
98 }
99 else if constexpr (kUseSysConf_) {
100 result = getdtablesize ();
101 }
102 else if constexpr (kUseGetRLimit_) {
103 struct rlimit fds{};
104 if (::getrlimit (RLIMIT_NOFILE, &fds) == 0) {
105 return fds.rlim_cur;
106 }
107 else {
108 return 1024; // wag
109 }
110 }
111 /*
112 * A little crazy, but in docker containers, this max# of files can get quite large (I've seen it over 1024*1024).
113 * Probably at that point its smart to use some other technique to close all the extra file descriptors (like look at
114 * lsof() or read /proc/sys/fs/file-nr? Something like that
115 *
116 * -- LGP 2018-10-08
117 */
118 Assert (result > 5); // sanity check - no real requirement
119 Assert (result < 4 * 1024 * 1024); // "" (if too big, looping to close all costly)
120 DbgTrace ("::sysconf (_SC_OPEN_MAX) = {}"_f, result);
121 return result;
122 }();
123}
124#endif
125
126#if qStroika_Foundation_Common_Platform_POSIX
127namespace {
128 pid_t DoFork_ ()
129 {
130 // we may want to use vfork or some such. But for AIX, it appears best to use f_fork
131 // https://www.ibm.com/support/knowledgecenter/ssw_aix_72/com.ibm.aix.basetrf1/fork.htm
132 // -- LGP 2016-03-31
133 return ::fork ();
134 }
135}
136#endif
137
138#if qStroika_Foundation_Common_Platform_POSIX
139#include <spawn.h>
140namespace {
141 // https://www.ibm.com/support/knowledgecenter/ssw_aix_53/com.ibm.aix.basetechref/doc/basetrf1/posix_spawn.htm%23posix_spawn
142 // http://www.systutorials.com/37124/a-posix_spawn-example-in-c-to-create-child-process-on-linux/
143
144 constexpr bool kUseSpawn_ = false; // 1/2 implemented
145}
146extern char** environ;
147#endif
148
149#if qStroika_Foundation_Common_Platform_Windows
150namespace {
151 class AutoHANDLE_ {
152 public:
153 AutoHANDLE_ (HANDLE h = INVALID_HANDLE_VALUE)
154 : fHandle{h}
155 {
156 }
157 AutoHANDLE_ (const AutoHANDLE_&) = delete;
158 ~AutoHANDLE_ ()
159 {
160 Close ();
161 }
162 AutoHANDLE_& operator= (const AutoHANDLE_& rhs)
163 {
164 if (this != &rhs) {
165 Close ();
166 fHandle = rhs.fHandle;
167 }
168 return *this;
169 }
170 operator HANDLE () const
171 {
172 return fHandle;
173 }
174 HANDLE* operator& ()
175 {
176 return &fHandle;
177 }
178 void Close ()
179 {
180 if (fHandle != INVALID_HANDLE_VALUE) {
181 Verify (::CloseHandle (fHandle));
182 fHandle = INVALID_HANDLE_VALUE;
183 }
184 }
185 void ReplaceHandleAsNonInheritable ()
186 {
187 HANDLE result = INVALID_HANDLE_VALUE;
188 Verify (::DuplicateHandle (::GetCurrentProcess (), fHandle, ::GetCurrentProcess (), &result, 0, FALSE, DUPLICATE_SAME_ACCESS));
189 Verify (::CloseHandle (fHandle));
190 fHandle = result;
191 }
192
193 public:
194 HANDLE fHandle;
195 };
196 inline void SAFE_HANDLE_CLOSER_ (HANDLE* h)
197 {
198 RequireNotNull (h);
199 if (*h != INVALID_HANDLE_VALUE) {
200 Verify (::CloseHandle (*h));
201 *h = INVALID_HANDLE_VALUE;
202 }
203 }
204}
205#endif
206
207namespace {
208 template <Common::IAnyOf<char, wchar_t> CHAR_T>
209 struct String2ContigArrayCStrs_ {
210 StackBuffer<CHAR_T> fBytesBuffer;
211 StackBuffer<CHAR_T*, 10 * sizeof (void*)> fPtrsBuffer;
212 String2ContigArrayCStrs_ (const Mapping<basic_string<CHAR_T>, basic_string<CHAR_T>>& data)
213 : String2ContigArrayCStrs_{data.template Map<Iterable<basic_string<CHAR_T>>> (
214 [] (auto kvp) -> basic_string<CHAR_T> { return kvp.fKey + SDKSTR ("=") + kvp.fValue; })}
215 {
216 }
217 String2ContigArrayCStrs_ (const Iterable<basic_string<CHAR_T>>& data)
218 {
219 StackBuffer<size_t> argsIdx;
220 size_t bufferIndex = 0;
221 for (const basic_string<CHAR_T>& i : data) {
222 fBytesBuffer.push_back (span{i});
223 fBytesBuffer.push_back ('\0');
224 argsIdx.push_back (bufferIndex);
225 bufferIndex = fBytesBuffer.GetSize ();
226 }
227 fBytesBuffer.push_back ('\0'); // not sure - maybe not needed for UNIX, but needed on windows (cuz not using double fPtrsBuffer)
228 auto freeze = fBytesBuffer.begin ();
229 for (size_t i : argsIdx) {
230 fPtrsBuffer.push_back (freeze + i);
231 }
232 fPtrsBuffer.push_back (nullptr);
233 }
234 String2ContigArrayCStrs_ () = delete;
235 String2ContigArrayCStrs_ (const String2ContigArrayCStrs_&) = delete;
236 String2ContigArrayCStrs_ (String2ContigArrayCStrs_&&) = delete;
237 };
238}
239
240#if qStroika_Foundation_Common_Platform_Windows
241namespace {
242// still unsure if needed/useful - I now think the PeekNamedPipe stuff is NOT needed, but
243// I can turn it on if needed -- LGP 2009-05-07
244//#define qUsePeekNamedPipe_ 1
245#ifndef qUsePeekNamedPipe_
246#define qUsePeekNamedPipe_ 0
247#endif
248 /*
249 * This code should all work with the smaller buffer sizes, but is more efficient with larger buffers.
250 * Just set to use the smaller buffers to stress test and debug.
251 *
252 * There is some subtle but serious bug with my pipe code - and that APPEARS to just be that
253 * WaitForMultipleObjects doesn't work with PIPEs.
254 *
255 * I COULD just rewrite a lot of this code to NOT use PIPES - but actual files. That might solve the problem
256 * because they never 'fill up'.
257 *
258 * Alternatively - it might be that my switch to ASYNC mode (PIPE_NOWAIT) was a bad idea. Maybe if I got
259 * rid of that - the WAIT code could be made to work? Not sure.
260 *
261 * Anyhow - this appears to be adequate for now...
262 *
263 * -- LGP 2006-10-17
264 */
265 constexpr size_t kPipeBufSize_ = 256 * 1024;
266 constexpr size_t kReadBufSize_ = 32 * 1024;
267}
268#endif
269
270/*
271 ********************************************************************************
272 ***************** Execution::ProcessRunner::Exception **************************
273 ********************************************************************************
274 */
275String ProcessRunner::Exception::mkMsg_ (const String& errorMessage, const optional<String>& stderrSubset,
276 const optional<ExitStatusType>& wExitStatus, const optional<SignalID>& wTermSig)
277{
278 StringBuilder sb;
279 sb << errorMessage;
280 {
281 StringBuilder extraMsg;
282 if (wExitStatus) {
283 extraMsg << "exit status {}"_f(int (*wExitStatus));
284 }
285 if (wTermSig) {
286 if (not extraMsg.empty ()) {
287 extraMsg << ", "sv;
288 }
289 extraMsg << "terminated by signal {}"_f(int (*wTermSig));
290 }
291 if (not extraMsg.empty ()) {
292 sb << ": "sv << extraMsg;
293 }
294 }
295 if (stderrSubset) {
296 sb << " (captured stderr: "sv
297 << stderrSubset->ReplaceAll ("\\s+"_RegEx, " "sv).LimitLength (100, StringShorteningPreference::ePreferKeepRight) << ")"sv;
298 }
299 return sb;
300}
301
302/*
303 ********************************************************************************
304 **************** Execution::ProcessRunner::ProcessResultType *******************
305 ********************************************************************************
306 */
307void ProcessRunner::ProcessResultType::ThrowIfFailed ()
308{
309 if (fExitStatus and *fExitStatus != 0) {
310 Throw (Exception{"Child process failed", nullopt, *fExitStatus});
311 }
312 if (fTerminatedByUncaughtSignalNumber and *fTerminatedByUncaughtSignalNumber != 0) {
313 Throw (Exception{"Child process failed", nullopt, nullopt, *fTerminatedByUncaughtSignalNumber});
314 }
315}
316
317/*
318 ********************************************************************************
319 **************** Execution::ProcessRunner::BackgroundProcess *******************
320 ********************************************************************************
321 */
322ProcessRunner::BackgroundProcess::BackgroundProcess ()
323 : fRep_{MakeSharedPtr<Rep_> ()}
324{
325}
326
328{
329 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
330 Thread::Ptr t{fRep_->fProcessRunner};
331 t.ThrowIfDoneWithException ();
332 if (auto o = GetProcessResult ()) {
333 if (o->fExitStatus and o->fExitStatus != ExitStatusType{}) {
334 AssertNotReached (); // I don't think this can happen since it should have resulted in a propagated exception
335 }
336 if (o->fTerminatedByUncaughtSignalNumber) {
337 AssertNotReached (); // I don't think this can happen since it should have resulted in a propagated exception
338 }
339 }
340}
341
343{
344 // tmphack impl
346 DurationSeconds remaining = timeout;
347 while (remaining > DurationSeconds{0}) {
348 if (auto pr = GetChildProcessID ()) {
349 return;
350 }
351 Sleep (1);
352 remaining -= DurationSeconds{1};
353 }
354}
356{
357 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
358 Thread::Ptr t{fRep_->fProcessRunner};
359 t.WaitForDone (timeout);
360}
361
363{
364 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
365 Thread::Ptr t{fRep_->fProcessRunner};
366 t.Join (timeout);
367 // if he asserts in PropagateIfException () are wrong, I may need to call that here!
368}
369
371{
372 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
373 Thread::Ptr t{fRep_->fProcessRunner};
374 t.JoinUntil (timeoutAt);
375 // if he asserts in PropagateIfException () are wrong, I may need to call that here!
376}
377
379{
380 TraceContextBumper ctx{"ProcessRunner::BackgroundProcess::Terminate"};
381 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
382 // @todo? set thread to null when done -
383 //
384 // @todo - Note - UNTESTED, and probably not 100% right (esp error checking!!!
385 //
386 if (optional<pid_t> o = fRep_->fPID) {
387#if qStroika_Foundation_Common_Platform_POSIX
388 ::kill (SIGTERM, *o);
389#elif qStroika_Foundation_Common_Platform_Windows
390 // @todo - if this OpenProcess gives us any trouble, we can return the handle directory from the 'CreateRunnable' where we invoke the process
391 HANDLE processHandle = ::OpenProcess (PROCESS_TERMINATE, false, *o);
392 if (processHandle != nullptr) {
393 ::TerminateProcess (processHandle, 1);
394 ::CloseHandle (processHandle);
395 }
396 else {
397 DbgTrace ("::OpenProcess returned null: GetLastError () = {}"_f, GetLastError ());
398 }
399#else
401#endif
402 }
403}
404
405/*
406 ********************************************************************************
407 ************************** Execution::ProcessRunner ****************************
408 ********************************************************************************
409 */
410
411namespace {
413 {
414 return kRawEnvironment ();
415 }
417 {
418 return r;
419 }
421 {
423 for (auto i : env) {
424 r.Add (i.fKey.AsSDKString (), i.fValue.AsSDKString ());
425 }
426 return r;
427 }
429 {
430 Mapping<SDKString, SDKString> r = getEnv_ ();
431#if qStroika_Foundation_Common_Platform_POSIX
432 SDKString path = replacePath.Join<SDKString> ([] (const filesystem::path& p) -> SDKString { return p; }, SDKString{":"sv});
433#elif qStroika_Foundation_Common_Platform_Windows
434 SDKString path = replacePath.Join<SDKString> ([] (const filesystem::path& p) -> SDKString { return p; }, SDKString{L";"sv});
435#endif
436 r.Add (SDKSTR ("PATH"), path);
437 return r;
438 }
439}
440
441ProcessRunner::ProcessRunner (const String& commandLine, const Options& o)
442 : ProcessRunner{commandLine.ContainsAny ({'\'', '\"', '<', '>', '|', '$', '{', '}'}) ? CommandLine{kDefaultShell, commandLine} : CommandLine{commandLine}, o}
443{
444}
445
448{
449 TraceContextBumper ctx{"ProcessRunner::Run"};
450 auto activity = LazyEvalActivity ([this] () -> String { return "running '{}'"_f(this->GetCommandLine ()); });
451 DeclareActivity currentActivity{&activity};
452 if (timeout == Time::kInfinity) {
453 fStdIn_ = in;
454 fStdOut_ = out;
455 fStdErr_ = error;
457 CreateRunnable_ (&pr, nullptr, progress) ();
458 pr->value_or (ProcessResultType{}).ThrowIfFailed ();
459 }
460 else {
461 // Use 'BackgroundProcess' to get a thread we can interrupt when time is up, for timeout
462 BackgroundProcess bp = RunInBackground (in, out, error, progress);
463 [[maybe_unused]] auto&& cleanup = Finally ([&] () noexcept { bp.Terminate (); });
464 bp.Join (timeout);
465 bp.PropagateIfException ();
466 // If we didn't timeout, then the process must have completed, so we must have a process result
467 bp.GetProcessResult ().value_or (ProcessResultType{}).ThrowIfFailed ();
468 }
469}
470void ProcessRunner::Run (optional<ProcessResultType>* processResult, ProgressMonitor::Updater progress, Time::DurationSeconds timeout)
471{
472 TraceContextBumper ctx{"ProcessRunner::Run"}; //DEPREACTED API.... LOSE
473 if (timeout == Time::kInfinity) {
474 if (processResult == nullptr) {
475 CreateRunnable_ (nullptr, nullptr, progress) ();
476 }
477 else {
479 [[maybe_unused]] auto&& cleanup = Finally ([&] () noexcept { *processResult = pr.load (); });
480 CreateRunnable_ (&pr, nullptr, progress) ();
481 }
482 }
483 else {
484 if (processResult == nullptr) {
485 Thread::Ptr t = Thread::New (CreateRunnable_ (nullptr, nullptr, progress), Thread::eAutoStart, "ProcessRunner thread"_k);
486 t.Join (timeout);
487 }
488 else {
490 [[maybe_unused]] auto&& cleanup = Finally ([&] () noexcept { *processResult = pr.load (); });
491 Thread::Ptr t = Thread::New (CreateRunnable_ (&pr, nullptr, progress), Thread::eAutoStart, "ProcessRunner thread"_k);
492 t.Join (timeout);
493 }
494 }
495}
496
497auto ProcessRunner::Run (const String& cmdStdInValue, const StringOptions& stringOpts, ProgressMonitor::Updater progress,
498 Time::DurationSeconds timeout) -> tuple<String, String>
499{
500 AssertExternallySynchronizedMutex::WriteContext declareContext{fThisAssertExternallySynchronized_};
501 MemoryStream::Ptr<byte> useStdIn = MemoryStream::New<byte> ();
502 MemoryStream::Ptr<byte> useStdOut = MemoryStream::New<byte> ();
503 MemoryStream::Ptr<byte> useStdErr = MemoryStream::New<byte> ();
504
505 auto mkReadStream = [&] (const InputStream::Ptr<byte>& readFromBinStrm) {
506 return stringOpts.fInputCodeCvt ? BinaryToText::Reader::New (readFromBinStrm, *stringOpts.fInputCodeCvt)
507 : BinaryToText::Reader::New (readFromBinStrm);
508 };
509 try {
510 // Prefill stream
511 if (not cmdStdInValue.empty ()) {
512 auto outStream = stringOpts.fOutputCodeCvt ? TextToBinary::Writer::New (useStdIn, *stringOpts.fOutputCodeCvt)
513 : TextToBinary::Writer::New (useStdIn);
514 outStream.Write (cmdStdInValue);
515 }
516 Assert (useStdIn.GetReadOffset () == 0);
517
518 Run (useStdIn, useStdOut, useStdErr, progress, timeout);
519
520 // get and return results from 'useStdOut' etc
521 Assert (useStdOut.GetReadOffset () == 0);
522 Assert (useStdErr.GetReadOffset () == 0);
523 return make_tuple (mkReadStream (useStdOut).ReadAll (), mkReadStream (useStdErr).ReadAll ());
524 }
525 catch (const Exception& e) {
526 String out = mkReadStream (useStdOut).ReadAll ();
527 String err = mkReadStream (useStdErr).ReadAll ();
528#if qStroika_Foundation_Debug_DefaultTracingOn
529 DbgTrace ("Captured stdout: {}"_f, out);
530 DbgTrace ("Captured stderr: {}"_f, err);
531#endif
532 Throw (Exception{e.fFailureMessage, err, e.fExitStatus, e.fTermSignal});
533 Throw (Exception{this->fArgs_.As<String> (), "{}: output: {}, stderr: {}"_f(e.As<String> (), out, err)});
534 }
535 catch (...) {
536 String out = mkReadStream (useStdOut).ReadAll ();
537 String err = mkReadStream (useStdErr).ReadAll ();
538#if qStroika_Foundation_Debug_DefaultTracingOn
539 DbgTrace ("Captured stdout: {}"_f, out);
540 DbgTrace ("Captured stderr: {}"_f, err);
541#endif
542 exception_ptr e = current_exception ();
543 Throw (NestedException{"{} (stderr: {})"_f(e, err), e});
544 }
545}
546
549{
550 TraceContextBumper ctx{"ProcessRunner::RunInBackground"};
551 this->fStdIn_ = in;
552 this->fStdOut_ = out;
553 this->fStdErr_ = error;
554 BackgroundProcess result;
555 result.fRep_->fProcessRunner =
556 Thread::New (CreateRunnable_ (&result.fRep_->fResult, nullptr, progress), Thread::eAutoStart, "ProcessRunner background thread"sv);
557 return result;
558}
559
561{
562 TraceContextBumper ctx{"ProcessRunner::RunInBackground"}; // DEPRECATED OVERLOAD
563 BackgroundProcess result;
564 result.fRep_->fProcessRunner =
565 Thread::New (CreateRunnable_ (&result.fRep_->fResult, nullptr, progress), Thread::eAutoStart, "ProcessRunner background thread"sv);
566 return result;
567}
568
569#if qStroika_Foundation_Common_Platform_POSIX
570namespace {
571 // @todo Good Candidate for REWRITE - this is a MESS!
572 void Process_Runner_POSIX_ (Synchronized<optional<ProcessRunner::ProcessResultType>>* processResult, Synchronized<optional<pid_t>>* runningPID,
573 ProgressMonitor::Updater progress, [[maybe_unused]] const optional<filesystem::path>& executable,
574 const CommandLine& cmdLine, const ProcessRunner::Options& options, const InputStream::Ptr<byte>& in,
576 {
577 optional<mode_t> umask = options.fChildUMask;
578 filesystem::path useCWD = options.fWorkingDirectory.value_or (IO::FileSystem::WellKnownLocations::GetTemporary ());
580 "...,cmdLine='{}',currentDir='{}',..."_f, cmdLine,
581 String{useCWD}.LimitLength (50, StringShorteningPreference::ePreferKeepRight))};
582
583 // track the last few bytes of stderr to include in possible exception messages
584 char trailingStderrBuf[256];
585 char* trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
586 size_t trailingStderrBufNWritten{};
587
588 /*
589 * NOTE:
590 * From http://linux.die.net/man/2/pipe
591 * "The array pipefd is used to return two file descriptors referring to the ends
592 * of the pipe. pipefd[0] refers to the read end of the pipe. pipefd[1] refers to
593 * the write end of the pipe"
594 */
595 int jStdin[2]{-1, -1};
596 int jStdout[2]{-1, -1};
597 int jStderr[2]{-1, -1};
598 [[maybe_unused]] auto&& cleanup = Finally ([&] () noexcept {
599 ::CLOSE_ (jStdin[0]);
600 ::CLOSE_ (jStdin[1]);
601 ::CLOSE_ (jStdout[0]);
602 ::CLOSE_ (jStdout[1]);
603 ::CLOSE_ (jStderr[0]);
604 ::CLOSE_ (jStderr[1]);
605 });
606 if (in) {
607 Handle_ErrNoResultInterruption ([&jStdin] () -> int { return ::pipe (jStdin); });
608 }
609 else {
610 jStdin[0] = ::open ("/dev/null", O_RDONLY);
611 }
612 if (out) {
613 Handle_ErrNoResultInterruption ([&jStdout] () -> int { return ::pipe (jStdout); });
614 }
615 else {
616 jStdout[1] = ::open ("/dev/null", O_WRONLY);
617 }
618 if (err) {
619 Handle_ErrNoResultInterruption ([&jStderr] () -> int { return ::pipe (jStderr); });
620 }
621 else {
622 jStderr[1] = ::open ("/dev/null", O_WRONLY);
623 }
624 // assert cuz code below needs to be more careful if these can overlap 0..2
625 Assert (in == nullptr or (jStdin[0] >= 3 and jStdin[1] >= 3));
626 Assert (out == nullptr or (jStdout[0] >= 3 and jStdout[1] >= 3));
627 Assert (err == nullptr or (jStderr[0] >= 3 and jStderr[1] >= 3));
628 DbgTrace ("jStdout[0-CHILD] = {} and jStdout[1-PARENT] = {}"_f, jStdout[0], jStdout[1]);
629
630 /*
631 * Note: Important to do all this code before the fork, because once we fork, we, lose other threads
632 * but share copy of RAM, so they COULD have mutexes locked! And we could deadlock waiting on them, so after
633 * fork, we are VERY limited as to what we can safely do.
634 */
635 const char* thisEXEPath_cstr = nullptr;
636 char** thisEXECArgv = nullptr;
637
638 String2ContigArrayCStrs_<char> execDataArgs{
639 cmdLine.GetArguments ().Map<Iterable<string>> ([] (auto si) { return si.AsNarrowSDKString (); })};
640 thisEXEPath_cstr = execDataArgs.fBytesBuffer.data ();
641 thisEXECArgv = execDataArgs.fPtrsBuffer.data ();
642
643 /*
644 * If the file is not accessible, and using fork/exec, we wont find that out til the execvp,
645 * and then there wont be a good way to propagate the error back to the caller.
646 *
647 * @todo for now - this code only checks access for absolute/full path, and we should also check using
648 * PATH and https://linux.die.net/man/3/execvp confstr(_CS_PATH)
649 */
650 if (not kUseSpawn_ and thisEXEPath_cstr[0] == '/' and ::access (thisEXEPath_cstr, R_OK | X_OK) < 0) {
651 errno_t e = errno; // save in case overwritten
652#if USE_NOISY_TRACE_IN_THIS_MODULE_
653 DbgTrace ("failed to access exe path so throwing: exe path='{}'"_f, String::FromNarrowSDKString (thisEXEPath_cstr));
654#endif
655 ThrowPOSIXErrNo (e);
656 }
657
658 pid_t childPID{};
659 if (kUseSpawn_) {
660 posix_spawn_file_actions_t file_actions{};
661 /// @see http://stackoverflow.com/questions/13893085/posix-spawnp-and-piping-child-output-to-a-string
662 // not quite right - maybe not that close
663 /*
664 * move arg stdin/out/err to 0/1/2 file-descriptors. Don't bother with variants that can handle errors/exceptions cuz we cannot really here...
665 */
666 {
667 posix_spawn_file_actions_init (&file_actions);
668 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
669 posix_spawn_file_actions_addclose (&file_actions, jStdin[0]);
670 posix_spawn_file_actions_adddup2 (&file_actions, jStdout[1], 1);
671 posix_spawn_file_actions_addclose (&file_actions, jStdout[0]);
672 posix_spawn_file_actions_adddup2 (&file_actions, jStderr[1], 2);
673 posix_spawn_file_actions_addclose (&file_actions, jStderr[1]);
674 }
675 posix_spawnattr_t* attr = nullptr;
676 int status = ::posix_spawnp (&childPID, thisEXEPath_cstr, &file_actions, attr, thisEXECArgv, environ);
677 if (status != 0) {
678 ThrowPOSIXErrNo (status);
679 }
680 }
681 else {
682 childPID = DoFork_ ();
683 ThrowPOSIXErrNoIfNegative (childPID);
684 if (childPID == 0) {
685 if (umask) {
686 (void)::umask (*umask);
687 }
688 try {
689 /*
690 * In child process. Don't DBGTRACE here, or do anything that could raise an exception. In the child process
691 * this would be bad...
692 */
693 DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wunused-result\"")
694 (void)::chdir (useCWD.c_str ());
695 DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wunused-result\"")
696 if (options.fDetached.value_or (false)) {
697 /*
698 * See http://pubs.opengroup.org/onlinepubs/007904875/functions/setsid.html
699 * This is similar to setpgrp () but makes doing setpgrp unnecessary.
700 * This is also similar to setpgid (0, 0) - but makes doing that unneeded.
701 *
702 * Avoid signals like SIGHUP when the terminal session ends as well as potentially SIGTTIN and SIGTTOU
703 *
704 * @see http://stackoverflow.com/questions/8777602/why-must-detach-from-tty-when-writing-a-linux-daemon
705 *
706 * Tried using
707 * #if defined _DEFAULT_SOURCE
708 * daemon (0, 0);
709 * #endif
710 * to workaround systemd defaulting to KillMode=control-group
711 */
712 (void)::setsid ();
713 }
714 {
715 /*
716 * move arg stdin/out/err to 0/1/2 file-descriptors. Don't bother with variants that can handle errors/exceptions cuz we cannot really here...
717 */
718 int useSTDIN = jStdin[0];
719 int useSTDOUT = jStdout[1];
720 int useSTDERR = jStderr[1];
721 Assert (useSTDIN >= 0 and useSTDOUT >= 0 and useSTDERR >= 0); // parent can have -1 FDs, but child always has legit FDs
722 ::close (0);
723 ::close (1);
724 ::close (2);
725 ::dup2 (useSTDIN, 0);
726 ::dup2 (useSTDOUT, 1);
727 ::dup2 (useSTDERR, 2);
728 ::close (jStdin[0]);
729 ::close (jStdin[1]);
730 ::close (jStdout[0]);
731 ::close (jStdout[1]);
732 ::close (jStderr[0]);
733 ::close (jStderr[1]);
734 }
735 constexpr bool kCloseAllExtraneousFDsInChild_ = true;
736 if (kCloseAllExtraneousFDsInChild_) {
737 // close all but stdin, stdout, and stderr in child fork
738 for (int i = 3; i < kMaxFD_; ++i) {
739 ::close (i);
740 }
741 }
742 [[maybe_unused]] int r = ::execvp (thisEXEPath_cstr, thisEXECArgv);
743#if USE_NOISY_TRACE_IN_THIS_MODULE_
744 {
745 ofstream myfile;
746 myfile.open ("/tmp/Stroika-ProcessRunner-Exec-Failed-Debug-File.txt");
747 myfile << "thisEXEPath_cstr = " << thisEXEPath_cstr << endl;
748 myfile << "r = " << r << " and errno = " << errno << endl;
749 }
750#endif
751 ::_exit (EXIT_FAILURE);
752 }
753 catch (...) {
754 ::_exit (EXIT_FAILURE);
755 }
756 }
757 }
758 // we got here, the spawn succeeded, or the fork succeeded, and we are the parent process
759 Assert (childPID > 0);
760 {
761 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
762
763#if USE_NOISY_TRACE_IN_THIS_MODULE_
764 DbgTrace ("In Parent Fork: child process PID={}"_f, childPID);
765#endif
766 if (runningPID != nullptr) {
767 runningPID->store (childPID);
768 }
769 /*
770 * WE ARE PARENT
771 */
772 int& useSTDIN = jStdin[1];
773 int& useSTDOUT = jStdout[0];
774 int& useSTDERR = jStderr[0];
775 {
776 CLOSE_ (jStdin[0]);
777 CLOSE_ (jStdout[1]);
778 CLOSE_ (jStderr[1]);
779 }
780
781 // To incrementally read from stderr and stderr as we write to stdin, we must assure
782 // our pipes are non-blocking
783 if (useSTDIN != -1) {
784 ThrowPOSIXErrNoIfNegative (::fcntl (useSTDIN, F_SETFL, fcntl (useSTDIN, F_GETFL, 0) | O_NONBLOCK));
785 }
786 if (useSTDOUT != -1) {
787 ThrowPOSIXErrNoIfNegative (::fcntl (useSTDOUT, F_SETFL, fcntl (useSTDOUT, F_GETFL, 0) | O_NONBLOCK));
788 }
789 if (useSTDERR != -1) {
790 ThrowPOSIXErrNoIfNegative (::fcntl (useSTDERR, F_SETFL, fcntl (useSTDERR, F_GETFL, 0) | O_NONBLOCK));
791 }
792
793 // Throw if any errors except EINTR (which is ignored) or EAGAIN (would block)
794 auto readALittleFromProcess = [&] (int fd, const OutputStream::Ptr<byte>& stream, bool write2StdErrCache, bool* eof = nullptr,
795 bool* maybeMoreData = nullptr) -> void {
796 if (fd == -1) {
797 if (maybeMoreData != nullptr) {
798 *maybeMoreData = false;
799 }
800 if (eof != nullptr) {
801 *eof = true;
802 }
803 return;
804 }
805 uint8_t buf[kStackBufReadAtATimeSize_];
806 int nBytesRead = 0; // int cuz we must allow for errno = EAGAIN error result = -1,
807#if USE_NOISY_TRACE_IN_THIS_MODULE_
808 int skipedThisMany{};
809#endif
810 while ((nBytesRead = ::read (fd, buf, sizeof (buf))) > 0) {
811 Assert (nBytesRead <= sizeof (buf));
812 if (stream != nullptr) {
813 stream.Write (span{buf, static_cast<size_t> (nBytesRead)});
814 }
815 if (write2StdErrCache) {
816 for (size_t i = 0; i < nBytesRead; ++i) {
817 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and
818 trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
819 *trailingStderrBufNextByte2WriteAt = buf[i];
820 ++trailingStderrBufNWritten;
821 ++trailingStderrBufNextByte2WriteAt;
822 if (trailingStderrBufNextByte2WriteAt == end (trailingStderrBuf)) {
823 trailingStderrBufNextByte2WriteAt = begin (trailingStderrBuf);
824 }
825 Assert (&trailingStderrBuf[0] <= trailingStderrBufNextByte2WriteAt and
826 trailingStderrBufNextByte2WriteAt < end (trailingStderrBuf));
827 }
828 }
829#if USE_NOISY_TRACE_IN_THIS_MODULE_
830 if (errno == EAGAIN) {
831 // If we get lots of EAGAINS, just skip logging them to avoid spamming the tracelog
832 if (skipedThisMany++ < 100) {
833 continue;
834 }
835 else {
836 DbgTrace ("skipped {} spamming EAGAINs"_f, skipedThisMany);
837 skipedThisMany = 0;
838 }
839 }
840 buf[(nBytesRead == std::size (buf)) ? (std::size (buf) - 1) : nBytesRead] = '\0';
841 DbgTrace ("read from process (fd={}) nBytesRead = {}: {}"_f, fd, nBytesRead,
842 String::FromNarrowSDKString (reinterpret_cast<const char*> (buf)));
843#endif
844 }
845#if USE_NOISY_TRACE_IN_THIS_MODULE_
846 DbgTrace ("from (fd={}) nBytesRead = {}, errno={}"_f, fd, nBytesRead, errno);
847#endif
848 if (nBytesRead < 0) {
849 if (errno != EINTR and errno != EAGAIN) {
850 ThrowPOSIXErrNo (errno);
851 }
852 }
853 if (eof != nullptr) {
854 *eof = (nBytesRead == 0);
855 }
856 if (maybeMoreData != nullptr) {
857 *maybeMoreData = (nBytesRead > 0) or (nBytesRead < 0 and errno == EINTR);
858 }
859 };
860 auto readSoNotBlocking = [&] (int fd, const OutputStream::Ptr<byte>& stream, bool write2StdErrCache) {
861 bool maybeMoreData = true;
862 while (maybeMoreData) {
863 readALittleFromProcess (fd, stream, write2StdErrCache, nullptr, &maybeMoreData);
864 }
865 };
866 auto readTilEOF = [&] (int fd, const OutputStream::Ptr<byte>& stream, bool write2StdErrCache) {
867 if (fd == -1) {
868 return;
869 }
870 WaitForIOReady waiter{fd};
871 bool eof = false;
872 while (not eof) {
873 (void)waiter.WaitQuietly (1s);
874 readALittleFromProcess (fd, stream, write2StdErrCache, &eof);
875 }
876 };
877
878 if (in != nullptr) {
879 byte stdinBuf[kStackBufReadAtATimeSize_];
880 // read to 'in' til it reaches EOF (returns 0). But don't fully block, cuz we want to at least trickle in the stdout/stderr data
881 // even if no input is ready to send to child.
882 while (true) {
883 if (optional<span<byte>> bytesReadFromStdIn = in.ReadNonBlocking (span{stdinBuf})) {
884 Assert (bytesReadFromStdIn->size () <= std::size (stdinBuf));
885 if (bytesReadFromStdIn->empty ()) {
886 break;
887 }
888 else {
889 const byte* e = bytesReadFromStdIn->data () + bytesReadFromStdIn->size ();
890 for (const byte* i = bytesReadFromStdIn->data (); i != e;) {
891 // read stuff from stdout, stderr while pushing to stdin, so that we don't get the PIPE buf too full
892 readSoNotBlocking (useSTDOUT, out, false);
893 readSoNotBlocking (useSTDERR, err, true);
894 int bytesWritten = ThrowPOSIXErrNoIfNegative (Handle_ErrNoResultInterruption ([useSTDIN, i, e] () {
895 int tmp = ::write (useSTDIN, i, e - i);
896 // NOTE: https://linux.die.net/man/2/write appears to indicate on pipe full, write could return 0, or < 0 with errno = EAGAIN, or EWOULDBLOCK
897 if (tmp < 0 and (errno == EAGAIN or errno == EWOULDBLOCK)) {
898 tmp = 0;
899 }
900 return tmp;
901 }));
902 Assert (bytesWritten >= 0);
903 Assert (bytesWritten <= (e - i));
904 i += bytesWritten;
905 if (bytesWritten == 0) {
906 // don't busy wait, but not clear how long to wait? Maybe should only sleep if readSoNotBlocking above returns no change
907 //
908 // OK - this is clearly wrong - @see http://stroika-bugs.sophists.com/browse/STK-589 - Fix performance of ProcessRunner - use select / poll instead of sleep when write to pipe returns 0
909 //
910 Sleep (1ms);
911 }
912 }
913 }
914 }
915 else {
916 // nothing on input stream, so pull from stdout, stderr, and wait a little to avoid busy-waiting
917 readSoNotBlocking (useSTDOUT, out, false);
918 readSoNotBlocking (useSTDERR, err, true);
919 Sleep (100ms);
920 }
921 }
922 }
923 // in case child process reads from its STDIN to EOF
924 CLOSE_ (useSTDIN);
925
926 readTilEOF (useSTDOUT, out, false);
927 readTilEOF (useSTDERR, err, true);
928
929 // not sure we need?
930 int status = 0;
931 int flags = 0; // FOR NOW - HACK - but really must handle sig-interruptions...
932 // Wait for child
933 int result =
934 Handle_ErrNoResultInterruption ([childPID, &status, flags] () -> int { return ::waitpid (childPID, &status, flags); });
935 // throw / warn if result other than child exited normally
936 if (processResult != nullptr) {
937 // not sure what it means if result != childPID??? - I think cannot happen cuz we pass in childPID, less result=-1
938 processResult->store (ProcessRunner::ProcessResultType{WIFEXITED (status) ? WEXITSTATUS (status) : optional<int> (),
939 WIFSIGNALED (status) ? WTERMSIG (status) : optional<int> ()});
940 }
941 else if (result != childPID or not WIFEXITED (status) or WEXITSTATUS (status) != 0) {
942 // @todo fix this message
943 DbgTrace ("childPID={}, result={}, status={}, WIFEXITED={}, WEXITSTATUS={}, WIFSIGNALED={}"_f, static_cast<int> (childPID),
944 result, status, WIFEXITED (status), WEXITSTATUS (status), WIFSIGNALED (status));
945 if (processResult == nullptr) {
946 StringBuilder stderrMsg;
947 if (trailingStderrBufNWritten > std::size (trailingStderrBuf)) {
948 stderrMsg << "..."sv;
949 stderrMsg << String::FromLatin1 (Memory::ConstSpan (span{trailingStderrBufNextByte2WriteAt, end (trailingStderrBuf)}));
950 }
951 stderrMsg << String::FromLatin1 (Memory::ConstSpan (span{begin (trailingStderrBuf), trailingStderrBufNextByte2WriteAt}));
952 Throw (ProcessRunner::Exception{"Spawned program"sv, stderrMsg.str (),
953 WIFEXITED (status) ? WEXITSTATUS (status) : optional<uint8_t>{},
954 WIFSIGNALED (status) ? WTERMSIG (status) : optional<uint8_t>{}});
955 }
956 }
957 }
958 }
959}
960#endif
961
962#if qStroika_Foundation_Common_Platform_Windows
963namespace {
964 void Process_Runner_Windows_ (Synchronized<optional<ProcessRunner::ProcessResultType>>* processResult,
965 Synchronized<optional<pid_t>>* runningPID, [[maybe_unused]] ProgressMonitor::Updater progress,
966 const optional<filesystem::path>& executable, const CommandLine& cmdLine, const ProcessRunner::Options& options,
968 {
969 filesystem::path useCWD = options.fWorkingDirectory.value_or (IO::FileSystem::WellKnownLocations::GetTemporary ());
970 TraceContextBumper ctx{"{}::Process_Runner_Windows_", Stroika_Foundation_Debug_OptionalizeTraceArgs (
971 "...,cmdLine='{}',currentDir={},..."_f, cmdLine,
972 String{useCWD}.LimitLength (50, StringShorteningPreference::ePreferKeepRight))};
973
974 /*
975 * o Build directory into which we can copy the JAR file plugin,
976 * o create STDIN/STDOUT file handles to send/grab results
977 * o Run the process, waiting for it to finish.
978 * o Grab results from STDOUT file.
979 * o Cleanup created directory.
980 */
981
982 // use AutoHANDLE so these are automatically closed at the end of the procedure, whether it ends normally or via
983 // exception.
984 AutoHANDLE_ jStdin[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
985 AutoHANDLE_ jStdout[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
986 AutoHANDLE_ jStderr[2]{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
987
988 PROCESS_INFORMATION processInfo{};
989 processInfo.hProcess = INVALID_HANDLE_VALUE;
990 processInfo.hThread = INVALID_HANDLE_VALUE;
991
992 try {
993 {
994 SECURITY_DESCRIPTOR sd{};
995 Verify (::InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION));
996 Verify (::SetSecurityDescriptorDacl (&sd, true, 0, false));
997 SECURITY_ATTRIBUTES sa = {sizeof (SECURITY_ATTRIBUTES), &sd, true};
998 if (in) {
999 Verify (::CreatePipe (&jStdin[1], &jStdin[0], &sa, kPipeBufSize_));
1000 }
1001 if (out) {
1002 Verify (::CreatePipe (&jStdout[1], &jStdout[0], &sa, kPipeBufSize_));
1003 }
1004 if (err) {
1005 Verify (::CreatePipe (&jStderr[1], &jStderr[0], &sa, kPipeBufSize_));
1006 }
1007 /*
1008 * Make sure the ends of the pipe WE hang onto are not inheritable, because otherwise the READ
1009 * wont return EOF (until the last one is closed).
1010 */
1011 if (in) {
1012 jStdin[0].ReplaceHandleAsNonInheritable ();
1013 }
1014 if (out) {
1015 jStdout[1].ReplaceHandleAsNonInheritable ();
1016 }
1017 if (err) {
1018 jStderr[1].ReplaceHandleAsNonInheritable ();
1019 }
1020 }
1021
1022 STARTUPINFO startInfo{};
1023 startInfo.cb = sizeof (startInfo);
1024 startInfo.hStdInput = jStdin[1];
1025 startInfo.hStdOutput = jStdout[0];
1026 startInfo.hStdError = jStderr[0];
1027 startInfo.dwFlags |= STARTF_USESTDHANDLES;
1028
1029 DWORD createProcFlags{NORMAL_PRIORITY_CLASS};
1030 if (options.fCreateNoWindow) {
1031 createProcFlags |= CREATE_NO_WINDOW;
1032 }
1033 else if (options.fDetached.value_or (false)) {
1034 // DETACHED_PROCESS ignored if CREATE_NO_WINDOW
1035 createProcFlags |= DETACHED_PROCESS;
1036 }
1037
1038 {
1039 // UNCLEAR; visual studio system() impl uses true; docs not clear
1040 // BUT - when I use false I get "unknown file: error: C++ exception with description "Spawned program 'echo hi mom' failed: error: 1" thrown in the test body." for some tests
1041 bool bInheritHandles = true;
1042
1043 TCHAR cmdLineBuf[32768]; // crazy MSFT definition! - why this should need to be non-const!
1044 Characters::CString::Copy (cmdLineBuf, std::size (cmdLineBuf), cmdLine.As<String> ().AsSDKString ().c_str ());
1045
1046 optional<filesystem::path> useEXEPath = executable;
1047
1048 // WARN if EXE not in path...
1049#if qStroika_Foundation_Debug_AssertionsChecked
1050 if (useEXEPath) {
1051 if (!FindExecutableInPath (*useEXEPath)) {
1052 DbgTrace ("Warning: Cannot find exe '{}' in PATH ({})"_f, useEXEPath, kPath ());
1053 }
1054 }
1055 else {
1056 // not sure we want to do this? - since first thing could be magic interpreted by shell, like set
1057 auto cmdArgs = cmdLine.GetArguments ();
1058 if (cmdArgs.size () >= 1) {
1059 filesystem::path exe2Find = cmdArgs[0].As<filesystem::path> ();
1060 if (!FindExecutableInPath (exe2Find)) {
1061 DbgTrace ("Warning: Cannot find exe '{}' in PATH ({})"_f, exe2Find, kPath ());
1062 }
1063 }
1064 }
1065#endif
1066
1067 unique_ptr<String2ContigArrayCStrs_<SDKChar>> envBuffer;
1068 LPVOID lpEnvironment = nullptr;
1069 if (options.fEnvironment) {
1070 if (auto oep = get_if<Sequence<filesystem::path>> (&options.fEnvironment.value ())) {
1071 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oep));
1072 }
1073 else if (auto om = get_if<Mapping<String, String>> (&options.fEnvironment.value ())) {
1074 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*om));
1075 }
1076 else if (auto oms = get_if<Mapping<SDKString, SDKString>> (&options.fEnvironment.value ())) {
1077 envBuffer = make_unique<String2ContigArrayCStrs_<SDKChar>> (getEnv_ (*oms));
1078 }
1079 AssertNotNull (envBuffer);
1080 lpEnvironment = envBuffer->fBytesBuffer.data (); // need to adjust createProcFlags for type used...
1081 if constexpr (same_as<SDKChar, wchar_t>) {
1082 createProcFlags |= CREATE_UNICODE_ENVIRONMENT;
1083 }
1084 }
1085
1086 // see https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa
1087 // for complex rules for interpreting nullptr in appname (first) arg, and cmdLineBuf... But mostly - the idea - is
1088 // it runs the search path algorithm and tries to do the right thing
1090 ::CreateProcess (useEXEPath == nullopt ? nullptr : useEXEPath->c_str (), cmdLineBuf, nullptr, nullptr, bInheritHandles,
1091 createProcFlags, lpEnvironment, useCWD.c_str (), &startInfo, &processInfo));
1092 }
1093
1094 if (runningPID != nullptr) {
1095 runningPID->store (processInfo.dwProcessId);
1096 }
1097
1098 {
1099 /*
1100 * Remove our copy of the stdin/stdout/stderr which belong to the child (so EOF will work properly).
1101 */
1102 jStdin[1].Close ();
1103 jStdout[0].Close ();
1104 jStderr[0].Close ();
1105 }
1106
1107 AutoHANDLE_& useSTDIN = jStdin[0];
1108 Assert (jStdin[1] == INVALID_HANDLE_VALUE);
1109 AutoHANDLE_& useSTDOUT = jStdout[1];
1110 Assert (jStdout[0] == INVALID_HANDLE_VALUE);
1111 AutoHANDLE_& useSTDERR = jStderr[1];
1112 Assert (jStderr[0] == INVALID_HANDLE_VALUE);
1113
1114 constexpr size_t kStackBufReadAtATimeSize_ = 10 * 1024;
1115
1116 auto readAnyAvailableAndCopy2StreamWithoutBlocking = [] (HANDLE p, const OutputStream::Ptr<byte>& o) {
1117 if (p == INVALID_HANDLE_VALUE) {
1118 return;
1119 }
1120 byte buf[kReadBufSize_];
1121#if qUsePeekNamedPipe_
1122 DWORD nBytesAvail{};
1123#endif
1124 DWORD nBytesRead{};
1125 // Read normally blocks, we don't want to because we may need to write more before it can output
1126 // and we may need to timeout
1127 while (
1128#if qUsePeekNamedPipe_
1129 ::PeekNamedPipe (p, nullptr, nullptr, nullptr, &nBytesAvail, nullptr) and nBytesAvail != 0 and
1130#endif
1131 ::ReadFile (p, buf, sizeof (buf), &nBytesRead, nullptr) and nBytesRead > 0) {
1132 if (o != nullptr) {
1133 o.Write (span{buf, nBytesRead});
1134 }
1135#if USE_NOISY_TRACE_IN_THIS_MODULE_
1136 buf[(nBytesRead == std::size (buf)) ? (std::size (buf) - 1) : nBytesRead] = byte{'\0'};
1137 DbgTrace ("read from process (fd={}) nBytesRead = {}: {}"_f, p, nBytesRead, buf);
1138#endif
1139 }
1140 };
1141
1142 if (processInfo.hProcess != INVALID_HANDLE_VALUE) {
1143 {
1144 {
1145 /*
1146 * Set the pipe endpoints to non-blocking mode.
1147 */
1148 auto mkPipeNoWait_ = [] (HANDLE ioHandle) -> void {
1149 if (ioHandle != INVALID_HANDLE_VALUE) {
1150 DWORD mode = 0;
1151 Verify (::GetNamedPipeHandleState (ioHandle, &mode, nullptr, nullptr, nullptr, nullptr, 0));
1152 mode |= PIPE_NOWAIT;
1153 Verify (::SetNamedPipeHandleState (ioHandle, &mode, nullptr, nullptr));
1154 }
1155 };
1156 mkPipeNoWait_ (useSTDIN);
1157 mkPipeNoWait_ (useSTDOUT);
1158 mkPipeNoWait_ (useSTDERR);
1159 }
1160
1161 /*
1162 * Fill child-process' stdin with the source document.
1163 */
1164 if (in != nullptr) {
1165 byte stdinBuf[kStackBufReadAtATimeSize_];
1166 // blocking read to 'in' til it reaches EOF (returns 0)
1167 while (size_t nbytes = in.ReadBlocking (span{stdinBuf}).size ()) {
1168 Assert (nbytes <= std::size (stdinBuf));
1169 const byte* p = begin (stdinBuf);
1170 const byte* e = p + nbytes;
1171 while (p < e) {
1172 DWORD written = 0;
1173 if (::WriteFile (useSTDIN, p, Math::PinToMaxForType<DWORD> (e - p), &written, nullptr) == 0) {
1174 DWORD lastErr = ::GetLastError ();
1175 // sometimes we fail because the target process hasn't read enough and the pipe is full.
1176 // Unfortunately - MSFT doesn't seem to have a single clear error message nor any clear
1177 // documentation about what WriteFile () returns in this case... So there maybe other errors
1178 // that are innocuous that may cause is to prematurely terminate our 'RunExternalProcess'.
1179 // -- LGP 2009-05-07
1180 if (lastErr != ERROR_SUCCESS and lastErr != ERROR_NO_MORE_FILES and lastErr != ERROR_PIPE_BUSY and
1181 lastErr != ERROR_NO_DATA) {
1182 DbgTrace ("in RunExternalProcess_ - throwing {} while fill in stdin"_f, lastErr);
1183 ThrowSystemErrNo (lastErr);
1184 }
1185 }
1186 Assert (written <= static_cast<size_t> (e - p));
1187 p += written;
1188 // in case we are failing to write to the stdIn because of blocked output on an outgoing pipe
1189 if (p < e) {
1190 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1191 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1192 }
1193 if (p < e and written == 0) {
1194 // if we have more to write, but that the target process hasn't consumed it yet - don't spin trying to
1195 // send it data - back off a little
1196 Sleep (100ms);
1197 }
1198#if 0
1199 // Do timeout handling at a higher level
1200 if (Time::GetTickCount () > timeoutAt) {
1201 DbgTrace (_T ("process timed out (writing initial data) - so throwing up!"));
1202 // then we've timed out - kill the process and DON'T return the partial result!
1203 (void)::TerminateProcess (processInfo.hProcess, -1); // if it exceeded the timeout - kill it (could already be done by now - in which case - this will be ignored - fine...
1204 Throw (Execution::Platform::Windows::Exception (ERROR_TIMEOUT));
1205 }
1206#endif
1207 }
1208 }
1209 }
1210
1211 // in case invoked sub-process is reading, and waiting for EOF before processing...
1212 useSTDIN.Close ();
1213 }
1214
1215 /*
1216 * Must keep reading while waiting - in case the child emits so much information that it
1217 * fills the OS PIPE buffer.
1218 */
1219 int timesWaited = 0;
1220 while (true) {
1221 /*
1222 * It would be nice to be able to WAIT on the PIPEs - but that doesn't appear to work when they
1223 * are in ASYNCRONOUS mode.
1224 *
1225 * So - instead - just wait a very short period, and then retry polling the pipes for more data.
1226 * -- LGP 2006-10-17
1227 */
1228 HANDLE events[1] = {processInfo.hProcess};
1229
1230 // We don't want to busy wait too much, but if its fast (with java, that's rare ;-)) don't want to wait
1231 // too long needlessly...
1232 //
1233 // Also - its not exactly a busy-wait. Its just a wait between reading stuff to avoid buffers filling. If the
1234 // process actually finishes, it will change state and the wait should return immediately.
1235 double remainingTimeout = (timesWaited <= 5) ? 0.1 : 0.5;
1236 DWORD waitResult = ::WaitForMultipleObjects (static_cast<DWORD> (std::size (events)), events, false,
1237 static_cast<int> (remainingTimeout * 1000));
1238 ++timesWaited;
1239
1240 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1241 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1242 switch (waitResult) {
1243 case WAIT_OBJECT_0: {
1244 DbgTrace ("external process finished (DONE)"_f);
1245 // timeoutAt = -1.0f; // force out of loop
1246 goto DoneWithProcess;
1247 } break;
1248 case WAIT_TIMEOUT: {
1249 DbgTrace ("still waiting for external process output (WAIT_TIMEOUT)"_f);
1250 }
1251 }
1252 }
1253
1254 DoneWithProcess:
1255 DWORD processExitCode{};
1256 Verify (::GetExitCodeProcess (processInfo.hProcess, &processExitCode));
1257
1258 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1259 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1260
1261 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDOUT, out);
1262 readAnyAvailableAndCopy2StreamWithoutBlocking (useSTDERR, err);
1263
1264 if (processResult == nullptr) {
1265 if (processExitCode != 0) {
1266 Throw (ProcessRunner::Exception{"Child process failed"sv, nullopt, processExitCode});
1267 }
1268 }
1269 else {
1270 processResult->store (ProcessRunner::ProcessResultType{static_cast<int> (processExitCode)});
1271 }
1272 }
1273 }
1274 catch (...) {
1275 // sadly and confusingly, CreateProcess() appears to set processInfo.hProcess and processInfo.hThread to nullptr - at least on some failures
1276 if (processInfo.hProcess != INVALID_HANDLE_VALUE and processInfo.hProcess != nullptr) {
1277 (void)::TerminateProcess (processInfo.hProcess, static_cast<UINT> (-1)); // if it exceeded the timeout - kill it
1278 SAFE_HANDLE_CLOSER_ (&processInfo.hProcess);
1279 SAFE_HANDLE_CLOSER_ (&processInfo.hThread);
1280 }
1281 ReThrow ();
1282 }
1283 }
1284}
1285#endif
1286
1287function<void ()> ProcessRunner::CreateRunnable_ (Synchronized<optional<ProcessResultType>>* processResult,
1288 Synchronized<optional<pid_t>>* runningPID, ProgressMonitor::Updater progress)
1289{
1290#if USE_NOISY_TRACE_IN_THIS_MODULE_
1291 TraceContextBumper ctx{"ProcessRunner::CreateRunnable_"};
1292#endif
1293 AssertExternallySynchronizedMutex::ReadContext declareContext{fThisAssertExternallySynchronized_};
1294 return [processResult, runningPID, progress, exe = this->fExecutable_, cmdLine = this->fArgs_, options = fOptions_, in = fStdIn_,
1295 out = fStdOut_, err = fStdErr_] () {
1296#if USE_NOISY_TRACE_IN_THIS_MODULE_
1297 TraceContextBumper ctx{"ProcessRunner::CreateRunnable_::{}::Runner..."};
1298#endif
1299 auto activity = LazyEvalActivity{[&] () { return "executing '{}'"_f(cmdLine); }};
1300 DeclareActivity currentActivity{&activity};
1301#if qStroika_Foundation_Common_Platform_POSIX
1302 Process_Runner_POSIX_ (processResult, runningPID, progress, exe, cmdLine, options, in, out, err);
1303#elif qStroika_Foundation_Common_Platform_Windows
1304 Process_Runner_Windows_ (processResult, runningPID, progress, exe, cmdLine, options, in, out, err);
1305#endif
1306 };
1307}
#define AssertNotNull(p)
Definition Assertions.h:333
#define AssertNotImplemented()
Definition Assertions.h:401
#define RequireNotNull(p)
Definition Assertions.h:347
#define AssertNotReached()
Definition Assertions.h:355
#define Verify(c)
Definition Assertions.h:419
auto MakeSharedPtr(ARGS_TYPE &&... args) -> shared_ptr< T >
same as make_shared, but if type T has block allocation, then use block allocation for the 'shared pa...
time_point< RealtimeClock, DurationSeconds > TimePointSeconds
TimePointSeconds is a simpler approach to chrono::time_point, which doesn't require using templates e...
Definition Realtime.h:82
chrono::duration< double > DurationSeconds
chrono::duration<double> - a time span (length of time) measured in seconds, but high precision.
Definition Realtime.h:57
InlineBuffer< T, BUF_SIZE > StackBuffer
Store variable sized (BUF_SIZE elements) array on the stack (.
Definition StackBuffer.h:59
#define DbgTrace
Definition Trace.h:309
#define Stroika_Foundation_Debug_OptionalizeTraceArgs(...)
Definition Trace.h:270
Similar to String, but intended to more efficiently construct a String. Mutable type (String is large...
String is like std::u32string, except it is much easier to use, often much more space efficient,...
Definition String.h:201
nonvirtual String LimitLength(size_t maxLen, StringShorteningPreference keepPref=StringShorteningPreference::ePreferKeepLeft) const
return the first maxLen (or fewer if string shorter) characters of this string (adding ellipsis if tr...
Definition String.inl:745
static String FromNarrowSDKString(const char *from)
Definition String.inl:470
nonvirtual SDKString AsSDKString() const
Definition String.inl:806
static String FromLatin1(const CHAR_T *cString)
Definition String.inl:355
nonvirtual bool Add(ArgByValueType< key_type > key, ArgByValueType< mapped_type > newElt, AddReplaceMode addReplaceMode=AddReplaceMode::eAddReplaces)
Definition Mapping.inl:188
A generalization of a vector: a container whose elements are keyed by the natural numbers.
shared_lock< const AssertExternallySynchronizedMutex > ReadContext
Instantiate AssertExternallySynchronizedMutex::ReadContext to designate an area of code where protect...
unique_lock< AssertExternallySynchronizedMutex > WriteContext
Instantiate AssertExternallySynchronizedMutex::WriteContext to designate an area of code where protec...
nonvirtual Sequence< String > GetArguments() const
nonvirtual T As(ARGS... args) const
Exception<> is a replacement (subclass) for any std c++ exception class (e.g. the default 'std::excep...
Definition Exceptions.h:157
NestedException contains a new higher level error message (typically based on argument basedOnExcepti...
Definition Exceptions.h:212
nonvirtual void WaitForStarted(Time::DurationSeconds timeout=Time::kInfinity) const
wait until GetChildProcessID () returns a valid answer, or until the process failed to start (in whic...
nonvirtual optional< ProcessResultType > GetProcessResult() const
nonvirtual void WaitForDone(Time::DurationSeconds timeout=Time::kInfinity) const
nonvirtual void Join(Time::DurationSeconds timeout=Time::kInfinity) const
Join () does WaitForDone () and throw exception if there was any error (see PropagateIfException).
nonvirtual void JoinUntil(Time::TimePointSeconds timeoutAt) const
WaitForDoneUntil () and throw exception if there was any error (see PropagateIfException).
Run the given command, and optionally support stdin/stdout/stderr as streams (either sync with Run,...
nonvirtual void Run(const Streams::InputStream::Ptr< byte > &in, const Streams::OutputStream::Ptr< byte > &out=nullptr, const Streams::OutputStream::Ptr< byte > &error=nullptr, ProgressMonitor::Updater progress=nullptr, Time::DurationSeconds timeout=Time::kInfinity)
Run the given external command/process (set by constructor) - with the given arguments,...
nonvirtual BackgroundProcess RunInBackground(const Streams::InputStream::Ptr< byte > &in=nullptr, const Streams::OutputStream::Ptr< byte > &out=nullptr, const Streams::OutputStream::Ptr< byte > &error=nullptr, ProgressMonitor::Updater progress=nullptr)
Run the given external command/process (set by constructor) - with the given arguments in the backgro...
ProcessRunner()=delete
Construct ProcessRunner with a CommandLine to run (doesn't actually RUN til you call Run or RunInBack...
Wrap any object with Synchronized<> and it can be used similarly to the base type,...
Thread::Ptr is a (unsynchronized) smart pointer referencing an internally synchronized std::thread ob...
Definition Thread.h:334
nonvirtual void Join(Time::DurationSeconds timeout=Time::kInfinity) const
Wait for the pointed-to thread to be done. If the thread completed with an exception (other than thre...
Definition Thread.inl:276
nonvirtual void WaitForDone(Time::DurationSeconds timeout=Time::kInfinity) const
Definition Thread.inl:286
nonvirtual void JoinUntil(Time::TimePointSeconds timeoutAt) const
Wait for the pointed-to thread to be done. If the thread completed with an exception (other than thre...
Definition Thread.inl:280
Logically halfway between std::array and std::vector; Smart 'direct memory array' - which when needed...
InputStream<>::Ptr is Smart pointer (with abstract Rep) class defining the interface to reading from ...
nonvirtual optional< ElementType > ReadBlocking() const
ReadBlocking () reads either a single element, or fills in argument intoBuffer - but never blocks (no...
nonvirtual optional< span< ElementType > > ReadNonBlocking(span< ElementType > intoBuffer) const
read into intoBuffer - returning nullopt if would block, and else returning subspan of input with rea...
OutputStream<>::Ptr is Smart pointer to a stream-based sink of data.
Iterable<T> is a base class for containers which easily produce an Iterator<T> to traverse them.
Definition Iterable.h:237
nonvirtual RESULT_T Join(const CONVERT_TO_RESULT &convertToResult=kDefaultToStringConverter<>, const COMBINER &combiner=Characters::kDefaultStringCombiner) const
ape the JavaScript/python 'join' function - take the parts of 'this' iterable and combine them into a...
nonvirtual Iterator< T > begin() const
Support for ranged for, and STL syntax in general.
basic_string< SDKChar > SDKString
Definition SDKString.h:38
Ptr New(const function< void()> &fun2CallOnce, const optional< Characters::String > &name, const optional< Configuration > &configuration)
Definition Thread.cpp:959
void Sleep(Time::Duration seconds2Wait)
Definition Sleep.cpp:18
void Throw(T &&e2Throw)
identical to builtin C++ 'throw' except that it does helpful, type dependent DbgTrace() messages firs...
Definition Throw.inl:43
const LazyInitialized< Containers::Sequence< filesystem::path > > kPath
Definition Module.cpp:144
EXPECTED::value_type ThrowIfFailed(const EXPECTED &e)
Definition Throw.inl:158
void ThrowPOSIXErrNo(errno_t errNo=errno)
treats errNo as a POSIX errno value, and throws a SystemError (subclass of @std::system_error) except...
auto Handle_ErrNoResultInterruption(CALL call) -> decltype(call())
Handle UNIX EINTR system call behavior - fairly transparently - just effectively removes them from th...
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
Definition Finally.inl:31
const LazyInitialized< Containers::Mapping< Characters::SDKString, Characters::SDKString > > kRawEnvironment
convert getenv() to a Mapping of SDKString (in case some issue with charactor set conversion)
Definition Module.cpp:180
optional< filesystem::path > FindExecutableInPath(const filesystem::path &fn)
If fn refers to an executable - return it (using kPATH, and kPathEXT as appropriate)
Definition Module.cpp:245
int pid_t
TODO - maybe move this to configuraiotn module???
Definition Module.h:34
INT_TYPE ThrowPOSIXErrNoIfNegative(INT_TYPE returnCode)
Ptr New(const InputStream::Ptr< byte > &src, optional< AutomaticCodeCvtFlags > codeCvtFlags={}, optional< SeekableFlag > seekable={}, ReadAhead readAhead=eReadAheadAllowed)
Create an InputStream::Ptr<Character> from the arguments (usually binary source) - which can be used ...
Ptr New(const Streams::OutputStream::Ptr< byte > &src, const Characters::CodeCvt<> &char2OutputConverter)