Imported Upstream version 3.17.1
[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->Finish();
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->Finish();
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
325   this->ProcessHandleClosed = true;
326   if (this->ReadHandleClosed) {
327     uv_timer_stop(this->Timer);
328     this->Finish();
329   }
330 }
331
332 void cmProcess::Finish()
333 {
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
338   // duration here.
339   if (this->TotalTime <= cmDuration::zero()) {
340     this->TotalTime = cmDuration::zero();
341   }
342   this->Runner.FinalizeTest();
343 }
344
345 cmProcess::State cmProcess::GetProcessStatus()
346 {
347   return this->ProcessState;
348 }
349
350 void cmProcess::ChangeTimeout(cmDuration t)
351 {
352   this->Timeout = t;
353   this->StartTimer();
354 }
355
356 void cmProcess::ResetStartTime()
357 {
358   this->StartTime = std::chrono::steady_clock::now();
359 }
360
361 cmProcess::Exception cmProcess::GetExitException()
362 {
363   auto exception = Exception::None;
364 #if defined(_WIN32) && !defined(__CYGWIN__)
365   auto exit_code = (DWORD)this->ExitValue;
366   if ((exit_code & 0xF0000000) != 0xC0000000) {
367     return exception;
368   }
369
370   if (exit_code) {
371     switch (exit_code) {
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;
381         break;
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:
391 #  endif
392 #  ifdef STATUS_FLOAT_MULTIPLE_TRAPS
393       case STATUS_FLOAT_MULTIPLE_TRAPS:
394 #  endif
395       case STATUS_INTEGER_DIVIDE_BY_ZERO:
396       case STATUS_INTEGER_OVERFLOW:
397         exception = Exception::Numerical;
398         break;
399       case STATUS_CONTROL_C_EXIT:
400         exception = Exception::Interrupt;
401         break;
402       case STATUS_ILLEGAL_INSTRUCTION:
403       case STATUS_PRIVILEGED_INSTRUCTION:
404         exception = Exception::Illegal;
405         break;
406       default:
407         exception = Exception::Other;
408     }
409   }
410 #else
411   if (this->Signal) {
412     switch (this->Signal) {
413       case SIGSEGV:
414         exception = Exception::Fault;
415         break;
416       case SIGFPE:
417         exception = Exception::Numerical;
418         break;
419       case SIGINT:
420         exception = Exception::Interrupt;
421         break;
422       case SIGILL:
423         exception = Exception::Illegal;
424         break;
425       default:
426         exception = Exception::Other;
427     }
428   }
429 #endif
430   return exception;
431 }
432
433 std::string cmProcess::GetExitExceptionString()
434 {
435   std::string exception_str;
436 #if defined(_WIN32)
437   switch (this->ExitValue) {
438     case STATUS_CONTROL_C_EXIT:
439       exception_str = "User interrupt";
440       break;
441     case STATUS_FLOAT_DENORMAL_OPERAND:
442       exception_str = "Floating-point exception (denormal operand)";
443       break;
444     case STATUS_FLOAT_DIVIDE_BY_ZERO:
445       exception_str = "Divide-by-zero";
446       break;
447     case STATUS_FLOAT_INEXACT_RESULT:
448       exception_str = "Floating-point exception (inexact result)";
449       break;
450     case STATUS_FLOAT_INVALID_OPERATION:
451       exception_str = "Invalid floating-point operation";
452       break;
453     case STATUS_FLOAT_OVERFLOW:
454       exception_str = "Floating-point overflow";
455       break;
456     case STATUS_FLOAT_STACK_CHECK:
457       exception_str = "Floating-point stack check failed";
458       break;
459     case STATUS_FLOAT_UNDERFLOW:
460       exception_str = "Floating-point underflow";
461       break;
462 #  ifdef STATUS_FLOAT_MULTIPLE_FAULTS
463     case STATUS_FLOAT_MULTIPLE_FAULTS:
464       exception_str = "Floating-point exception (multiple faults)";
465       break;
466 #  endif
467 #  ifdef STATUS_FLOAT_MULTIPLE_TRAPS
468     case STATUS_FLOAT_MULTIPLE_TRAPS:
469       exception_str = "Floating-point exception (multiple traps)";
470       break;
471 #  endif
472     case STATUS_INTEGER_DIVIDE_BY_ZERO:
473       exception_str = "Integer divide-by-zero";
474       break;
475     case STATUS_INTEGER_OVERFLOW:
476       exception_str = "Integer overflow";
477       break;
478
479     case STATUS_DATATYPE_MISALIGNMENT:
480       exception_str = "Datatype misalignment";
481       break;
482     case STATUS_ACCESS_VIOLATION:
483       exception_str = "Access violation";
484       break;
485     case STATUS_IN_PAGE_ERROR:
486       exception_str = "In-page error";
487       break;
488     case STATUS_INVALID_HANDLE:
489       exception_str = "Invalid handle";
490       break;
491     case STATUS_NONCONTINUABLE_EXCEPTION:
492       exception_str = "Noncontinuable exception";
493       break;
494     case STATUS_INVALID_DISPOSITION:
495       exception_str = "Invalid disposition";
496       break;
497     case STATUS_ARRAY_BOUNDS_EXCEEDED:
498       exception_str = "Array bounds exceeded";
499       break;
500     case STATUS_STACK_OVERFLOW:
501       exception_str = "Stack overflow";
502       break;
503
504     case STATUS_ILLEGAL_INSTRUCTION:
505       exception_str = "Illegal instruction";
506       break;
507     case STATUS_PRIVILEGED_INSTRUCTION:
508       exception_str = "Privileged instruction";
509       break;
510     case STATUS_NO_MEMORY:
511     default:
512       char buf[1024];
513       const char* fmt = "Exit code 0x%" KWIML_INT_PRIx64 "\n";
514       _snprintf(buf, 1024, fmt, this->ExitValue);
515       exception_str.assign(buf);
516   }
517 #else
518   switch (this->Signal) {
519 #  ifdef SIGSEGV
520     case SIGSEGV:
521       exception_str = "Segmentation fault";
522       break;
523 #  endif
524 #  ifdef SIGBUS
525 #    if !defined(SIGSEGV) || SIGBUS != SIGSEGV
526     case SIGBUS:
527       exception_str = "Bus error";
528       break;
529 #    endif
530 #  endif
531 #  ifdef SIGFPE
532     case SIGFPE:
533       exception_str = "Floating-point exception";
534       break;
535 #  endif
536 #  ifdef SIGILL
537     case SIGILL:
538       exception_str = "Illegal instruction";
539       break;
540 #  endif
541 #  ifdef SIGINT
542     case SIGINT:
543       exception_str = "User interrupt";
544       break;
545 #  endif
546 #  ifdef SIGABRT
547     case SIGABRT:
548       exception_str = "Child aborted";
549       break;
550 #  endif
551 #  ifdef SIGKILL
552     case SIGKILL:
553       exception_str = "Child killed";
554       break;
555 #  endif
556 #  ifdef SIGTERM
557     case SIGTERM:
558       exception_str = "Child terminated";
559       break;
560 #  endif
561 #  ifdef SIGHUP
562     case SIGHUP:
563       exception_str = "SIGHUP";
564       break;
565 #  endif
566 #  ifdef SIGQUIT
567     case SIGQUIT:
568       exception_str = "SIGQUIT";
569       break;
570 #  endif
571 #  ifdef SIGTRAP
572     case SIGTRAP:
573       exception_str = "SIGTRAP";
574       break;
575 #  endif
576 #  ifdef SIGIOT
577 #    if !defined(SIGABRT) || SIGIOT != SIGABRT
578     case SIGIOT:
579       exception_str = "SIGIOT";
580       break;
581 #    endif
582 #  endif
583 #  ifdef SIGUSR1
584     case SIGUSR1:
585       exception_str = "SIGUSR1";
586       break;
587 #  endif
588 #  ifdef SIGUSR2
589     case SIGUSR2:
590       exception_str = "SIGUSR2";
591       break;
592 #  endif
593 #  ifdef SIGPIPE
594     case SIGPIPE:
595       exception_str = "SIGPIPE";
596       break;
597 #  endif
598 #  ifdef SIGALRM
599     case SIGALRM:
600       exception_str = "SIGALRM";
601       break;
602 #  endif
603 #  ifdef SIGSTKFLT
604     case SIGSTKFLT:
605       exception_str = "SIGSTKFLT";
606       break;
607 #  endif
608 #  ifdef SIGCHLD
609     case SIGCHLD:
610       exception_str = "SIGCHLD";
611       break;
612 #  elif defined(SIGCLD)
613     case SIGCLD:
614       exception_str = "SIGCLD";
615       break;
616 #  endif
617 #  ifdef SIGCONT
618     case SIGCONT:
619       exception_str = "SIGCONT";
620       break;
621 #  endif
622 #  ifdef SIGSTOP
623     case SIGSTOP:
624       exception_str = "SIGSTOP";
625       break;
626 #  endif
627 #  ifdef SIGTSTP
628     case SIGTSTP:
629       exception_str = "SIGTSTP";
630       break;
631 #  endif
632 #  ifdef SIGTTIN
633     case SIGTTIN:
634       exception_str = "SIGTTIN";
635       break;
636 #  endif
637 #  ifdef SIGTTOU
638     case SIGTTOU:
639       exception_str = "SIGTTOU";
640       break;
641 #  endif
642 #  ifdef SIGURG
643     case SIGURG:
644       exception_str = "SIGURG";
645       break;
646 #  endif
647 #  ifdef SIGXCPU
648     case SIGXCPU:
649       exception_str = "SIGXCPU";
650       break;
651 #  endif
652 #  ifdef SIGXFSZ
653     case SIGXFSZ:
654       exception_str = "SIGXFSZ";
655       break;
656 #  endif
657 #  ifdef SIGVTALRM
658     case SIGVTALRM:
659       exception_str = "SIGVTALRM";
660       break;
661 #  endif
662 #  ifdef SIGPROF
663     case SIGPROF:
664       exception_str = "SIGPROF";
665       break;
666 #  endif
667 #  ifdef SIGWINCH
668     case SIGWINCH:
669       exception_str = "SIGWINCH";
670       break;
671 #  endif
672 #  ifdef SIGPOLL
673     case SIGPOLL:
674       exception_str = "SIGPOLL";
675       break;
676 #  endif
677 #  ifdef SIGIO
678 #    if !defined(SIGPOLL) || SIGIO != SIGPOLL
679     case SIGIO:
680       exception_str = "SIGIO";
681       break;
682 #    endif
683 #  endif
684 #  ifdef SIGPWR
685     case SIGPWR:
686       exception_str = "SIGPWR";
687       break;
688 #  endif
689 #  ifdef SIGSYS
690     case SIGSYS:
691       exception_str = "SIGSYS";
692       break;
693 #  endif
694 #  ifdef SIGUNUSED
695 #    if !defined(SIGSYS) || SIGUNUSED != SIGSYS
696     case SIGUNUSED:
697       exception_str = "SIGUNUSED";
698       break;
699 #    endif
700 #  endif
701     default:
702       exception_str = cmStrCat("Signal ", this->Signal);
703   }
704 #endif
705   return exception_str;
706 }