1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
9 #include <cmext/algorithm>
11 #include "cmsys/Process.h"
14 #include "cmCTestRunTest.h"
15 #include "cmCTestTestHandler.h"
16 #include "cmGetPipes.h"
17 #include "cmStringAlgorithms.h"
19 # include "cm_kwiml.h"
23 #define CM_PROCESS_BUF_SIZE 65536
25 cmProcess::cmProcess(cmCTestRunTest& runner)
27 , Conv(cmProcessOutput::UTF8, CM_PROCESS_BUF_SIZE)
29 this->Timeout = cmDuration::zero();
30 this->TotalTime = cmDuration::zero();
33 this->StartTime = std::chrono::steady_clock::time_point();
36 cmProcess::~cmProcess() = default;
38 void cmProcess::SetCommand(std::string const& command)
40 this->Command = command;
43 void cmProcess::SetCommandArguments(std::vector<std::string> const& args)
45 this->Arguments = args;
48 void cmProcess::SetWorkingDirectory(std::string const& dir)
50 this->WorkingDirectory = dir;
53 bool cmProcess::StartProcess(uv_loop_t& loop, std::vector<size_t>* affinity)
55 this->ProcessState = cmProcess::State::Error;
56 if (this->Command.empty()) {
59 this->StartTime = std::chrono::steady_clock::now();
60 this->ProcessArgs.clear();
61 // put the command as arg0
62 this->ProcessArgs.push_back(this->Command.c_str());
63 // now put the command arguments in
64 for (std::string const& arg : this->Arguments) {
65 this->ProcessArgs.push_back(arg.c_str());
67 this->ProcessArgs.push_back(nullptr); // null terminate the list
69 cm::uv_timer_ptr timer;
70 int status = timer.init(loop, this);
72 cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
73 "Error initializing timer: " << uv_strerror(status)
78 cm::uv_pipe_ptr pipe_writer;
79 cm::uv_pipe_ptr pipe_reader;
81 pipe_writer.init(loop, 0);
82 pipe_reader.init(loop, 0, this);
84 int fds[2] = { -1, -1 };
85 status = cmGetPipes(fds);
87 cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
88 "Error initializing pipe: " << uv_strerror(status)
93 uv_pipe_open(pipe_reader, fds[0]);
94 uv_pipe_open(pipe_writer, fds[1]);
96 uv_stdio_container_t stdio[3];
97 stdio[0].flags = UV_INHERIT_FD;
99 stdio[1].flags = UV_INHERIT_STREAM;
100 stdio[1].data.stream = pipe_writer;
103 uv_process_options_t options = uv_process_options_t();
104 options.file = this->Command.data();
105 options.args = const_cast<char**>(this->ProcessArgs.data());
106 options.stdio_count = 3; // in, out and err
107 options.exit_cb = &cmProcess::OnExitCB;
108 options.stdio = stdio;
109 #if !defined(CMAKE_USE_SYSTEM_LIBUV)
110 std::vector<char> cpumask;
111 if (affinity && !affinity->empty()) {
112 cpumask.resize(static_cast<size_t>(uv_cpumask_size()), 0);
113 for (auto p : *affinity) {
116 options.cpumask = cpumask.data();
117 options.cpumask_size = cpumask.size();
119 options.cpumask = nullptr;
120 options.cpumask_size = 0;
123 static_cast<void>(affinity);
127 uv_read_start(pipe_reader, &cmProcess::OnAllocateCB, &cmProcess::OnReadCB);
130 cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
131 "Error starting read events: " << uv_strerror(status)
136 status = this->Process.spawn(loop, options, this);
138 cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
139 "Process not started\n " << this->Command << "\n["
140 << uv_strerror(status) << "]\n");
144 this->PipeReader = std::move(pipe_reader);
145 this->Timer = std::move(timer);
149 this->ProcessState = cmProcess::State::Executing;
153 void cmProcess::StartTimer()
155 auto properties = this->Runner.GetTestProperties();
157 std::chrono::duration_cast<std::chrono::milliseconds>(this->Timeout);
159 if (msec != std::chrono::milliseconds(0) || !properties->ExplicitTimeout) {
160 this->Timer.start(&cmProcess::OnTimeoutCB,
161 static_cast<uint64_t>(msec.count()), 0);
165 bool cmProcess::Buffer::GetLine(std::string& line)
167 // Scan for the next newline.
168 for (size_type sz = this->size(); this->Last != sz; ++this->Last) {
169 if ((*this)[this->Last] == '\n' || (*this)[this->Last] == '\0') {
170 // Extract the range first..last as a line.
171 const char* text = this->data() + this->First;
172 size_type length = this->Last - this->First;
173 while (length && text[length - 1] == '\r') {
176 line.assign(text, length);
178 // Start a new range for the next line.
182 // Return the line extracted.
187 // Available data have been exhausted without a newline.
188 if (this->First != 0) {
189 // Move the partial line to the beginning of the buffer.
190 this->erase(this->begin(), this->begin() + this->First);
192 this->Last = this->size();
197 bool cmProcess::Buffer::GetLast(std::string& line)
199 // Return the partial last line, if any.
200 if (!this->empty()) {
201 line.assign(this->data(), this->size());
202 this->First = this->Last = 0;
209 void cmProcess::OnReadCB(uv_stream_t* stream, ssize_t nread,
212 auto self = static_cast<cmProcess*>(stream->data);
213 self->OnRead(nread, buf);
216 void cmProcess::OnRead(ssize_t nread, const uv_buf_t* buf)
221 this->Conv.DecodeText(buf->base, static_cast<size_t>(nread), strdata);
222 cm::append(this->Output, strdata);
224 while (this->Output.GetLine(line)) {
225 this->Runner.CheckOutput(line);
236 // The process will provide no more data.
237 if (nread != UV_EOF) {
238 auto error = static_cast<int>(nread);
239 cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
240 "Error reading stream: " << uv_strerror(error) << std::endl);
243 // Look for partial last lines.
244 if (this->Output.GetLast(line)) {
245 this->Runner.CheckOutput(line);
248 this->ReadHandleClosed = true;
249 this->PipeReader.reset();
250 if (this->ProcessHandleClosed) {
251 uv_timer_stop(this->Timer);
256 void cmProcess::OnAllocateCB(uv_handle_t* handle, size_t suggested_size,
259 auto self = static_cast<cmProcess*>(handle->data);
260 self->OnAllocate(suggested_size, buf);
263 void cmProcess::OnAllocate(size_t /*suggested_size*/, uv_buf_t* buf)
265 if (this->Buf.size() != CM_PROCESS_BUF_SIZE) {
266 this->Buf.resize(CM_PROCESS_BUF_SIZE);
270 uv_buf_init(this->Buf.data(), static_cast<unsigned int>(this->Buf.size()));
273 void cmProcess::OnTimeoutCB(uv_timer_t* timer)
275 auto self = static_cast<cmProcess*>(timer->data);
279 void cmProcess::OnTimeout()
281 this->ProcessState = cmProcess::State::Expired;
282 bool const was_still_reading = !this->ReadHandleClosed;
283 if (!this->ReadHandleClosed) {
284 this->ReadHandleClosed = true;
285 this->PipeReader.reset();
287 if (!this->ProcessHandleClosed) {
288 // Kill the child and let our on-exit handler finish the test.
289 cmsysProcess_KillPID(static_cast<unsigned long>(this->Process->pid));
290 } else if (was_still_reading) {
291 // Our on-exit handler already ran but did not finish the test
292 // because we were still reading output. We've just dropped
293 // our read handler, so we need to finish the test now.
298 void cmProcess::OnExitCB(uv_process_t* process, int64_t exit_status,
301 auto self = static_cast<cmProcess*>(process->data);
302 self->OnExit(exit_status, term_signal);
305 void cmProcess::OnExit(int64_t exit_status, int term_signal)
307 if (this->ProcessState != cmProcess::State::Expired) {
310 ((DWORD)exit_status & 0xF0000000) == 0xC0000000
315 this->ProcessState = cmProcess::State::Exception;
317 this->ProcessState = cmProcess::State::Exited;
321 // Record exit information.
322 this->ExitValue = exit_status;
323 this->Signal = term_signal;
325 this->ProcessHandleClosed = true;
326 if (this->ReadHandleClosed) {
327 uv_timer_stop(this->Timer);
332 void cmProcess::Finish()
334 this->TotalTime = std::chrono::steady_clock::now() - this->StartTime;
335 // Because of a processor clock scew the runtime may become slightly
336 // negative. If someone changed the system clock while the process was
337 // running this may be even more. Make sure not to report a negative
339 if (this->TotalTime <= cmDuration::zero()) {
340 this->TotalTime = cmDuration::zero();
342 this->Runner.FinalizeTest();
345 cmProcess::State cmProcess::GetProcessStatus()
347 return this->ProcessState;
350 void cmProcess::ChangeTimeout(cmDuration t)
356 void cmProcess::ResetStartTime()
358 this->StartTime = std::chrono::steady_clock::now();
361 cmProcess::Exception cmProcess::GetExitException()
363 auto exception = Exception::None;
364 #if defined(_WIN32) && !defined(__CYGWIN__)
365 auto exit_code = (DWORD)this->ExitValue;
366 if ((exit_code & 0xF0000000) != 0xC0000000) {
372 case STATUS_DATATYPE_MISALIGNMENT:
373 case STATUS_ACCESS_VIOLATION:
374 case STATUS_IN_PAGE_ERROR:
375 case STATUS_INVALID_HANDLE:
376 case STATUS_NONCONTINUABLE_EXCEPTION:
377 case STATUS_INVALID_DISPOSITION:
378 case STATUS_ARRAY_BOUNDS_EXCEEDED:
379 case STATUS_STACK_OVERFLOW:
380 exception = Exception::Fault;
382 case STATUS_FLOAT_DENORMAL_OPERAND:
383 case STATUS_FLOAT_DIVIDE_BY_ZERO:
384 case STATUS_FLOAT_INEXACT_RESULT:
385 case STATUS_FLOAT_INVALID_OPERATION:
386 case STATUS_FLOAT_OVERFLOW:
387 case STATUS_FLOAT_STACK_CHECK:
388 case STATUS_FLOAT_UNDERFLOW:
389 # ifdef STATUS_FLOAT_MULTIPLE_FAULTS
390 case STATUS_FLOAT_MULTIPLE_FAULTS:
392 # ifdef STATUS_FLOAT_MULTIPLE_TRAPS
393 case STATUS_FLOAT_MULTIPLE_TRAPS:
395 case STATUS_INTEGER_DIVIDE_BY_ZERO:
396 case STATUS_INTEGER_OVERFLOW:
397 exception = Exception::Numerical;
399 case STATUS_CONTROL_C_EXIT:
400 exception = Exception::Interrupt;
402 case STATUS_ILLEGAL_INSTRUCTION:
403 case STATUS_PRIVILEGED_INSTRUCTION:
404 exception = Exception::Illegal;
407 exception = Exception::Other;
412 switch (this->Signal) {
414 exception = Exception::Fault;
417 exception = Exception::Numerical;
420 exception = Exception::Interrupt;
423 exception = Exception::Illegal;
426 exception = Exception::Other;
433 std::string cmProcess::GetExitExceptionString()
435 std::string exception_str;
437 switch (this->ExitValue) {
438 case STATUS_CONTROL_C_EXIT:
439 exception_str = "User interrupt";
441 case STATUS_FLOAT_DENORMAL_OPERAND:
442 exception_str = "Floating-point exception (denormal operand)";
444 case STATUS_FLOAT_DIVIDE_BY_ZERO:
445 exception_str = "Divide-by-zero";
447 case STATUS_FLOAT_INEXACT_RESULT:
448 exception_str = "Floating-point exception (inexact result)";
450 case STATUS_FLOAT_INVALID_OPERATION:
451 exception_str = "Invalid floating-point operation";
453 case STATUS_FLOAT_OVERFLOW:
454 exception_str = "Floating-point overflow";
456 case STATUS_FLOAT_STACK_CHECK:
457 exception_str = "Floating-point stack check failed";
459 case STATUS_FLOAT_UNDERFLOW:
460 exception_str = "Floating-point underflow";
462 # ifdef STATUS_FLOAT_MULTIPLE_FAULTS
463 case STATUS_FLOAT_MULTIPLE_FAULTS:
464 exception_str = "Floating-point exception (multiple faults)";
467 # ifdef STATUS_FLOAT_MULTIPLE_TRAPS
468 case STATUS_FLOAT_MULTIPLE_TRAPS:
469 exception_str = "Floating-point exception (multiple traps)";
472 case STATUS_INTEGER_DIVIDE_BY_ZERO:
473 exception_str = "Integer divide-by-zero";
475 case STATUS_INTEGER_OVERFLOW:
476 exception_str = "Integer overflow";
479 case STATUS_DATATYPE_MISALIGNMENT:
480 exception_str = "Datatype misalignment";
482 case STATUS_ACCESS_VIOLATION:
483 exception_str = "Access violation";
485 case STATUS_IN_PAGE_ERROR:
486 exception_str = "In-page error";
488 case STATUS_INVALID_HANDLE:
489 exception_str = "Invalid handle";
491 case STATUS_NONCONTINUABLE_EXCEPTION:
492 exception_str = "Noncontinuable exception";
494 case STATUS_INVALID_DISPOSITION:
495 exception_str = "Invalid disposition";
497 case STATUS_ARRAY_BOUNDS_EXCEEDED:
498 exception_str = "Array bounds exceeded";
500 case STATUS_STACK_OVERFLOW:
501 exception_str = "Stack overflow";
504 case STATUS_ILLEGAL_INSTRUCTION:
505 exception_str = "Illegal instruction";
507 case STATUS_PRIVILEGED_INSTRUCTION:
508 exception_str = "Privileged instruction";
510 case STATUS_NO_MEMORY:
513 const char* fmt = "Exit code 0x%" KWIML_INT_PRIx64 "\n";
514 _snprintf(buf, 1024, fmt, this->ExitValue);
515 exception_str.assign(buf);
518 switch (this->Signal) {
521 exception_str = "Segmentation fault";
525 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
527 exception_str = "Bus error";
533 exception_str = "Floating-point exception";
538 exception_str = "Illegal instruction";
543 exception_str = "User interrupt";
548 exception_str = "Child aborted";
553 exception_str = "Child killed";
558 exception_str = "Child terminated";
563 exception_str = "SIGHUP";
568 exception_str = "SIGQUIT";
573 exception_str = "SIGTRAP";
577 # if !defined(SIGABRT) || SIGIOT != SIGABRT
579 exception_str = "SIGIOT";
585 exception_str = "SIGUSR1";
590 exception_str = "SIGUSR2";
595 exception_str = "SIGPIPE";
600 exception_str = "SIGALRM";
605 exception_str = "SIGSTKFLT";
610 exception_str = "SIGCHLD";
612 # elif defined(SIGCLD)
614 exception_str = "SIGCLD";
619 exception_str = "SIGCONT";
624 exception_str = "SIGSTOP";
629 exception_str = "SIGTSTP";
634 exception_str = "SIGTTIN";
639 exception_str = "SIGTTOU";
644 exception_str = "SIGURG";
649 exception_str = "SIGXCPU";
654 exception_str = "SIGXFSZ";
659 exception_str = "SIGVTALRM";
664 exception_str = "SIGPROF";
669 exception_str = "SIGWINCH";
674 exception_str = "SIGPOLL";
678 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
680 exception_str = "SIGIO";
686 exception_str = "SIGPWR";
691 exception_str = "SIGSYS";
695 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
697 exception_str = "SIGUNUSED";
702 exception_str = cmStrCat("Signal ", this->Signal);
705 return exception_str;