cdf899c497e5d0c49e940152ab72b3091744c623
[platform/upstream/cmake.git] / Source / CTest / cmProcess.cxx
1 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2    file Copyright.txt or https://cmake.org/licensing for details.  */
3 #include "cmProcess.h"
4
5 #include <csignal>
6 #include <iostream>
7 #include <string>
8
9 #include <cmext/algorithm>
10
11 #include "cmsys/Process.h"
12
13 #include "cmCTest.h"
14 #include "cmCTestRunTest.h"
15 #include "cmCTestTestHandler.h"
16 #include "cmGetPipes.h"
17 #include "cmStringAlgorithms.h"
18 #if defined(_WIN32)
19 #  include "cm_kwiml.h"
20 #endif
21 #include <utility>
22
23 #define CM_PROCESS_BUF_SIZE 65536
24
25 cmProcess::cmProcess(cmCTestRunTest& runner)
26   : Runner(runner)
27   , Conv(cmProcessOutput::UTF8, CM_PROCESS_BUF_SIZE)
28 {
29   this->Timeout = cmDuration::zero();
30   this->TotalTime = cmDuration::zero();
31   this->ExitValue = 0;
32   this->Id = 0;
33   this->StartTime = std::chrono::steady_clock::time_point();
34 }
35
36 cmProcess::~cmProcess() = default;
37
38 void cmProcess::SetCommand(std::string const& command)
39 {
40   this->Command = command;
41 }
42
43 void cmProcess::SetCommandArguments(std::vector<std::string> const& args)
44 {
45   this->Arguments = args;
46 }
47
48 void cmProcess::SetWorkingDirectory(std::string const& dir)
49 {
50   this->WorkingDirectory = dir;
51 }
52
53 bool cmProcess::StartProcess(uv_loop_t& loop, std::vector<size_t>* affinity)
54 {
55   this->ProcessState = cmProcess::State::Error;
56   if (this->Command.empty()) {
57     return false;
58   }
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());
66   }
67   this->ProcessArgs.push_back(nullptr); // null terminate the list
68
69   cm::uv_timer_ptr timer;
70   int status = timer.init(loop, this);
71   if (status != 0) {
72     cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
73                "Error initializing timer: " << uv_strerror(status)
74                                             << std::endl);
75     return false;
76   }
77
78   cm::uv_pipe_ptr pipe_writer;
79   cm::uv_pipe_ptr pipe_reader;
80
81   pipe_writer.init(loop, 0);
82   pipe_reader.init(loop, 0, this);
83
84   int fds[2] = { -1, -1 };
85   status = cmGetPipes(fds);
86   if (status != 0) {
87     cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
88                "Error initializing pipe: " << uv_strerror(status)
89                                            << std::endl);
90     return false;
91   }
92
93   uv_pipe_open(pipe_reader, fds[0]);
94   uv_pipe_open(pipe_writer, fds[1]);
95
96   uv_stdio_container_t stdio[3];
97   stdio[0].flags = UV_INHERIT_FD;
98   stdio[0].data.fd = 0;
99   stdio[1].flags = UV_INHERIT_STREAM;
100   stdio[1].data.stream = pipe_writer;
101   stdio[2] = stdio[1];
102
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) {
114       cpumask[p] = 1;
115     }
116     options.cpumask = cpumask.data();
117     options.cpumask_size = cpumask.size();
118   } else {
119     options.cpumask = nullptr;
120     options.cpumask_size = 0;
121   }
122 #else
123   static_cast<void>(affinity);
124 #endif
125
126   status =
127     uv_read_start(pipe_reader, &cmProcess::OnAllocateCB, &cmProcess::OnReadCB);
128
129   if (status != 0) {
130     cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
131                "Error starting read events: " << uv_strerror(status)
132                                               << std::endl);
133     return false;
134   }
135
136   status = this->Process.spawn(loop, options, this);
137   if (status != 0) {
138     cmCTestLog(this->Runner.GetCTest(), ERROR_MESSAGE,
139                "Process not started\n " << this->Command << "\n["
140                                         << uv_strerror(status) << "]\n");
141     return false;
142   }
143
144   this->PipeReader = std::move(pipe_reader);
145   this->Timer = std::move(timer);
146
147   this->StartTimer();
148
149   this->ProcessState = cmProcess::State::Executing;
150   return true;
151 }
152
153 void cmProcess::StartTimer()
154 {
155   auto properties = this->Runner.GetTestProperties();
156   auto msec =
157     std::chrono::duration_cast<std::chrono::milliseconds>(this->Timeout);
158
159   if (msec != std::chrono::milliseconds(0) || !properties->ExplicitTimeout) {
160     this->Timer.start(&cmProcess::OnTimeoutCB,
161                       static_cast<uint64_t>(msec.count()), 0);
162   }
163 }
164
165 bool cmProcess::Buffer::GetLine(std::string& line)
166 {
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') {
174         length--;
175       }
176       line.assign(text, length);
177
178       // Start a new range for the next line.
179       ++this->Last;
180       this->First = Last;
181
182       // Return the line extracted.
183       return true;
184     }
185   }
186
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);
191     this->First = 0;
192     this->Last = this->size();
193   }
194   return false;
195 }
196
197 bool cmProcess::Buffer::GetLast(std::string& line)
198 {
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;
203     this->clear();
204     return true;
205   }
206   return false;
207 }
208
209 void cmProcess::OnReadCB(uv_stream_t* stream, ssize_t nread,
210                          const uv_buf_t* buf)
211 {
212   auto self = static_cast<cmProcess*>(stream->data);
213   self->OnRead(nread, buf);
214 }
215
216 void cmProcess::OnRead(ssize_t nread, const uv_buf_t* buf)
217 {
218   std::string line;
219   if (nread > 0) {
220     std::string strdata;
221     this->Conv.DecodeText(buf->base, static_cast<size_t>(nread), strdata);
222     cm::append(this->Output, strdata);
223
224     while (this->Output.GetLine(line)) {
225       this->Runner.CheckOutput(line);
226       line.clear();
227     }
228
229     return;
230   }
231
232   if (nread == 0) {
233     return;
234   }
235
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);
241   }
242
243   // Look for partial last lines.
244   if (this->Output.GetLast(line)) {
245     this->Runner.CheckOutput(line);
246   }
247
248   this->ReadHandleClosed = true;
249   this->PipeReader.reset();
250   if (this->ProcessHandleClosed) {
251     uv_timer_stop(this->Timer);
252     this->Runner.FinalizeTest();
253   }
254 }
255
256 void cmProcess::OnAllocateCB(uv_handle_t* handle, size_t suggested_size,
257                              uv_buf_t* buf)
258 {
259   auto self = static_cast<cmProcess*>(handle->data);
260   self->OnAllocate(suggested_size, buf);
261 }
262
263 void cmProcess::OnAllocate(size_t /*suggested_size*/, uv_buf_t* buf)
264 {
265   if (this->Buf.size() != CM_PROCESS_BUF_SIZE) {
266     this->Buf.resize(CM_PROCESS_BUF_SIZE);
267   }
268
269   *buf =
270     uv_buf_init(this->Buf.data(), static_cast<unsigned int>(this->Buf.size()));
271 }
272
273 void cmProcess::OnTimeoutCB(uv_timer_t* timer)
274 {
275   auto self = static_cast<cmProcess*>(timer->data);
276   self->OnTimeout();
277 }
278
279 void cmProcess::OnTimeout()
280 {
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();
286   }
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();
295   }
296 }
297
298 void cmProcess::OnExitCB(uv_process_t* process, int64_t exit_status,
299                          int term_signal)
300 {
301   auto self = static_cast<cmProcess*>(process->data);
302   self->OnExit(exit_status, term_signal);
303 }
304
305 void cmProcess::OnExit(int64_t exit_status, int term_signal)
306 {
307   if (this->ProcessState != cmProcess::State::Expired) {
308     if (
309 #if defined(_WIN32)
310       ((DWORD)exit_status & 0xF0000000) == 0xC0000000
311 #else
312       term_signal != 0
313 #endif
314     ) {
315       this->ProcessState = cmProcess::State::Exception;
316     } else {
317       this->ProcessState = cmProcess::State::Exited;
318     }
319   }
320
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
328   // duration here.
329   if (this->TotalTime <= cmDuration::zero()) {
330     this->TotalTime = cmDuration::zero();
331   }
332
333   this->ProcessHandleClosed = true;
334   if (this->ReadHandleClosed) {
335     uv_timer_stop(this->Timer);
336     this->Runner.FinalizeTest();
337   }
338 }
339
340 cmProcess::State cmProcess::GetProcessStatus()
341 {
342   return this->ProcessState;
343 }
344
345 void cmProcess::ChangeTimeout(cmDuration t)
346 {
347   this->Timeout = t;
348   this->StartTimer();
349 }
350
351 void cmProcess::ResetStartTime()
352 {
353   this->StartTime = std::chrono::steady_clock::now();
354 }
355
356 cmProcess::Exception cmProcess::GetExitException()
357 {
358   auto exception = Exception::None;
359 #if defined(_WIN32) && !defined(__CYGWIN__)
360   auto exit_code = (DWORD)this->ExitValue;
361   if ((exit_code & 0xF0000000) != 0xC0000000) {
362     return exception;
363   }
364
365   if (exit_code) {
366     switch (exit_code) {
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;
376         break;
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:
386 #  endif
387 #  ifdef STATUS_FLOAT_MULTIPLE_TRAPS
388       case STATUS_FLOAT_MULTIPLE_TRAPS:
389 #  endif
390       case STATUS_INTEGER_DIVIDE_BY_ZERO:
391       case STATUS_INTEGER_OVERFLOW:
392         exception = Exception::Numerical;
393         break;
394       case STATUS_CONTROL_C_EXIT:
395         exception = Exception::Interrupt;
396         break;
397       case STATUS_ILLEGAL_INSTRUCTION:
398       case STATUS_PRIVILEGED_INSTRUCTION:
399         exception = Exception::Illegal;
400         break;
401       default:
402         exception = Exception::Other;
403     }
404   }
405 #else
406   if (this->Signal) {
407     switch (this->Signal) {
408       case SIGSEGV:
409         exception = Exception::Fault;
410         break;
411       case SIGFPE:
412         exception = Exception::Numerical;
413         break;
414       case SIGINT:
415         exception = Exception::Interrupt;
416         break;
417       case SIGILL:
418         exception = Exception::Illegal;
419         break;
420       default:
421         exception = Exception::Other;
422     }
423   }
424 #endif
425   return exception;
426 }
427
428 std::string cmProcess::GetExitExceptionString()
429 {
430   std::string exception_str;
431 #if defined(_WIN32)
432   switch (this->ExitValue) {
433     case STATUS_CONTROL_C_EXIT:
434       exception_str = "User interrupt";
435       break;
436     case STATUS_FLOAT_DENORMAL_OPERAND:
437       exception_str = "Floating-point exception (denormal operand)";
438       break;
439     case STATUS_FLOAT_DIVIDE_BY_ZERO:
440       exception_str = "Divide-by-zero";
441       break;
442     case STATUS_FLOAT_INEXACT_RESULT:
443       exception_str = "Floating-point exception (inexact result)";
444       break;
445     case STATUS_FLOAT_INVALID_OPERATION:
446       exception_str = "Invalid floating-point operation";
447       break;
448     case STATUS_FLOAT_OVERFLOW:
449       exception_str = "Floating-point overflow";
450       break;
451     case STATUS_FLOAT_STACK_CHECK:
452       exception_str = "Floating-point stack check failed";
453       break;
454     case STATUS_FLOAT_UNDERFLOW:
455       exception_str = "Floating-point underflow";
456       break;
457 #  ifdef STATUS_FLOAT_MULTIPLE_FAULTS
458     case STATUS_FLOAT_MULTIPLE_FAULTS:
459       exception_str = "Floating-point exception (multiple faults)";
460       break;
461 #  endif
462 #  ifdef STATUS_FLOAT_MULTIPLE_TRAPS
463     case STATUS_FLOAT_MULTIPLE_TRAPS:
464       exception_str = "Floating-point exception (multiple traps)";
465       break;
466 #  endif
467     case STATUS_INTEGER_DIVIDE_BY_ZERO:
468       exception_str = "Integer divide-by-zero";
469       break;
470     case STATUS_INTEGER_OVERFLOW:
471       exception_str = "Integer overflow";
472       break;
473
474     case STATUS_DATATYPE_MISALIGNMENT:
475       exception_str = "Datatype misalignment";
476       break;
477     case STATUS_ACCESS_VIOLATION:
478       exception_str = "Access violation";
479       break;
480     case STATUS_IN_PAGE_ERROR:
481       exception_str = "In-page error";
482       break;
483     case STATUS_INVALID_HANDLE:
484       exception_str = "Invalid handle";
485       break;
486     case STATUS_NONCONTINUABLE_EXCEPTION:
487       exception_str = "Noncontinuable exception";
488       break;
489     case STATUS_INVALID_DISPOSITION:
490       exception_str = "Invalid disposition";
491       break;
492     case STATUS_ARRAY_BOUNDS_EXCEEDED:
493       exception_str = "Array bounds exceeded";
494       break;
495     case STATUS_STACK_OVERFLOW:
496       exception_str = "Stack overflow";
497       break;
498
499     case STATUS_ILLEGAL_INSTRUCTION:
500       exception_str = "Illegal instruction";
501       break;
502     case STATUS_PRIVILEGED_INSTRUCTION:
503       exception_str = "Privileged instruction";
504       break;
505     case STATUS_NO_MEMORY:
506     default:
507       char buf[1024];
508       const char* fmt = "Exit code 0x%" KWIML_INT_PRIx64 "\n";
509       _snprintf(buf, 1024, fmt, this->ExitValue);
510       exception_str.assign(buf);
511   }
512 #else
513   switch (this->Signal) {
514 #  ifdef SIGSEGV
515     case SIGSEGV:
516       exception_str = "Segmentation fault";
517       break;
518 #  endif
519 #  ifdef SIGBUS
520 #    if !defined(SIGSEGV) || SIGBUS != SIGSEGV
521     case SIGBUS:
522       exception_str = "Bus error";
523       break;
524 #    endif
525 #  endif
526 #  ifdef SIGFPE
527     case SIGFPE:
528       exception_str = "Floating-point exception";
529       break;
530 #  endif
531 #  ifdef SIGILL
532     case SIGILL:
533       exception_str = "Illegal instruction";
534       break;
535 #  endif
536 #  ifdef SIGINT
537     case SIGINT:
538       exception_str = "User interrupt";
539       break;
540 #  endif
541 #  ifdef SIGABRT
542     case SIGABRT:
543       exception_str = "Child aborted";
544       break;
545 #  endif
546 #  ifdef SIGKILL
547     case SIGKILL:
548       exception_str = "Child killed";
549       break;
550 #  endif
551 #  ifdef SIGTERM
552     case SIGTERM:
553       exception_str = "Child terminated";
554       break;
555 #  endif
556 #  ifdef SIGHUP
557     case SIGHUP:
558       exception_str = "SIGHUP";
559       break;
560 #  endif
561 #  ifdef SIGQUIT
562     case SIGQUIT:
563       exception_str = "SIGQUIT";
564       break;
565 #  endif
566 #  ifdef SIGTRAP
567     case SIGTRAP:
568       exception_str = "SIGTRAP";
569       break;
570 #  endif
571 #  ifdef SIGIOT
572 #    if !defined(SIGABRT) || SIGIOT != SIGABRT
573     case SIGIOT:
574       exception_str = "SIGIOT";
575       break;
576 #    endif
577 #  endif
578 #  ifdef SIGUSR1
579     case SIGUSR1:
580       exception_str = "SIGUSR1";
581       break;
582 #  endif
583 #  ifdef SIGUSR2
584     case SIGUSR2:
585       exception_str = "SIGUSR2";
586       break;
587 #  endif
588 #  ifdef SIGPIPE
589     case SIGPIPE:
590       exception_str = "SIGPIPE";
591       break;
592 #  endif
593 #  ifdef SIGALRM
594     case SIGALRM:
595       exception_str = "SIGALRM";
596       break;
597 #  endif
598 #  ifdef SIGSTKFLT
599     case SIGSTKFLT:
600       exception_str = "SIGSTKFLT";
601       break;
602 #  endif
603 #  ifdef SIGCHLD
604     case SIGCHLD:
605       exception_str = "SIGCHLD";
606       break;
607 #  elif defined(SIGCLD)
608     case SIGCLD:
609       exception_str = "SIGCLD";
610       break;
611 #  endif
612 #  ifdef SIGCONT
613     case SIGCONT:
614       exception_str = "SIGCONT";
615       break;
616 #  endif
617 #  ifdef SIGSTOP
618     case SIGSTOP:
619       exception_str = "SIGSTOP";
620       break;
621 #  endif
622 #  ifdef SIGTSTP
623     case SIGTSTP:
624       exception_str = "SIGTSTP";
625       break;
626 #  endif
627 #  ifdef SIGTTIN
628     case SIGTTIN:
629       exception_str = "SIGTTIN";
630       break;
631 #  endif
632 #  ifdef SIGTTOU
633     case SIGTTOU:
634       exception_str = "SIGTTOU";
635       break;
636 #  endif
637 #  ifdef SIGURG
638     case SIGURG:
639       exception_str = "SIGURG";
640       break;
641 #  endif
642 #  ifdef SIGXCPU
643     case SIGXCPU:
644       exception_str = "SIGXCPU";
645       break;
646 #  endif
647 #  ifdef SIGXFSZ
648     case SIGXFSZ:
649       exception_str = "SIGXFSZ";
650       break;
651 #  endif
652 #  ifdef SIGVTALRM
653     case SIGVTALRM:
654       exception_str = "SIGVTALRM";
655       break;
656 #  endif
657 #  ifdef SIGPROF
658     case SIGPROF:
659       exception_str = "SIGPROF";
660       break;
661 #  endif
662 #  ifdef SIGWINCH
663     case SIGWINCH:
664       exception_str = "SIGWINCH";
665       break;
666 #  endif
667 #  ifdef SIGPOLL
668     case SIGPOLL:
669       exception_str = "SIGPOLL";
670       break;
671 #  endif
672 #  ifdef SIGIO
673 #    if !defined(SIGPOLL) || SIGIO != SIGPOLL
674     case SIGIO:
675       exception_str = "SIGIO";
676       break;
677 #    endif
678 #  endif
679 #  ifdef SIGPWR
680     case SIGPWR:
681       exception_str = "SIGPWR";
682       break;
683 #  endif
684 #  ifdef SIGSYS
685     case SIGSYS:
686       exception_str = "SIGSYS";
687       break;
688 #  endif
689 #  ifdef SIGUNUSED
690 #    if !defined(SIGSYS) || SIGUNUSED != SIGSYS
691     case SIGUNUSED:
692       exception_str = "SIGUNUSED";
693       break;
694 #    endif
695 #  endif
696     default:
697       exception_str = cmStrCat("Signal ", this->Signal);
698   }
699 #endif
700   return exception_str;
701 }