• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
43 extern char** environ;
44 
closefd(int fd)45 static void closefd(int fd) {
46   if (close(fd) == 0 || errno == EINTR || errno == EINPROGRESS)
47     return;
48 
49   perror("close");
50   abort();
51 }
52 
53 
notify_parent_process(void)54 void 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. */
platform_init(int argc,char ** argv)70 void 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. */
process_start(char * name,char * part,process_info_t * p,int is_helper)81 int 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 = fopen("/data/local/tmp/test.txt", "w+");
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     execve(args[0], args, environ);
146     perror("execve()");
147     _exit(127);
148   }
149 
150   /* parent */
151   p->pid = pid;
152   p->name = strdup(name);
153   p->stdout_file = stdout_file;
154 
155   if (!is_helper)
156     return 0;
157 
158   closefd(pipefd[1]);
159   unsetenv("UV_TEST_RUNNER_FD");
160 
161   do
162     rc = read(pipefd[0], &n, 1);
163   while (rc == -1 && errno == EINTR);
164 
165   closefd(pipefd[0]);
166 
167   if (rc == -1) {
168     perror("read");
169     return -1;
170   }
171 
172   if (rc > 0) {
173     fprintf(stderr, "EOF expected but got data.\n");
174     return -1;
175   }
176 
177   return 0;
178 }
179 
180 
181 typedef struct {
182   int pipe[2];
183   process_info_t* vec;
184   int n;
185 } dowait_args;
186 
187 
188 /* This function is run inside a pthread. We do this so that we can possibly
189  * timeout.
190  */
dowait(void * data)191 static void* dowait(void* data) {
192   dowait_args* args = data;
193 
194   int i, r;
195   process_info_t* p;
196 
197   for (i = 0; i < args->n; i++) {
198     p = &args->vec[i];
199     if (p->terminated) continue;
200     r = waitpid(p->pid, &p->status, 0);
201     if (r < 0) {
202       perror("waitpid");
203       return NULL;
204     }
205     p->terminated = 1;
206   }
207 
208   if (args->pipe[1] >= 0) {
209     /* Write a character to the main thread to notify it about this. */
210     ssize_t r;
211 
212     do
213       r = write(args->pipe[1], "", 1);
214     while (r == -1 && errno == EINTR);
215   }
216 
217   return NULL;
218 }
219 
220 
221 /* Wait for all `n` processes in `vec` to terminate. Time out after `timeout`
222  * msec, or never if timeout == -1. Return 0 if all processes are terminated,
223  * -1 on error, -2 on timeout. */
process_wait(process_info_t * vec,int n,int timeout)224 int process_wait(process_info_t* vec, int n, int timeout) {
225   int i;
226   int r;
227   int retval;
228   process_info_t* p;
229   dowait_args args;
230   pthread_t tid;
231   pthread_attr_t attr;
232   unsigned int elapsed_ms;
233   struct timeval timebase;
234   struct timeval tv;
235   fd_set fds;
236 
237   args.vec = vec;
238   args.n = n;
239   args.pipe[0] = -1;
240   args.pipe[1] = -1;
241 
242   /* The simple case is where there is no timeout */
243   if (timeout == -1) {
244     dowait(&args);
245     return 0;
246   }
247 
248   /* Hard case. Do the wait with a timeout.
249    *
250    * Assumption: we are the only ones making this call right now. Otherwise
251    * we'd need to lock vec.
252    */
253 
254   r = pipe((int*)&(args.pipe));
255   if (r) {
256     perror("pipe()");
257     return -1;
258   }
259 
260   if (pthread_attr_init(&attr))
261     abort();
262 
263 #if defined(__MVS__)
264   if (pthread_attr_setstacksize(&attr, 1024 * 1024))
265 #else
266   if (pthread_attr_setstacksize(&attr, 256 * 1024))
267 #endif
268     abort();
269 
270   r = pthread_create(&tid, &attr, dowait, &args);
271 
272   if (pthread_attr_destroy(&attr))
273     abort();
274 
275   if (r) {
276     perror("pthread_create()");
277     retval = -1;
278     goto terminate;
279   }
280 
281   if (gettimeofday(&timebase, NULL))
282     abort();
283 
284   tv = timebase;
285   for (;;) {
286     /* Check that gettimeofday() doesn't jump back in time. */
287     assert(tv.tv_sec > timebase.tv_sec ||
288            (tv.tv_sec == timebase.tv_sec && tv.tv_usec >= timebase.tv_usec));
289 
290     elapsed_ms =
291         (tv.tv_sec - timebase.tv_sec) * 1000 +
292         (tv.tv_usec / 1000) -
293         (timebase.tv_usec / 1000);
294 
295     r = 0;  /* Timeout. */
296     if (elapsed_ms >= (unsigned) timeout)
297       break;
298 
299     tv.tv_sec = (timeout - elapsed_ms) / 1000;
300     tv.tv_usec = (timeout - elapsed_ms) % 1000 * 1000;
301 
302     FD_ZERO(&fds);
303     FD_SET(args.pipe[0], &fds);
304 
305     r = select(args.pipe[0] + 1, &fds, NULL, NULL, &tv);
306     if (!(r == -1 && errno == EINTR))
307       break;
308 
309     if (gettimeofday(&tv, NULL))
310       abort();
311   }
312 
313   if (r == -1) {
314     perror("select()");
315     retval = -1;
316 
317   } else if (r) {
318     /* The thread completed successfully. */
319     retval = 0;
320 
321   } else {
322     /* Timeout. Kill all the children. */
323     for (i = 0; i < n; i++) {
324       p = &vec[i];
325       kill(p->pid, SIGTERM);
326     }
327     retval = -2;
328   }
329 
330   if (pthread_join(tid, NULL))
331     abort();
332 
333 terminate:
334   closefd(args.pipe[0]);
335   closefd(args.pipe[1]);
336   return retval;
337 }
338 
339 
340 /* Returns the number of bytes in the stdio output buffer for process `p`. */
process_output_size(process_info_t * p)341 long int process_output_size(process_info_t *p) {
342   /* Size of the p->stdout_file */
343   struct stat buf;
344 
345   int r = fstat(fileno(p->stdout_file), &buf);
346   if (r < 0) {
347     return -1;
348   }
349 
350   return (long)buf.st_size;
351 }
352 
353 
354 /* Copy the contents of the stdio output buffer to `fd`. */
process_copy_output(process_info_t * p,FILE * stream)355 int process_copy_output(process_info_t* p, FILE* stream) {
356   char buf[1024];
357   int r;
358 
359   r = fseek(p->stdout_file, 0, SEEK_SET);
360   if (r < 0) {
361     perror("fseek");
362     return -1;
363   }
364 
365   /* TODO: what if the line is longer than buf */
366   while ((r = fread(buf, 1, sizeof(buf), p->stdout_file)) != 0)
367     print_lines(buf, r, stream);
368 
369   if (ferror(p->stdout_file)) {
370     perror("read");
371     return -1;
372   }
373 
374   return 0;
375 }
376 
377 
378 /* Copy the last line of the stdio output buffer to `buffer` */
process_read_last_line(process_info_t * p,char * buffer,size_t buffer_len)379 int process_read_last_line(process_info_t *p,
380                            char* buffer,
381                            size_t buffer_len) {
382   char* ptr;
383 
384   int r = fseek(p->stdout_file, 0, SEEK_SET);
385   if (r < 0) {
386     perror("fseek");
387     return -1;
388   }
389 
390   buffer[0] = '\0';
391 
392   while (fgets(buffer, buffer_len, p->stdout_file) != NULL) {
393     for (ptr = buffer; *ptr && *ptr != '\r' && *ptr != '\n'; ptr++)
394       ;
395     *ptr = '\0';
396   }
397 
398   if (ferror(p->stdout_file)) {
399     perror("read");
400     buffer[0] = '\0';
401     return -1;
402   }
403   return 0;
404 }
405 
406 
407 /* Return the name that was specified when `p` was started by process_start */
process_get_name(process_info_t * p)408 char* process_get_name(process_info_t *p) {
409   return p->name;
410 }
411 
412 
413 /* Terminate process `p`. */
process_terminate(process_info_t * p)414 int process_terminate(process_info_t *p) {
415   return kill(p->pid, SIGTERM);
416 }
417 
418 
419 /* Return the exit code of process p. On error, return -1. */
process_reap(process_info_t * p)420 int process_reap(process_info_t *p) {
421   if (WIFEXITED(p->status)) {
422     return WEXITSTATUS(p->status);
423   } else  {
424     return p->status; /* ? */
425   }
426 }
427 
428 
429 /* Clean up after terminating process `p` (e.g. free the output buffer etc.). */
process_cleanup(process_info_t * p)430 void process_cleanup(process_info_t *p) {
431   fclose(p->stdout_file);
432   free(p->name);
433 }
434 
435 
436 /* Move the console cursor one line up and back to the first column. */
rewind_cursor(void)437 void rewind_cursor(void) {
438 #if defined(__MVS__)
439   fprintf(stderr, "\047[2K\r");
440 #else
441   fprintf(stderr, "\033[2K\r");
442 #endif
443 }
444