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);
252 this->Runner.FinalizeTest();
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.
294 this->Runner.FinalizeTest();
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;
324 this->TotalTime = std::chrono::steady_clock::now() - this->StartTime;
325 // Because of a processor clock scew the runtime may become slightly
326 // negative. If someone changed the system clock while the process was
327 // running this may be even more. Make sure not to report a negative
329 if (this->TotalTime <= cmDuration::zero()) {
330 this->TotalTime = cmDuration::zero();
333 this->ProcessHandleClosed = true;
334 if (this->ReadHandleClosed) {
335 uv_timer_stop(this->Timer);
336 this->Runner.FinalizeTest();
340 cmProcess::State cmProcess::GetProcessStatus()
342 return this->ProcessState;
345 void cmProcess::ChangeTimeout(cmDuration t)
351 void cmProcess::ResetStartTime()
353 this->StartTime = std::chrono::steady_clock::now();
356 cmProcess::Exception cmProcess::GetExitException()
358 auto exception = Exception::None;
359 #if defined(_WIN32) && !defined(__CYGWIN__)
360 auto exit_code = (DWORD)this->ExitValue;
361 if ((exit_code & 0xF0000000) != 0xC0000000) {
367 case STATUS_DATATYPE_MISALIGNMENT:
368 case STATUS_ACCESS_VIOLATION:
369 case STATUS_IN_PAGE_ERROR:
370 case STATUS_INVALID_HANDLE:
371 case STATUS_NONCONTINUABLE_EXCEPTION:
372 case STATUS_INVALID_DISPOSITION:
373 case STATUS_ARRAY_BOUNDS_EXCEEDED:
374 case STATUS_STACK_OVERFLOW:
375 exception = Exception::Fault;
377 case STATUS_FLOAT_DENORMAL_OPERAND:
378 case STATUS_FLOAT_DIVIDE_BY_ZERO:
379 case STATUS_FLOAT_INEXACT_RESULT:
380 case STATUS_FLOAT_INVALID_OPERATION:
381 case STATUS_FLOAT_OVERFLOW:
382 case STATUS_FLOAT_STACK_CHECK:
383 case STATUS_FLOAT_UNDERFLOW:
384 # ifdef STATUS_FLOAT_MULTIPLE_FAULTS
385 case STATUS_FLOAT_MULTIPLE_FAULTS:
387 # ifdef STATUS_FLOAT_MULTIPLE_TRAPS
388 case STATUS_FLOAT_MULTIPLE_TRAPS:
390 case STATUS_INTEGER_DIVIDE_BY_ZERO:
391 case STATUS_INTEGER_OVERFLOW:
392 exception = Exception::Numerical;
394 case STATUS_CONTROL_C_EXIT:
395 exception = Exception::Interrupt;
397 case STATUS_ILLEGAL_INSTRUCTION:
398 case STATUS_PRIVILEGED_INSTRUCTION:
399 exception = Exception::Illegal;
402 exception = Exception::Other;
407 switch (this->Signal) {
409 exception = Exception::Fault;
412 exception = Exception::Numerical;
415 exception = Exception::Interrupt;
418 exception = Exception::Illegal;
421 exception = Exception::Other;
428 std::string cmProcess::GetExitExceptionString()
430 std::string exception_str;
432 switch (this->ExitValue) {
433 case STATUS_CONTROL_C_EXIT:
434 exception_str = "User interrupt";
436 case STATUS_FLOAT_DENORMAL_OPERAND:
437 exception_str = "Floating-point exception (denormal operand)";
439 case STATUS_FLOAT_DIVIDE_BY_ZERO:
440 exception_str = "Divide-by-zero";
442 case STATUS_FLOAT_INEXACT_RESULT:
443 exception_str = "Floating-point exception (inexact result)";
445 case STATUS_FLOAT_INVALID_OPERATION:
446 exception_str = "Invalid floating-point operation";
448 case STATUS_FLOAT_OVERFLOW:
449 exception_str = "Floating-point overflow";
451 case STATUS_FLOAT_STACK_CHECK:
452 exception_str = "Floating-point stack check failed";
454 case STATUS_FLOAT_UNDERFLOW:
455 exception_str = "Floating-point underflow";
457 # ifdef STATUS_FLOAT_MULTIPLE_FAULTS
458 case STATUS_FLOAT_MULTIPLE_FAULTS:
459 exception_str = "Floating-point exception (multiple faults)";
462 # ifdef STATUS_FLOAT_MULTIPLE_TRAPS
463 case STATUS_FLOAT_MULTIPLE_TRAPS:
464 exception_str = "Floating-point exception (multiple traps)";
467 case STATUS_INTEGER_DIVIDE_BY_ZERO:
468 exception_str = "Integer divide-by-zero";
470 case STATUS_INTEGER_OVERFLOW:
471 exception_str = "Integer overflow";
474 case STATUS_DATATYPE_MISALIGNMENT:
475 exception_str = "Datatype misalignment";
477 case STATUS_ACCESS_VIOLATION:
478 exception_str = "Access violation";
480 case STATUS_IN_PAGE_ERROR:
481 exception_str = "In-page error";
483 case STATUS_INVALID_HANDLE:
484 exception_str = "Invalid handle";
486 case STATUS_NONCONTINUABLE_EXCEPTION:
487 exception_str = "Noncontinuable exception";
489 case STATUS_INVALID_DISPOSITION:
490 exception_str = "Invalid disposition";
492 case STATUS_ARRAY_BOUNDS_EXCEEDED:
493 exception_str = "Array bounds exceeded";
495 case STATUS_STACK_OVERFLOW:
496 exception_str = "Stack overflow";
499 case STATUS_ILLEGAL_INSTRUCTION:
500 exception_str = "Illegal instruction";
502 case STATUS_PRIVILEGED_INSTRUCTION:
503 exception_str = "Privileged instruction";
505 case STATUS_NO_MEMORY:
508 const char* fmt = "Exit code 0x%" KWIML_INT_PRIx64 "\n";
509 _snprintf(buf, 1024, fmt, this->ExitValue);
510 exception_str.assign(buf);
513 switch (this->Signal) {
516 exception_str = "Segmentation fault";
520 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
522 exception_str = "Bus error";
528 exception_str = "Floating-point exception";
533 exception_str = "Illegal instruction";
538 exception_str = "User interrupt";
543 exception_str = "Child aborted";
548 exception_str = "Child killed";
553 exception_str = "Child terminated";
558 exception_str = "SIGHUP";
563 exception_str = "SIGQUIT";
568 exception_str = "SIGTRAP";
572 # if !defined(SIGABRT) || SIGIOT != SIGABRT
574 exception_str = "SIGIOT";
580 exception_str = "SIGUSR1";
585 exception_str = "SIGUSR2";
590 exception_str = "SIGPIPE";
595 exception_str = "SIGALRM";
600 exception_str = "SIGSTKFLT";
605 exception_str = "SIGCHLD";
607 # elif defined(SIGCLD)
609 exception_str = "SIGCLD";
614 exception_str = "SIGCONT";
619 exception_str = "SIGSTOP";
624 exception_str = "SIGTSTP";
629 exception_str = "SIGTTIN";
634 exception_str = "SIGTTOU";
639 exception_str = "SIGURG";
644 exception_str = "SIGXCPU";
649 exception_str = "SIGXFSZ";
654 exception_str = "SIGVTALRM";
659 exception_str = "SIGPROF";
664 exception_str = "SIGWINCH";
669 exception_str = "SIGPOLL";
673 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
675 exception_str = "SIGIO";
681 exception_str = "SIGPWR";
686 exception_str = "SIGSYS";
690 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
692 exception_str = "SIGUNUSED";
697 exception_str = cmStrCat("Signal ", this->Signal);
700 return exception_str;