1/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to
5 * deal in the Software without restriction, including without limitation the
6 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 * sell copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
9 *
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 * IN THE SOFTWARE.
20 */
21
22#include "runner-unix.h"
23#include "runner.h"
24
25#include <limits.h>
26#include <stdint.h> /* uintptr_t */
27
28#include <errno.h>
29#include <unistd.h> /* usleep */
30#include <string.h> /* strdup */
31#include <stdio.h>
32#include <stdlib.h>
33#include <sys/types.h>
34#include <signal.h>
35#include <sys/wait.h>
36#include <sys/stat.h>
37#include <assert.h>
38
39#include <sys/select.h>
40#include <sys/time.h>
41#include <pthread.h>
42
43extern char** environ;
44
45static void closefd(int fd) {
46  if (close(fd) == 0 || errno == EINTR || errno == EINPROGRESS)
47    return;
48
49  perror("close");
50  abort();
51}
52
53
54void notify_parent_process(void) {
55  char* arg;
56  int fd;
57
58  arg = getenv("UV_TEST_RUNNER_FD");
59  if (arg == NULL)
60    return;
61
62  fd = atoi(arg);
63  assert(fd > STDERR_FILENO);
64  unsetenv("UV_TEST_RUNNER_FD");
65  closefd(fd);
66}
67
68
69/* Do platform-specific initialization. */
70void platform_init(int argc, char **argv) {
71  /* Disable stdio output buffering. */
72  setvbuf(stdout, NULL, _IONBF, 0);
73  setvbuf(stderr, NULL, _IONBF, 0);
74  signal(SIGPIPE, SIG_IGN);
75  snprintf(executable_path, sizeof(executable_path), "%s", argv[0]);
76}
77
78
79/* Invoke "argv[0] test-name [test-part]". Store process info in *p. Make sure
80 * that all stdio output of the processes is buffered up. */
81int process_start(char* name, char* part, process_info_t* p, int is_helper) {
82  FILE* stdout_file;
83  int stdout_fd;
84  const char* arg;
85  char* args[16];
86  int pipefd[2];
87  char fdstr[8];
88  ssize_t rc;
89  int n;
90  pid_t pid;
91
92  arg = getenv("UV_USE_VALGRIND");
93  n = 0;
94
95  /* Disable valgrind for helpers, it complains about helpers leaking memory.
96   * They're killed after the test and as such never get a chance to clean up.
97   */
98  if (is_helper == 0 && arg != NULL && atoi(arg) != 0) {
99    args[n++] = "valgrind";
100    args[n++] = "--quiet";
101    args[n++] = "--leak-check=full";
102    args[n++] = "--show-reachable=yes";
103    args[n++] = "--error-exitcode=125";
104  }
105
106  args[n++] = executable_path;
107  args[n++] = name;
108  args[n++] = part;
109  args[n++] = NULL;
110
111  stdout_file = tmpfile();
112  stdout_fd = fileno(stdout_file);
113  if (!stdout_file) {
114    perror("tmpfile");
115    return -1;
116  }
117
118  if (is_helper) {
119    if (pipe(pipefd)) {
120      perror("pipe");
121      return -1;
122    }
123
124    snprintf(fdstr, sizeof(fdstr), "%d", pipefd[1]);
125    if (setenv("UV_TEST_RUNNER_FD", fdstr, /* overwrite */ 1)) {
126      perror("setenv");
127      return -1;
128    }
129  }
130
131  p->terminated = 0;
132  p->status = 0;
133
134  pid = fork();
135
136  if (pid < 0) {
137    perror("fork");
138    return -1;
139  }
140
141  if (pid == 0) {
142    /* child */
143    if (is_helper)
144      closefd(pipefd[0]);
145    dup2(stdout_fd, STDOUT_FILENO);
146    dup2(stdout_fd, STDERR_FILENO);
147    execve(args[0], args, environ);
148    perror("execve()");
149    _exit(127);
150  }
151
152  /* parent */
153  p->pid = pid;
154  p->name = strdup(name);
155  p->stdout_file = stdout_file;
156
157  if (!is_helper)
158    return 0;
159
160  closefd(pipefd[1]);
161  unsetenv("UV_TEST_RUNNER_FD");
162
163  do
164    rc = read(pipefd[0], &n, 1);
165  while (rc == -1 && errno == EINTR);
166
167  closefd(pipefd[0]);
168
169  if (rc == -1) {
170    perror("read");
171    return -1;
172  }
173
174  if (rc > 0) {
175    fprintf(stderr, "EOF expected but got data.\n");
176    return -1;
177  }
178
179  return 0;
180}
181
182
183typedef struct {
184  int pipe[2];
185  process_info_t* vec;
186  int n;
187} dowait_args;
188
189
190/* This function is run inside a pthread. We do this so that we can possibly
191 * timeout.
192 */
193static void* dowait(void* data) {
194  dowait_args* args = data;
195
196  int i, r;
197  process_info_t* p;
198
199  for (i = 0; i < args->n; i++) {
200    p = &args->vec[i];
201    if (p->terminated) continue;
202    r = waitpid(p->pid, &p->status, 0);
203    if (r < 0) {
204      perror("waitpid");
205      return NULL;
206    }
207    p->terminated = 1;
208  }
209
210  if (args->pipe[1] >= 0) {
211    /* Write a character to the main thread to notify it about this. */
212    ssize_t r;
213
214    do
215      r = write(args->pipe[1], "", 1);
216    while (r == -1 && errno == EINTR);
217  }
218
219  return NULL;
220}
221
222
223/* Wait for all `n` processes in `vec` to terminate. Time out after `timeout`
224 * msec, or never if timeout == -1. Return 0 if all processes are terminated,
225 * -1 on error, -2 on timeout. */
226int process_wait(process_info_t* vec, int n, int timeout) {
227  int i;
228  int r;
229  int retval;
230  process_info_t* p;
231  dowait_args args;
232  pthread_t tid;
233  pthread_attr_t attr;
234  unsigned int elapsed_ms;
235  struct timeval timebase;
236  struct timeval tv;
237  fd_set fds;
238
239  args.vec = vec;
240  args.n = n;
241  args.pipe[0] = -1;
242  args.pipe[1] = -1;
243
244  /* The simple case is where there is no timeout */
245  if (timeout == -1) {
246    dowait(&args);
247    return 0;
248  }
249
250  /* Hard case. Do the wait with a timeout.
251   *
252   * Assumption: we are the only ones making this call right now. Otherwise
253   * we'd need to lock vec.
254   */
255
256  r = pipe((int*)&(args.pipe));
257  if (r) {
258    perror("pipe()");
259    return -1;
260  }
261
262  if (pthread_attr_init(&attr))
263    abort();
264
265#if defined(__MVS__)
266  if (pthread_attr_setstacksize(&attr, 1024 * 1024))
267#else
268  if (pthread_attr_setstacksize(&attr, 256 * 1024))
269#endif
270    abort();
271
272  r = pthread_create(&tid, &attr, dowait, &args);
273
274  if (pthread_attr_destroy(&attr))
275    abort();
276
277  if (r) {
278    perror("pthread_create()");
279    retval = -1;
280    goto terminate;
281  }
282
283  if (gettimeofday(&timebase, NULL))
284    abort();
285
286  tv = timebase;
287  for (;;) {
288    /* Check that gettimeofday() doesn't jump back in time. */
289    assert(tv.tv_sec > timebase.tv_sec ||
290           (tv.tv_sec == timebase.tv_sec && tv.tv_usec >= timebase.tv_usec));
291
292    elapsed_ms =
293        (tv.tv_sec - timebase.tv_sec) * 1000 +
294        (tv.tv_usec / 1000) -
295        (timebase.tv_usec / 1000);
296
297    r = 0;  /* Timeout. */
298    if (elapsed_ms >= (unsigned) timeout)
299      break;
300
301    tv.tv_sec = (timeout - elapsed_ms) / 1000;
302    tv.tv_usec = (timeout - elapsed_ms) % 1000 * 1000;
303
304    FD_ZERO(&fds);
305    FD_SET(args.pipe[0], &fds);
306
307    r = select(args.pipe[0] + 1, &fds, NULL, NULL, &tv);
308    if (!(r == -1 && errno == EINTR))
309      break;
310
311    if (gettimeofday(&tv, NULL))
312      abort();
313  }
314
315  if (r == -1) {
316    perror("select()");
317    retval = -1;
318
319  } else if (r) {
320    /* The thread completed successfully. */
321    retval = 0;
322
323  } else {
324    /* Timeout. Kill all the children. */
325    for (i = 0; i < n; i++) {
326      p = &vec[i];
327      kill(p->pid, SIGTERM);
328    }
329    retval = -2;
330  }
331
332  if (pthread_join(tid, NULL))
333    abort();
334
335terminate:
336  closefd(args.pipe[0]);
337  closefd(args.pipe[1]);
338  return retval;
339}
340
341
342/* Returns the number of bytes in the stdio output buffer for process `p`. */
343long int process_output_size(process_info_t *p) {
344  /* Size of the p->stdout_file */
345  struct stat buf;
346
347  int r = fstat(fileno(p->stdout_file), &buf);
348  if (r < 0) {
349    return -1;
350  }
351
352  return (long)buf.st_size;
353}
354
355
356/* Copy the contents of the stdio output buffer to `fd`. */
357int process_copy_output(process_info_t* p, FILE* stream) {
358  char buf[1024];
359  int r;
360
361  r = fseek(p->stdout_file, 0, SEEK_SET);
362  if (r < 0) {
363    perror("fseek");
364    return -1;
365  }
366
367  /* TODO: what if the line is longer than buf */
368  while ((r = fread(buf, 1, sizeof(buf), p->stdout_file)) != 0)
369    print_lines(buf, r, stream);
370
371  if (ferror(p->stdout_file)) {
372    perror("read");
373    return -1;
374  }
375
376  return 0;
377}
378
379
380/* Copy the last line of the stdio output buffer to `buffer` */
381int process_read_last_line(process_info_t *p,
382                           char* buffer,
383                           size_t buffer_len) {
384  char* ptr;
385
386  int r = fseek(p->stdout_file, 0, SEEK_SET);
387  if (r < 0) {
388    perror("fseek");
389    return -1;
390  }
391
392  buffer[0] = '\0';
393
394  while (fgets(buffer, buffer_len, p->stdout_file) != NULL) {
395    for (ptr = buffer; *ptr && *ptr != '\r' && *ptr != '\n'; ptr++)
396      ;
397    *ptr = '\0';
398  }
399
400  if (ferror(p->stdout_file)) {
401    perror("read");
402    buffer[0] = '\0';
403    return -1;
404  }
405  return 0;
406}
407
408
409/* Return the name that was specified when `p` was started by process_start */
410char* process_get_name(process_info_t *p) {
411  return p->name;
412}
413
414
415/* Terminate process `p`. */
416int process_terminate(process_info_t *p) {
417  return kill(p->pid, SIGTERM);
418}
419
420
421/* Return the exit code of process p. On error, return -1. */
422int process_reap(process_info_t *p) {
423  if (WIFEXITED(p->status)) {
424    return WEXITSTATUS(p->status);
425  } else  {
426    return p->status; /* ? */
427  }
428}
429
430
431/* Clean up after terminating process `p` (e.g. free the output buffer etc.). */
432void process_cleanup(process_info_t *p) {
433  fclose(p->stdout_file);
434  free(p->name);
435}
436
437
438/* Move the console cursor one line up and back to the first column. */
439void rewind_cursor(void) {
440#if defined(__MVS__)
441  fprintf(stderr, "\047[2K\r");
442#else
443  fprintf(stderr, "\033[2K\r");
444#endif
445}
446