Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
ea3ec6e47a11aae0aec1e1516ace7f6bc5a8edbf
[simgrid.git] / tools / tesh / run_context.c
1 /* run_context -- stuff in which TESH runs a command                        */
2
3 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "tesh.h"
10
11 #include <signal.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <sys/stat.h>
15 #include <unistd.h>
16 #include <math.h>               /* floor */
17
18 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(tesh);
19
20 int fg_job = 0;
21 xbt_dynar_t bg_jobs = NULL;
22 rctx_t armageddon_initiator = NULL;
23 xbt_os_mutex_t armageddon_mutex = NULL;
24 struct {
25   int num;
26   struct sigaction act;
27 } oldact[3];                    /* SIGINT, SIGQUIT, SIGTERM */
28
29 xbt_os_thread_t sigwaiter_thread;
30 xbt_os_mutex_t sigwaiter_mutex;
31 xbt_os_cond_t sigwaiter_cond;
32 int armageddon_requested = 0;
33 int caught_signum = 0;
34
35 /*
36  * Module management
37  */
38
39 static void armageddon_sighandler(int signum)
40 {
41   xbt_os_mutex_acquire(sigwaiter_mutex);
42   caught_signum = signum;
43   armageddon_requested = 1;
44   xbt_os_cond_signal(sigwaiter_cond);
45   xbt_os_mutex_release(sigwaiter_mutex);
46 }
47
48 static void *armageddon_sigwaiter(_XBT_GNUC_UNUSED void *arg)
49 {
50   xbt_os_mutex_acquire(sigwaiter_mutex);
51   /* Inform main thread that it started. */
52   xbt_os_cond_signal(sigwaiter_cond);
53   /* Wait for ending signal... */
54   xbt_os_cond_wait(sigwaiter_cond, sigwaiter_mutex);
55   if (armageddon_requested) {
56     XBT_ERROR("Test suite `%s': caught signal %d", testsuite_name, caught_signum);
57     rctx_armageddon(rctx, 3);
58   }
59   xbt_os_mutex_release(sigwaiter_mutex);
60   return NULL;
61 }
62
63 static void wait_it(rctx_t rctx)
64 {
65   XBT_VERB("Join thread %p which were running background cmd <%s>",
66         rctx->runner, rctx->filepos);
67   xbt_os_thread_join(rctx->runner, NULL);
68 }
69
70 static void kill_it(void *r)
71 {
72   rctx_t rctx = *(rctx_t *) r;
73   wait_it(rctx);
74   rctx_free(rctx);
75 }
76
77 void rctx_init(void)
78 {
79   struct sigaction newact;
80   int i;
81   fg_job = 0;
82   bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
83   armageddon_mutex = xbt_os_mutex_init();
84   armageddon_initiator = NULL;
85   sigwaiter_mutex = xbt_os_mutex_init();
86   sigwaiter_cond = xbt_os_cond_init();
87   xbt_os_mutex_acquire(sigwaiter_mutex);
88   sigwaiter_thread = xbt_os_thread_create("Armaggedon request waiter",
89                                           armageddon_sigwaiter, NULL, NULL);
90   /* Wait for thread to start... */
91   xbt_os_cond_wait(sigwaiter_cond, sigwaiter_mutex);
92   xbt_os_mutex_release(sigwaiter_mutex);
93   memset(&newact, 0, sizeof(newact));
94   newact.sa_handler = armageddon_sighandler;
95   oldact[0].num = SIGINT;
96   oldact[1].num = SIGQUIT;
97   oldact[2].num = SIGTERM;
98   for (i = 0; i < 3; i++)
99     sigaction(oldact[i].num, &newact, &oldact[i].act);
100 }
101
102 void rctx_exit(void)
103 {
104   int i;
105   for (i = 0; i < 3; i++)
106     sigaction(oldact[i].num, &oldact[i].act, NULL);
107   xbt_os_cond_signal(sigwaiter_cond);
108   xbt_os_thread_join(sigwaiter_thread, NULL);
109   xbt_dynar_free(&bg_jobs);
110   xbt_os_cond_destroy(sigwaiter_cond);
111   xbt_os_mutex_destroy(sigwaiter_mutex);
112   xbt_os_mutex_destroy(armageddon_mutex);
113 }
114
115 void rctx_wait_bg(void)
116 {
117   /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon
118    * from working */
119   while (!xbt_dynar_is_empty(bg_jobs)) {
120     rctx_t rctx = xbt_dynar_getlast_as(bg_jobs, rctx_t);
121     wait_it(rctx);
122     xbt_dynar_pop(bg_jobs, &rctx);
123     rctx_free(rctx);
124   }
125   xbt_dynar_reset(bg_jobs);
126 }
127
128 static void rctx_armageddon_kill_one(rctx_t initiator, const char *filepos,
129                                      rctx_t rctx)
130 {
131   if (rctx != initiator) {
132     XBT_INFO("Kill <%s> because <%s> failed", rctx->filepos, filepos);
133     xbt_os_mutex_acquire(rctx->interruption);
134     if (!rctx->reader_done) {
135       rctx->interrupted = 1;
136       kill(rctx->pid, SIGTERM);
137       struct timespec ts;
138       ts.tv_sec = 0;
139       ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
140       nanosleep (&ts, NULL);
141       kill(rctx->pid, SIGKILL);
142     }
143     xbt_os_mutex_release(rctx->interruption);
144   }
145 }
146
147 void rctx_armageddon(rctx_t initiator, int exitcode)
148 {
149   unsigned int cursor;
150   rctx_t job;
151   const char *filepos = initiator && initiator->filepos ?
152       initiator->filepos : "(master)";
153
154   XBT_DEBUG("Armageddon request by <%s> (exit=%d)", filepos, exitcode);
155   xbt_os_mutex_acquire(armageddon_mutex);
156   if (armageddon_initiator != NULL) {
157     XBT_VERB("Armageddon already started. Let it go");
158     xbt_os_mutex_release(armageddon_mutex);
159     return;
160   }
161   XBT_DEBUG("Armageddon request by <%s> got the lock. Let's go amok",
162          filepos);
163   armageddon_initiator = initiator;
164   xbt_os_mutex_release(armageddon_mutex);
165
166   /* Kill foreground command */
167   if (fg_job)
168     rctx_armageddon_kill_one(initiator, filepos, rctx);
169
170   /* Kill any background commands */
171   xbt_dynar_foreach(bg_jobs, cursor, job) {
172     rctx_armageddon_kill_one(initiator, filepos, job);
173   }
174
175   /* Give runner threads a chance to acknowledge the processes deaths */
176   struct timespec ts;
177   ts.tv_sec = 0;
178   ts.tv_nsec = (10000e-6 - floor(10000e-6)) * 1e9;
179   nanosleep (&ts, NULL);
180   /* Ensure that nobody is running rctx_wait on exit */
181   if (fg_job)
182     xbt_os_mutex_acquire(rctx->interruption);
183   xbt_dynar_foreach(bg_jobs, cursor, job)
184     xbt_os_mutex_acquire(job->interruption);
185   XBT_VERB("Shut everything down!");
186   exit(exitcode);
187 }
188
189 /*
190  * Memory management
191  */
192
193 void rctx_empty(rctx_t rc)
194 {
195   int i;
196   char **env_it;
197   void *filepos;
198
199   free(rc->cmd);
200   rc->cmd = NULL;
201   /* avoid race with rctx_armageddon log messages */
202   filepos = rc->filepos;
203   rc->filepos = NULL;
204   free(filepos);
205   for (i = 0, env_it = environ; *env_it; i++, env_it++);
206   if (rc->env) {
207     for (env_it = rctx->env + i; *env_it; env_it++)
208       free(*env_it);
209     free(rc->env);
210   }
211   rc->env_size = i + 1;
212   rc->env = malloc(rc->env_size * sizeof(char *));
213   memcpy(rc->env, environ, rc->env_size * sizeof(char *));
214
215   rc->is_empty = 1;
216   rc->is_background = 0;
217   rc->is_stoppable = 0;
218   rc->output = e_output_check;
219   rc->output_sort = 0;
220   rc->brokenpipe = 0;
221   rc->timeout = 0;
222   rc->interrupted = 0;
223   xbt_strbuff_empty(rc->input);
224   xbt_strbuff_empty(rc->output_wanted);
225   xbt_strbuff_empty(rc->output_got);
226 }
227
228
229 rctx_t rctx_new()
230 {
231   rctx_t res = xbt_new0(s_rctx_t, 1);
232
233   res->input = xbt_strbuff_new();
234   res->output_sort = 0;
235   res->output_wanted = xbt_strbuff_new();
236   res->output_got = xbt_strbuff_new();
237   res->interruption = xbt_os_mutex_init();
238   rctx_empty(res);
239   return res;
240 }
241
242 void rctx_free(rctx_t rctx)
243 {
244   XBT_DEBUG("RCTX: Free %p", rctx);
245   rctx_dump(rctx, "free");
246   if (!rctx)
247     return;
248
249   free(rctx->cmd);
250   free(rctx->filepos);
251   if (rctx->env) {
252     int i;
253     char **env_it;
254     for (i = 0, env_it = environ; *env_it; i++, env_it++);
255     for (env_it = rctx->env + i; *env_it; env_it++)
256       free(*env_it);
257     free(rctx->env);
258   }
259   xbt_os_mutex_destroy(rctx->interruption);
260   xbt_strbuff_free(rctx->input);
261   xbt_strbuff_free(rctx->output_got);
262   xbt_strbuff_free(rctx->output_wanted);
263   free(rctx);
264 }
265
266 void rctx_dump(rctx_t rctx, const char *str)
267 {
268   XBT_DEBUG("%s RCTX %p={in%p={%d,%10s}, want={%d,%10s}, out={%d,%10s}}",
269          str, rctx,
270          rctx->input, rctx->input->used, rctx->input->data,
271          rctx->output_wanted->used, rctx->output_wanted->data,
272          rctx->output_got->used, rctx->output_got->data);
273   XBT_DEBUG("%s RCTX %p=[cmd%p=%10s, pid=%d]",
274          str, rctx, rctx->cmd, rctx->cmd, rctx->pid);
275
276 }
277
278 /*
279  * Getting instructions from the file
280  */
281
282 void rctx_pushline(const char *filepos, char kind, char *line)
283 {
284
285   switch (kind) {
286   case '$':
287   case '&':
288     if (rctx->cmd) {
289       if (!rctx->is_empty) {
290         XBT_ERROR
291             ("[%s] More than one command in this chunk of lines (previous: %s).\n"
292              " Cannot guess which input/output belongs to which command.",
293              filepos, rctx->cmd);
294         XBT_ERROR("Test suite `%s': NOK (syntax error)", testsuite_name);
295         rctx_armageddon(rctx, 1);
296         return;
297       }
298       rctx_start();
299       XBT_VERB("[%s] More than one command in this chunk of lines", filepos);
300     }
301     if (kind == '&')
302       rctx->is_background = 1;
303     else
304       rctx->is_background = 0;
305
306     rctx->cmd = xbt_strdup(line);
307     rctx->filepos = xbt_strdup(filepos);
308     if (option){
309       char *newcmd = bprintf("%s %s", rctx->cmd, option);
310       free(rctx->cmd);
311       rctx->cmd = newcmd;
312     }
313     XBT_INFO("[%s] %s%s", filepos, rctx->cmd,
314           ((rctx->is_background) ? " (background command)" : ""));
315
316     break;
317
318   case '<':
319     rctx->is_empty = 0;
320     xbt_strbuff_append(rctx->input, line);
321     xbt_strbuff_append(rctx->input, "\n");
322     break;
323
324   case '>':
325     rctx->is_empty = 0;
326     xbt_strbuff_append(rctx->output_wanted, line);
327     xbt_strbuff_append(rctx->output_wanted, "\n");
328     break;
329
330   case '!':
331     if (rctx->cmd)
332       rctx_start();
333
334     if (!strncmp(line, "timeout no", strlen("timeout no"))) {
335       XBT_VERB("[%s] (disable timeout)", filepos);
336       timeout_value = -1;
337     } else if (!strncmp(line, "timeout ", strlen("timeout "))) {
338       timeout_value = atoi(line + strlen("timeout"));
339       XBT_VERB("[%s] (new timeout value: %d)", filepos, timeout_value);
340
341     } else if (!strncmp(line, "expect signal ", strlen("expect signal "))) {
342       rctx->expected_signal = strdup(line + strlen("expect signal "));
343       xbt_str_trim(rctx->expected_signal, " \n");
344       XBT_VERB("[%s] (next command must raise signal %s)",
345             filepos, rctx->expected_signal);
346
347     } else if (!strncmp(line, "expect return ", strlen("expect return "))) {
348       rctx->expected_return = atoi(line + strlen("expect return "));
349       XBT_VERB("[%s] (next command must return code %d)",
350             filepos, rctx->expected_return);
351
352     } else if (!strncmp(line, "output sort", strlen("output sort"))) {
353       sort_len = atoi(line + strlen("output sort"));
354       if (sort_len==0)
355         sort_len=SORT_LEN_DEFAULT;
356       rctx->output_sort = 1;
357       XBT_VERB("[%s] (sort output of next command)", filepos);
358
359     } else if (!strncmp(line, "output ignore", strlen("output ignore"))) {
360       rctx->output = e_output_ignore;
361       XBT_VERB("[%s] (ignore output of next command)", filepos);
362
363     } else if (!strncmp(line, "output display", strlen("output display"))) {
364       rctx->output = e_output_display;
365       XBT_VERB("[%s] (ignore output of next command)", filepos);
366
367     } else if (!strncmp(line, "setenv ", strlen("setenv "))) {
368       int len = strlen("setenv ");
369       char *eq = strchr(line + len, '=');
370       char *key = bprintf("%.*s", (int) (eq - line - len), line + len);
371       xbt_dict_set(env, key, xbt_strdup(eq + 1), NULL);
372       free(key);
373
374       rctx->env = realloc(rctx->env, ++(rctx->env_size) * sizeof(char *));
375       rctx->env[rctx->env_size - 2] = xbt_strdup(line + len);
376       rctx->env[rctx->env_size - 1] = NULL;
377       XBT_VERB("[%s] setenv %s", filepos, line + len);
378
379     } else {
380       XBT_ERROR("%s: Malformed metacommand: %s", filepos, line);
381       XBT_ERROR("Test suite `%s': NOK (syntax error)", testsuite_name);
382       rctx_armageddon(rctx, 1);
383       return;
384     }
385     break;
386   }
387 }
388
389 /*
390  * Actually doing the job
391  */
392
393 /* The IO of the childs are handled by the two following threads
394    (one pair per child) */
395
396 static void *thread_writer(void *r)
397 {
398   int posw;
399   rctx_t rctx = (rctx_t) r;
400   for (posw = 0; posw < rctx->input->used && !rctx->brokenpipe;) {
401     int got;
402     XBT_DEBUG("Still %d chars to write", rctx->input->used - posw);
403     got =
404         write(rctx->child_to, rctx->input->data + posw,
405               rctx->input->used - posw);
406     if (got > 0)
407       posw += got;
408     if (got < 0) {
409       if (errno == EPIPE) {
410         rctx->brokenpipe = 1;
411       } else if (errno != EINTR && errno != EAGAIN && errno != EPIPE) {
412         perror("Error while writing input to child");
413         XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
414         rctx_armageddon(rctx, 4);
415         return NULL;
416       }
417     }
418     XBT_DEBUG("written %d chars so far", posw);
419
420     if (got <= 0){
421       struct timespec ts;
422       ts.tv_sec = 0;
423       ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
424       nanosleep (&ts, NULL);
425     }
426   }
427   rctx->input->data[0] = '\0';
428   rctx->input->used = 0;
429   close(rctx->child_to);
430
431   return NULL;
432 }
433
434 static void *thread_reader(void *r)
435 {
436   rctx_t rctx = (rctx_t) r;
437   char *buffout = malloc(4096);
438   int posr, got_pid;
439
440   do {
441     posr = read(rctx->child_from, buffout, 4095);
442     if (posr < 0 && errno != EINTR && errno != EAGAIN) {
443       perror("Error while reading output of child");
444       XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
445       rctx_armageddon(rctx, 4);
446       return NULL;
447     }
448     if (posr > 0) {
449       buffout[posr] = '\0';
450       xbt_strbuff_append(rctx->output_got, buffout);
451     } else {
452       struct timespec ts;
453       ts.tv_sec = 0;
454       ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
455       nanosleep (&ts, NULL);
456     }
457   } while (!rctx->timeout && posr != 0);
458   free(buffout);
459
460   /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
461   got_pid = waitpid(rctx->pid, &rctx->status, 0);
462   if (got_pid != rctx->pid) {
463     perror(bprintf
464            ("(%s) Cannot wait for the child %s (got pid %d where pid %d were expected;status=%d)",
465             xbt_thread_self_name(), rctx->cmd, (int) got_pid,
466             (int) rctx->pid, rctx->status));
467     XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
468     rctx_armageddon(rctx, 4);
469     return NULL;
470   }
471
472   rctx->reader_done = 1;
473   return NULL;
474 }
475
476 /* Special command: mkfile is a built-in creating a file with the input data as content */
477 static void rctx_mkfile(void)
478 {
479   char *filename = xbt_strdup(rctx->cmd + strlen("mkfile "));
480   FILE *OUT;
481   int err;
482   xbt_str_trim(filename, NULL);
483   OUT = fopen(filename, "w");
484   if (!OUT) {
485     THROWF(system_error, errno, "%s: Cannot create file %s: %s",
486            rctx->filepos, filename, strerror(errno));
487   }
488   err = (fprintf(OUT, "%s", rctx->input->data) < 0);
489   err = (fclose(OUT) == -1) || err;
490   if (err) {
491     THROWF(system_error, errno, "%s: Cannot write file %s: %s",
492            rctx->filepos, filename, strerror(errno));
493   }
494   free(filename);
495 }
496
497 /* function to be called from the child to start the actual process */
498 static void start_command(rctx_t rctx)
499 {
500   xbt_dynar_t cmd;
501   char *binary_name = NULL;
502   unsigned int it;
503   char *str;
504   char **args;
505   int errcode;
506
507   if (!strncmp(rctx->cmd, "mkfile ", strlen("mkfile "))) {
508     rctx_mkfile();
509     /* Valgrind detects memory leaks here.
510      * To correct those leaks, we must free objects allocated in main() or in
511      * handle_suite(), but we have no more reference to them at this point.
512      * A quick and dirty hack to make valgrind happy it to uncomment the
513      * following line.
514      */
515     /* execlp("true", "true", (const char *)0); */
516     exit(0);                    /* end the working child */
517   }
518
519   cmd = xbt_str_split_quoted(rctx->cmd);
520   xbt_dynar_get_cpy(cmd, 0, &binary_name);
521   args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
522   xbt_dynar_foreach(cmd, it, str) {
523     args[it] = xbt_strdup(str);
524   }
525   args[it] = NULL;
526   xbt_dynar_free_container(&cmd);
527
528   /* To search for the right executable path when not trivial */
529   struct stat stat_buf;
530
531   /* build the command line */
532   if (stat(binary_name, &stat_buf)) {
533     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
534     int i;
535
536     for (i = 0; environ[i]; i++) {
537       if (!strncmp("PATH=", environ[i], 5)) {
538         xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
539
540         xbt_dynar_foreach(path, it, str) {
541           free(binary_name);
542           binary_name = bprintf("%s/%s", str, args[0]);
543           if (!stat(binary_name, &stat_buf)) {
544             /* Found. */
545             XBT_DEBUG("Looked in the PATH for the binary. Found %s",
546                    binary_name);
547             xbt_dynar_free(&path);
548             break;
549           }
550         }
551         xbt_dynar_free(&path);
552         if (stat(binary_name, &stat_buf)) {
553           /* not found */
554           printf("TESH_ERROR Command %s not found\n", args[0]);
555           exit(127);
556         }
557         break;
558       }
559     }
560   } else {
561     binary_name = xbt_strdup(args[0]);
562   }
563
564   errcode = execve(binary_name, args, rctx->env);
565   printf("TESH_ERROR %s: Cannot start %s: %s\n", rctx->filepos, rctx->cmd,
566          strerror(errcode));
567   exit(127);
568 }
569
570 /* Start a new child, plug the pipes as expected and fire up the
571    helping threads. Is also waits for the child to end if this is a
572    foreground job, or fire up a thread to wait otherwise. */
573 void rctx_start(void)
574 {
575   int child_in[2];
576   int child_out[2];
577
578   XBT_DEBUG("Cmd before rewriting %s", rctx->cmd);
579   char *newcmd = xbt_str_varsubst(rctx->cmd, env);
580   free(rctx->cmd);
581   rctx->cmd = newcmd;
582   XBT_VERB("Start %s %s", rctx->cmd,
583         (rctx->is_background ? "(background job)" : ""));
584   xbt_os_mutex_acquire(armageddon_mutex);
585   if (armageddon_initiator) {
586     XBT_VERB("Armageddon in progress. Do not start job.");
587     xbt_os_mutex_release(armageddon_mutex);
588     return;
589   }
590   if (pipe(child_in) || pipe(child_out)) {
591     perror("Cannot open the pipes");
592     XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
593     xbt_os_mutex_release(armageddon_mutex);
594     rctx_armageddon(rctx, 4);
595   }
596
597   rctx->pid = fork();
598   if (rctx->pid < 0) {
599     perror("Cannot fork the command");
600     XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
601     xbt_os_mutex_release(armageddon_mutex);
602     rctx_armageddon(rctx, 4);
603     return;
604   }
605
606   if (rctx->pid) {              /* father */
607     close(child_in[0]);
608     rctx->child_to = child_in[1];
609
610     close(child_out[1]);
611     rctx->child_from = child_out[0];
612
613     if (timeout_value > 0)
614       rctx->end_time = time(NULL) + timeout_value;
615     else
616       rctx->end_time = -1;
617
618     rctx->reader_done = 0;
619     rctx->reader =
620         xbt_os_thread_create("reader", thread_reader, (void *) rctx, NULL);
621     rctx->writer =
622         xbt_os_thread_create("writer", thread_writer, (void *) rctx, NULL);
623
624   } else {                      /* child */
625     close(child_in[1]);
626     dup2(child_in[0], 0);
627     close(child_in[0]);
628
629     close(child_out[0]);
630     dup2(child_out[1], 1);
631     dup2(child_out[1], 2);
632     close(child_out[1]);
633
634     start_command(rctx);
635   }
636
637   rctx->is_stoppable = 1;
638
639   if (!rctx->is_background) {
640     fg_job = 1;
641     xbt_os_mutex_release(armageddon_mutex);
642     rctx_wait(rctx);
643     fg_job = 0;
644   } else {
645     /* Damn. Copy the rctx and launch a thread to handle it */
646     rctx_t old = rctx;
647     xbt_os_thread_t runner;
648
649     rctx = rctx_new();
650     XBT_DEBUG("RCTX: new bg=%p, new fg=%p", old, rctx);
651
652     XBT_DEBUG("Launch a thread to wait for %s %d", old->cmd, old->pid);
653     runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old, NULL);
654     old->runner = runner;
655     XBT_VERB("Launched thread %p to wait for %s %d", runner, old->cmd,
656           old->pid);
657     xbt_dynar_push(bg_jobs, &old);
658     xbt_os_mutex_release(armageddon_mutex);
659   }
660 }
661
662 /* Helper function to sort the output */
663 static int cmpstringp(const void *p1, const void *p2) {
664   /* Sort only using the sort_len first chars
665    * If they are the same, then, sort using pointer address
666    * (be stable wrt output of each process)
667    */
668   const char **s1 = *(const char***)p1;
669   const char **s2 = *(const char***)p2;
670
671   XBT_DEBUG("Compare strings '%s' and '%s'", *s1, *s2);
672
673   int res = strncmp(*s1, *s2, sort_len);
674   if (res == 0)
675     res = s1 > s2 ? 1 : (s1 < s2 ? -1 : 0);
676   return res;
677 }
678
679 static void stable_sort(xbt_dynar_t a)
680 {
681   unsigned long len = xbt_dynar_length(a);
682   void **b = xbt_new(void*, len);
683   unsigned long i;
684   for (i = 0 ; i < len ; i++)   /* fill the array b with pointers to strings */
685     b[i] = xbt_dynar_get_ptr(a, i);
686   qsort(b, len, sizeof *b, cmpstringp); /* sort it */
687   for (i = 0 ; i < len ; i++) /* dereference the pointers to get the strings */
688     b[i] = *(char**)b[i];
689   for (i = 0 ; i < len ; i++)   /* put everything in place */
690     xbt_dynar_set_as(a, i, char*, b[i]);
691   xbt_free(b);
692 }
693
694 /* Waits for the child to end (or to timeout), and check its
695    ending conditions. This is launched from rctx_start but either in main
696    thread (for foreground jobs) or in a separate one for background jobs.
697    That explains the prototype, forced by xbt_os_thread_create. */
698
699 void *rctx_wait(void *r)
700 {
701   rctx_t rctx = (rctx_t) r;
702   int errcode = 0;
703   int now = time(NULL);
704
705   rctx_dump(rctx, "wait");
706
707   if (!rctx->is_stoppable)
708     THROWF(unknown_error, 0, "Cmd '%s' not started yet. Cannot wait it",
709            rctx->cmd);
710
711   /* Wait for the child to die or the timeout to happen (or an armageddon to happen) */
712   while (!rctx->reader_done
713          && (rctx->end_time < 0 || rctx->end_time >= now)) {
714     struct timespec ts;
715     ts.tv_sec = 0;
716     ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
717     nanosleep (&ts, NULL);
718     now = time(NULL);
719   }
720
721   xbt_os_mutex_acquire(rctx->interruption);
722   if (!rctx->interrupted && rctx->end_time > 0 && rctx->end_time < now) {
723     XBT_INFO("<%s> timeouted. Kill the process.", rctx->filepos);
724     rctx->timeout = 1;
725     kill(rctx->pid, SIGTERM);
726     struct timespec ts;
727     ts.tv_sec = 0;
728     ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
729     nanosleep (&ts, NULL);
730     kill(rctx->pid, SIGKILL);
731   }
732
733   /* Make sure helper threads die.
734      Cannot block since they wait for the child we just killed
735      if not already dead. */
736   xbt_os_thread_join(rctx->writer, NULL);
737   xbt_os_thread_join(rctx->reader, NULL);
738
739   /*  xbt_os_mutex_release(rctx->interruption);
740      if (rctx->interrupted)
741      return NULL;
742      xbt_os_mutex_acquire(rctx->interruption); */
743
744   {
745     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
746     xbt_dynar_t b = xbt_dynar_new(sizeof(char *), NULL);
747     unsigned cpt;
748     char *str;
749     xbt_dynar_foreach(a, cpt, str) {
750       if (strncmp(str, "TESH_ERROR ", (sizeof "TESH_ERROR ") - 1) == 0) {
751         XBT_CRITICAL("%s", str);
752         errcode = 1;
753       } else if (coverage &&
754                  strncmp(str, "profiling:", (sizeof "profiling:") - 1) == 0) {
755         XBT_DEBUG("Remove line [%u]: '%s'", cpt, str);
756       } else {
757         xbt_dynar_push_as(b, char *, str);
758       }
759     }
760
761     if (rctx->output_sort) {
762       stable_sort(b);
763       /* If empty lines moved in first position, remove them */
764       while (!xbt_dynar_is_empty(b) && *xbt_dynar_getfirst_as(b, char*) == '\0')
765         xbt_dynar_shift(b, NULL);
766     }
767
768     if (rctx->output_sort || xbt_dynar_length(b) != xbt_dynar_length(a)) {
769       char *newbuf = xbt_str_join(b, "\n");
770       strcpy(rctx->output_got->data, newbuf);
771       rctx->output_got->used = strlen(newbuf);
772       xbt_free(newbuf);
773     }
774
775     xbt_dynar_free(&b);
776     xbt_dynar_free(&a);
777   }
778
779   xbt_strbuff_chomp(rctx->output_got);
780   xbt_strbuff_chomp(rctx->output_wanted);
781   xbt_strbuff_trim(rctx->output_got);
782   xbt_strbuff_trim(rctx->output_wanted);
783
784   /* Check for broken pipe */
785   if (rctx->brokenpipe)
786     XBT_VERB
787         ("Warning: Child did not consume all its input (I got broken pipe)");
788
789   /* Check for timeouts */
790   if (rctx->timeout) {
791     if (rctx->output_got->data[0])
792       XBT_INFO("<%s> Output on timeout:\n%s",
793             rctx->filepos, rctx->output_got->data);
794     else
795       XBT_INFO("<%s> No output before timeout", rctx->filepos);
796     XBT_ERROR("Test suite `%s': NOK (<%s> timeout after %d sec)",
797            testsuite_name, rctx->filepos, timeout_value);
798     XBT_DEBUG("<%s> Interrupted = %d", rctx->filepos, (int)rctx->interrupted);
799     if (!rctx->interrupted) {
800       xbt_os_mutex_release(rctx->interruption);
801       rctx_armageddon(rctx, 3);
802       return NULL;
803     }
804   }
805
806   XBT_DEBUG("RCTX=%p (pid=%d)", rctx, rctx->pid);
807   XBT_DEBUG("Status(%s|%d)=%d", rctx->cmd, rctx->pid, rctx->status);
808
809   if (!rctx->interrupted) {
810     if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
811       XBT_ERROR("Test suite `%s': NOK (<%s> got signal %s)",
812              testsuite_name, rctx->filepos,
813              signal_name(WTERMSIG(rctx->status), NULL));
814       errcode = WTERMSIG(rctx->status) + 4;
815     }
816
817     if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
818         strcmp(signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
819                rctx->expected_signal)) {
820       XBT_ERROR("Test suite `%s': NOK (%s got signal %s instead of %s)",
821              testsuite_name, rctx->filepos,
822              signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
823              rctx->expected_signal);
824       errcode = WTERMSIG(rctx->status) + 4;
825     }
826
827     if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
828       XBT_ERROR("Test suite `%s': NOK (child %s expected signal %s)",
829              testsuite_name, rctx->filepos, rctx->expected_signal);
830       errcode = 5;
831     }
832
833     if (WIFEXITED(rctx->status)
834         && WEXITSTATUS(rctx->status) != rctx->expected_return) {
835       if (rctx->expected_return)
836         XBT_ERROR
837             ("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
838              testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status),
839              rctx->expected_return);
840       else
841         XBT_ERROR("Test suite `%s': NOK (<%s> returned code %d)",
842                testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
843       errcode = 40 + WEXITSTATUS(rctx->status);
844
845     }
846     rctx->expected_return = 0;
847
848     free(rctx->expected_signal);
849     rctx->expected_signal = NULL;
850   }
851
852   if ((errcode && errcode != 1) || rctx->interrupted) {
853     /* checking output, and matching */
854     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
855     char *out = xbt_str_join(a, "\n||");
856     xbt_dynar_free(&a);
857     XBT_INFO("Output of <%s> so far: \n||%s", rctx->filepos, out);
858     free(out);
859   } else if (rctx->output == e_output_check
860              && (rctx->output_got->used != rctx->output_wanted->used
861                  || strcmp(rctx->output_got->data,
862                            rctx->output_wanted->data))) {
863     if (XBT_LOG_ISENABLED(tesh, xbt_log_priority_info)) {
864       char *diff =
865           xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
866       XBT_ERROR("Output of <%s> mismatch:\n%s", rctx->filepos, diff);
867       free(diff);
868     }
869     XBT_ERROR("Test suite `%s': NOK (<%s> output mismatch)",
870            testsuite_name, rctx->filepos);
871
872     errcode = 2;
873   } else if (rctx->output == e_output_ignore) {
874     XBT_INFO("(ignoring the output of <%s> as requested)", rctx->filepos);
875   } else if (rctx->output == e_output_display) {
876     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
877     char *out = xbt_str_join(a, "\n||");
878     xbt_dynar_free(&a);
879     XBT_INFO("Here is the (ignored) command output: \n||%s", out);
880     free(out);
881   }
882
883   if (!rctx->is_background) {
884     xbt_os_mutex_acquire(armageddon_mutex);
885     /* Don't touch rctx if armageddon is in progress. */
886     if (!armageddon_initiator)
887       rctx_empty(rctx);
888     xbt_os_mutex_release(armageddon_mutex);
889   }
890   if (errcode) {
891     if (!rctx->interrupted) {
892       xbt_os_mutex_release(rctx->interruption);
893       rctx_armageddon(rctx, errcode);
894       return NULL;
895     }
896   }
897
898   xbt_os_mutex_release(rctx->interruption);
899   return NULL;
900 }