CBMC
piped_process.cpp
Go to the documentation of this file.
1 
5 // NOTES ON WINDOWS PIPES IMPLEMENTATION
6 //
7 // This is a note to explain the choices related to the Windows pipes
8 // implementation and to serve as information for future work on the
9 // Windows parts of this class.
10 //
11 // Windows supports two kinds of pipes: anonymous and named.
12 //
13 // Anonymous pipes can only operate in blocking mode. This is a problem for
14 // this class because blocking mode pipes (on Windows) will not allow the
15 // other end to read until the process providing the data has terminated.
16 // (You might think that this is not necessary, but in practice this is
17 // the case.) For example, if we ran
18 // echo The Jabberwocky; ping 127.0.0.1 -n 6 >nul
19 // on the command line in Windows we would see the string "The Jabberwocky"
20 // immediately, and then the command would end about 6 seconds later after the
21 // pings complete. However, a blocking pipe will see nothing until the ping
22 // command has finished, even if the echo has completed and (supposedly)
23 // written to the pipe.
24 //
25 // For the above reason, we NEED to be able to use non-blocking pipes. Since
26 // anonymous pipes cannot be non-blocking (in theory they have a named pipe
27 // underneath, but it's not clear you could hack this to be non-blocking
28 // safely), we have to use named pipes.
29 //
30 // Named pipes can be non-blocking and this is how we create them.
31 //
32 // Aside on security:
33 // Named pipes can be connected to by other processes and here we have NOT
34 // gone deep into the security handling. The default used here is to allow
35 // access from the same session token/permissions. This SHOULD be sufficient
36 // for what we need.
37 //
38 // Non-blocking pipes allow immediate reading of any data on the pipe which
39 // matches the Linux/MacOS pipe behaviour and also allows reading of the
40 // string "The Jabberwocky" from the example above before waiting for the ping
41 // command to terminate. This reading can be done with any of the usual pipe
42 // read/peek functions, so we use those.
43 //
44 // There is one problem with the approach used here, that there is no Windows
45 // function that can wait on a non-blocking pipe. There are a few options that
46 // appear like they would work (or claim they work). Details on these and why
47 // they don't work are over-viewed here:
48 // - WaitCommEvent claims it can wait for events on a handle (e.g. char
49 // written) which would be perfect. Unfortunately on a non-blocking pipe
50 // this returns immediately. Using this on a blocking pipe fails to detect
51 // that a character is written until the other process terminates in the
52 // example above, making this ineffective for what we want.
53 // - Setting the pipe timeout or changing blocking after creation. This is
54 // theoretically possible, but in practice either has no effect, or can
55 // cause a segmentation fault. This was attempted with the SetCommTimeouts
56 // function and cause segfault.
57 // - Using a wait for event function (e.g. WaitForMultipleObjects, also single
58 // object, event, etc.). These can in theory wait until an event, but have
59 // the problem that with non-blocking pipes, the wait will not happen since
60 // they return immediately. One might think they can work with a blocking
61 // pipe and a timeout (i.e. have a blocking read and a timeout thread and
62 // wait for one of them to happen to see if there is something to read or
63 // whether we could timeout). However, while this can create the right
64 // wait and timeout behaviour, since the underlying pipe is blocking this
65 // means the example above cannot read "The Jabberwocky" until the ping has
66 // finished, again undoing the interactive behaviour desired.
67 // Since none of the above work effectivley, the chosen approach is to use a
68 // non-blocking peek to see if there is anthing to read, and use a sleep and
69 // poll behaviour that might be much busier than we want. At the time of
70 // writing this has not been made smart, just a first choice option for how
71 // frequently to poll.
72 //
73 // Conclusion
74 // The implementation is written this way to mitigate the problems with what
75 // can and cannot be done with Windows pipes. It's not always pretty, but it
76 // does work and handles what we want.
77 
78 #ifdef _WIN32
79 # include "run.h" // for Windows arg quoting
80 # include "unicode.h" // for widen function
81 # include <tchar.h> // library for _tcscpy function
82 # include <windows.h>
83 #else
84 # include <fcntl.h> // library for fcntl function
85 # include <poll.h> // library for poll function
86 # include <signal.h> // library for kill function
87 # include <unistd.h> // library for read/write/sleep/etc. functions
88 #endif
89 
90 #include "exception_utils.h"
91 #include "invariant.h"
92 #include "narrow.h"
93 #include "piped_process.h"
94 
95 #include <cstring> // library for strerror function (on linux)
96 #include <iostream>
97 #include <vector>
98 
99 #ifdef _WIN32
100 # define BUFSIZE (1024 * 64)
101 #else
102 # define BUFSIZE 2048
103 #endif
104 
105 #ifdef _WIN32
111 static std::wstring
112 prepare_windows_command_line(const std::vector<std::string> &commandvec)
113 {
114  std::wstring result = widen(commandvec[0]);
115  for(int i = 1; i < commandvec.size(); i++)
116  {
117  result.append(L" ");
118  result.append(quote_windows_arg(widen(commandvec[i])));
119  }
120  return result;
121 }
122 #endif
123 
125  const std::vector<std::string> &commandvec,
126  message_handlert &message_handler)
127  : log{message_handler}
128 {
129 # ifdef _WIN32
130  // Security attributes for pipe creation
131  SECURITY_ATTRIBUTES sec_attr;
132  sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
133  // Ensure pipes are inherited
134  sec_attr.bInheritHandle = TRUE;
135  // This sets the security to the default for the current session access token
136  // See following link for details
137  // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/aa379560(v=vs.85) //NOLINT
138  sec_attr.lpSecurityDescriptor = NULL;
139  // Use named pipes to allow non-blocking read
140  // Build the base name for the pipes
141  std::string base_name = "\\\\.\\pipe\\cbmc\\child\\";
142  // Use process ID as a unique ID for this process at this time.
143  base_name.append(std::to_string(GetCurrentProcessId()));
144  const std::string in_name = base_name + "\\IN";
145  child_std_IN_Wr = CreateNamedPipe(
146  in_name.c_str(),
147  PIPE_ACCESS_OUTBOUND, // Writing for us
148  PIPE_TYPE_BYTE | PIPE_NOWAIT, // Bytes and non-blocking
149  PIPE_UNLIMITED_INSTANCES, // Probably doesn't matter
150  BUFSIZE,
151  BUFSIZE, // Output and input bufffer sizes
152  0, // Timeout in ms, 0 = use system default
153  // This is the timeout that WaitNamedPipe functions will wait to try
154  // and connect before aborting if no instance of the pipe is available.
155  // In practice this is not used since we connect immediately and only
156  // use one instance (no waiting for a free instance).
157  &sec_attr); // For inheritance by child
158  if(child_std_IN_Rd == INVALID_HANDLE_VALUE)
159  {
160  throw system_exceptiont("Input pipe creation failed for child_std_IN_Rd");
161  }
162  // Connect to the other side of the pipe
163  child_std_IN_Rd = CreateFile(
164  in_name.c_str(),
165  GENERIC_READ, // Read side
166  FILE_SHARE_READ | FILE_SHARE_WRITE, // Shared read/write
167  &sec_attr, // Need this for inherit
168  OPEN_EXISTING, // Opening other end
169  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, // Normal, but don't buffer
170  NULL);
171  if(child_std_IN_Wr == INVALID_HANDLE_VALUE)
172  {
173  throw system_exceptiont("Input pipe creation failed for child_std_IN_Wr");
174  }
175  if(!SetHandleInformation(
176  child_std_IN_Rd, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
177  {
178  throw system_exceptiont(
179  "Input pipe creation failed on SetHandleInformation");
180  }
181  const std::string out_name = base_name + "\\OUT";
182  child_std_OUT_Rd = CreateNamedPipe(
183  out_name.c_str(),
184  PIPE_ACCESS_INBOUND, // Reading for us
185  PIPE_TYPE_BYTE | PIPE_NOWAIT, // Bytes and non-blocking
186  PIPE_UNLIMITED_INSTANCES, // Probably doesn't matter
187  BUFSIZE,
188  BUFSIZE, // Output and input bufffer sizes
189  0, // Timeout in ms, 0 = use system default
190  &sec_attr); // For inheritance by child
191  if(child_std_OUT_Rd == INVALID_HANDLE_VALUE)
192  {
193  throw system_exceptiont("Output pipe creation failed for child_std_OUT_Rd");
194  }
195  child_std_OUT_Wr = CreateFile(
196  out_name.c_str(),
197  GENERIC_WRITE, // Write side
198  FILE_SHARE_READ | FILE_SHARE_WRITE, // Shared read/write
199  &sec_attr, // Need this for inherit
200  OPEN_EXISTING, // Opening other end
201  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, // Normal, but don't buffer
202  NULL);
203  if(child_std_OUT_Wr == INVALID_HANDLE_VALUE)
204  {
205  throw system_exceptiont("Output pipe creation failed for child_std_OUT_Wr");
206  }
207  if(!SetHandleInformation(child_std_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
208  {
209  throw system_exceptiont(
210  "Output pipe creation failed on SetHandleInformation");
211  }
212  // Create the child process
213  STARTUPINFOW start_info;
214  proc_info = std::make_unique<PROCESS_INFORMATION>();
215  ZeroMemory(proc_info.get(), sizeof(PROCESS_INFORMATION));
216  ZeroMemory(&start_info, sizeof(STARTUPINFOW));
217  start_info.cb = sizeof(STARTUPINFOW);
218  start_info.hStdError = child_std_OUT_Wr;
219  start_info.hStdOutput = child_std_OUT_Wr;
220  start_info.hStdInput = child_std_IN_Rd;
221  start_info.dwFlags |= STARTF_USESTDHANDLES;
222  const std::wstring cmdline = prepare_windows_command_line(commandvec);
223  // Note that we do NOT free this since it becomes part of the child
224  // and causes heap corruption in Windows if we free!
225  const BOOL success = CreateProcessW(
226  NULL, // application name, we only use the command below
227  _wcsdup(cmdline.c_str()), // command line
228  NULL, // process security attributes
229  NULL, // primary thread security attributes
230  TRUE, // handles are inherited
231  0, // creation flags
232  NULL, // use parent's environment
233  NULL, // use parent's current directory
234  &start_info, // STARTUPINFO pointer
235  proc_info.get()); // receives PROCESS_INFORMATION
236  // Close handles to the stdin and stdout pipes no longer needed by the
237  // child process. If they are not explicitly closed, there is no way to
238  // recognize that the child process has ended (but maybe we don't care).
239  CloseHandle(child_std_OUT_Wr);
240  CloseHandle(child_std_IN_Rd);
241  if(!success)
242  throw system_exceptiont("Process creation failed.");
243 # else
244 
245  if(pipe(pipe_input) == -1)
246  {
247  throw system_exceptiont("Input pipe creation failed");
248  }
249 
250  if(pipe(pipe_output) == -1)
251  {
252  throw system_exceptiont("Output pipe creation failed");
253  }
254 
255 
256  if(fcntl(pipe_output[0], F_SETFL, O_NONBLOCK) < 0)
257  {
258  throw system_exceptiont("Setting pipe non-blocking failed");
259  }
260 
261  // Create a new process for the child that will execute the
262  // command and receive information via pipes.
263  child_process_id = fork();
264  if(child_process_id == 0)
265  {
266  // child process here
267 
268  // Close pipes that will be used by the parent so we do
269  // not have our own copies and conflicts.
270  close(pipe_input[1]);
271  close(pipe_output[0]);
272 
273  // Duplicate pipes so we have the ones we need.
274  dup2(pipe_input[0], STDIN_FILENO);
275  dup2(pipe_output[1], STDOUT_FILENO);
276  dup2(pipe_output[1], STDERR_FILENO);
277 
278  // Create a char** for the arguments plus a NULL terminator (by convention,
279  // the first "argument" is the command itself)
280  char **args = reinterpret_cast<char **>(
281  malloc((commandvec.size() + 1) * sizeof(char *)));
282  // Add all the arguments to the args array of char *.
283  unsigned long i = 0;
284  while(i < commandvec.size())
285  {
286  args[i] = strdup(commandvec[i].c_str());
287  i++;
288  }
289  args[i] = NULL;
290  execvp(commandvec[0].c_str(), args);
291  // The args variable will be handled by the OS if execvp succeeds, but
292  // if execvp fails then we should free it here (just in case the runtime
293  // error below continues execution.)
294  while(i > 0)
295  {
296  i--;
297  free(args[i]);
298  }
299  free(args);
300  // Only reachable if execvp failed
301  // Note that here we send to std::cerr since we are in the child process
302  // here and this is received by the parent process.
303  std::cerr << "Launching " << commandvec[0]
304  << " failed with error: " << std::strerror(errno) << std::endl;
305  abort();
306  }
307  else
308  {
309  // parent process here
310  // Close pipes to be used by the child process
311  close(pipe_input[0]);
312  close(pipe_output[1]);
313 
314  // Get stream for sending to the child process
315  command_stream = fdopen(pipe_input[1], "w");
316  }
317 # endif
319 }
320 
322 {
323 # ifdef _WIN32
324  TerminateProcess(proc_info->hProcess, 0);
325  // Disconnecting the pipes also kicks the client off, it should be killed
326  // by now, but this will also force the client off.
327  // Note that pipes are cleaned up by Windows when all handles to the pipe
328  // are closed. Disconnect may be superfluous here.
329  DisconnectNamedPipe(child_std_OUT_Rd);
330  DisconnectNamedPipe(child_std_IN_Wr);
331  CloseHandle(child_std_OUT_Rd);
332  CloseHandle(child_std_IN_Wr);
333  CloseHandle(proc_info->hProcess);
334  CloseHandle(proc_info->hThread);
335 # else
336  // Close the parent side of the remaining pipes
338  // Note that the above will call close(pipe_input[1]);
339  close(pipe_output[0]);
340  // Send signal to the child process to terminate
341  kill(child_process_id, SIGTERM);
342 # endif
343 }
344 
345 [[nodiscard]] piped_processt::send_responset
346 piped_processt::send(const std::string &message)
347 {
349  {
351  }
352 #ifdef _WIN32
353  const auto message_size = narrow<DWORD>(message.size());
354  PRECONDITION(message_size > 0);
355  DWORD bytes_written = 0;
356  const int retry_limit = 10;
357  for(int send_attempts = 0; send_attempts < retry_limit; ++send_attempts)
358  {
359  // `WriteFile` can return a success status but write 0 bytes if we write
360  // messages quickly enough. This problem has been observed when using a
361  // release build, but resolved when using a debug build or `--verbosity 10`.
362  // Presumably this happens if cbmc gets too far ahead of the sub process.
363  // Flushing the buffer and retrying should then succeed to write the message
364  // in this case.
365  if(!WriteFile(
366  child_std_IN_Wr, message.c_str(), message_size, &bytes_written, NULL))
367  {
368  const DWORD error_code = GetLastError();
369  log.debug() << "Last error code is " + std::to_string(error_code)
370  << messaget::eom;
371  return send_responset::FAILED;
372  }
373  if(bytes_written != 0)
374  break;
375  // Give the sub-process chance to read the waiting message(s).
376  const auto wait_milliseconds = narrow<DWORD>(1 << send_attempts);
377  log.debug() << "Zero bytes send to sub process. Retrying in "
378  << wait_milliseconds << " milliseconds." << messaget::eom;
379  FlushFileBuffers(child_std_IN_Wr);
380  Sleep(wait_milliseconds);
381  }
382  INVARIANT(
383  message_size == bytes_written,
384  "Number of bytes written to sub process must match message size."
385  "Message size is " +
386  std::to_string(message_size) + " but " + std::to_string(bytes_written) +
387  " bytes were written.");
388 #else
389  // send message to solver process
390  int send_status = fputs(message.c_str(), command_stream);
392 
393  if(send_status == EOF)
394  {
395  return send_responset::FAILED;
396  }
397 # endif
399 }
400 
402 {
403  INVARIANT(
405  "Can only receive() from a fully initialised process");
406  std::string response = std::string("");
407  char buff[BUFSIZE];
408  bool success = true;
409 #ifdef _WIN32
410  DWORD nbytes;
411 #else
412  int nbytes;
413 #endif
414  while(success)
415  {
416 #ifdef _WIN32
417  success = ReadFile(child_std_OUT_Rd, buff, BUFSIZE, &nbytes, NULL);
418 #else
419  nbytes = read(pipe_output[0], buff, BUFSIZE);
420  // Added the status back in here to keep parity with old implementation
421  // TODO: check which statuses are really used/needed.
422  if(nbytes == 0) // Update if the pipe is stopped
424  success = nbytes > 0;
425 #endif
426  INVARIANT(
427  nbytes < BUFSIZE,
428  "More bytes cannot be read at a time, than the size of the buffer");
429  if(nbytes > 0)
430  {
431  response.append(buff, nbytes);
432  }
433  }
434  return response;
435 }
436 
438 {
439  // can_receive(PIPED_PROCESS_INFINITE_TIMEOUT) waits an ubounded time until
440  // there is some data
442  return receive();
443 }
444 
446 {
447  return process_state;
448 }
449 
450 bool piped_processt::can_receive(std::optional<std::size_t> wait_time)
451 {
452  // unwrap the optional argument here
453  const int timeout = wait_time ? narrow<int>(*wait_time) : -1;
454 #ifdef _WIN32
455  int waited_time = 0;
456  DWORD total_bytes_available = 0;
457  while(timeout < 0 || waited_time >= timeout)
458  {
459  const LPVOID lpBuffer = nullptr;
460  const DWORD nBufferSize = 0;
461  const LPDWORD lpBytesRead = nullptr;
462  const LPDWORD lpTotalBytesAvail = &total_bytes_available;
463  const LPDWORD lpBytesLeftThisMessage = nullptr;
464  PeekNamedPipe(
465  child_std_OUT_Rd,
466  lpBuffer,
467  nBufferSize,
468  lpBytesRead,
469  lpTotalBytesAvail,
470  lpBytesLeftThisMessage);
471  if(total_bytes_available > 0)
472  {
473  return true;
474  }
475 // TODO make this define and choice better
476 # define WIN_POLL_WAIT 10
477  Sleep(WIN_POLL_WAIT);
478  waited_time += WIN_POLL_WAIT;
479  }
480 #else
481  struct pollfd fds // NOLINT
482  {
483  pipe_output[0], POLLIN, 0
484  };
485  nfds_t nfds = POLLIN;
486  const int ready = poll(&fds, nfds, timeout);
487 
488  switch(ready)
489  {
490  case -1:
491  // Error case
492  // Further error handling could go here
494  // fallthrough intended
495  case 0:
496  // Timeout case
497  // Do nothing for timeout and error fallthrough, default function behaviour
498  // is to return false.
499  break;
500  default:
501  // Found some events, check for POLLIN
502  if(fds.revents & POLLIN)
503  {
504  // we can read from the pipe here
505  return true;
506  }
507  // Some revent we did not ask for or check for, can't read though.
508  }
509 # endif
510  return false;
511 }
512 
514 {
515  return can_receive(0);
516 }
517 
519 {
520  while(process_state == statet::RUNNING && !can_receive(0))
521  {
522 #ifdef _WIN32
523  Sleep(wait_time);
524 #else
525  usleep(wait_time);
526 #endif
527  }
528 }
mstreamt & debug() const
Definition: message.h:421
static eomt eom
Definition: message.h:289
pid_t child_process_id
statet process_state
bool can_receive()
See if this process can receive data from the other process.
void wait_receivable(int wait_time)
Wait for the pipe to be ready, waiting specified time between checks.
std::string receive()
Read a string from the child process' output.
send_responset send(const std::string &message)
Send a string message (command) to the child process.
FILE * command_stream
statet
Enumeration to keep track of child process state.
Definition: piped_process.h:30
piped_processt(const std::vector< std::string > &commandvec, message_handlert &message_handler)
Initiate a new subprocess with pipes supporting communication between the parent (this process) and t...
statet get_status()
Get child process status.
send_responset
Enumeration for send response.
Definition: piped_process.h:37
std::string wait_receive()
Wait until a string is available and read a string from the child process' output.
Thrown when some external system fails unexpectedly.
int fcntl(int fd, int cmd,...)
Definition: fcntl.c:34
int __CPROVER_ID java::java io InputStream read
Definition: java.io.c:5
double log(double x)
Definition: math.c:2776
#define BUFSIZE
Subprocess communication with pipes.
#define PIPED_PROCESS_INFINITE_TIMEOUT
Definition: piped_process.h:20
int kill(pid_t pid, int sig)
Definition: signal.c:15
#define PRECONDITION(CONDITION)
Definition: invariant.h:463
FILE * fdopen(int handle, const char *mode)
Definition: stdio.c:256
int fputs(const char *s, FILE *stream)
Definition: stdio.c:611
int fclose(FILE *stream)
Definition: stdio.c:230
int fflush(FILE *stream)
Definition: stdio.c:647
void * malloc(__CPROVER_size_t malloc_size)
Definition: stdlib.c:212
void abort(void)
Definition: stdlib.c:128
void free(void *ptr)
Definition: stdlib.c:317
char * strdup(const char *str)
Definition: string.c:590
char * strerror(int errnum)
Definition: string.c:1014
std::string to_string(const string_not_contains_constraintt &expr)
Used for debug printing.
std::wstring widen(const char *s)
Definition: unicode.cpp:49
int usleep(unsigned int usec)
Definition: unistd.c:34
int close(int fildes)
Definition: unistd.c:139
int pipe(int fildes[2])
Definition: unistd.c:90