Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'hypervisor' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid into hypervisor
[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(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     XBT_DEBUG("wanted:%s",rctx->output_wanted->data);
329     break;
330
331   case '!':
332     if (rctx->cmd)
333       rctx_start();
334
335     if (!strncmp(line, "timeout no", strlen("timeout no"))) {
336       XBT_VERB("[%s] (disable timeout)", filepos);
337       timeout_value = -1;
338     } else if (!strncmp(line, "timeout ", strlen("timeout "))) {
339       timeout_value = atoi(line + strlen("timeout"));
340       XBT_VERB("[%s] (new timeout value: %d)", filepos, timeout_value);
341
342     } else if (!strncmp(line, "expect signal ", strlen("expect signal "))) {
343       rctx->expected_signal = strdup(line + strlen("expect signal "));
344       xbt_str_trim(rctx->expected_signal, " \n");
345       XBT_VERB("[%s] (next command must raise signal %s)",
346             filepos, rctx->expected_signal);
347
348     } else if (!strncmp(line, "expect return ", strlen("expect return "))) {
349       rctx->expected_return = atoi(line + strlen("expect return "));
350       XBT_VERB("[%s] (next command must return code %d)",
351             filepos, rctx->expected_return);
352
353     } else if (!strncmp(line, "output sort", strlen("output sort"))) {
354       sort_len = atoi(line + strlen("output sort"));
355       if (sort_len==0)
356         sort_len=SORT_LEN_DEFAULT;
357       rctx->output_sort = 1;
358       XBT_VERB("[%s] (sort output of next command)", filepos);
359
360     } else if (!strncmp(line, "output ignore", strlen("output ignore"))) {
361       rctx->output = e_output_ignore;
362       XBT_VERB("[%s] (ignore output of next command)", filepos);
363
364     } else if (!strncmp(line, "output display", strlen("output display"))) {
365       rctx->output = e_output_display;
366       XBT_VERB("[%s] (ignore output of next command)", filepos);
367
368     } else if (!strncmp(line, "setenv ", strlen("setenv "))) {
369       int len = strlen("setenv ");
370       char *eq = strchr(line + len, '=');
371       char *key = bprintf("%.*s", (int) (eq - line - len), line + len);
372       xbt_dict_set(env, key, xbt_strdup(eq + 1), NULL);
373       free(key);
374
375       rctx->env = realloc(rctx->env, ++(rctx->env_size) * sizeof(char *));
376       rctx->env[rctx->env_size - 2] = xbt_strdup(line + len);
377       rctx->env[rctx->env_size - 1] = NULL;
378       XBT_VERB("[%s] setenv %s", filepos, line + len);
379
380     } else {
381       XBT_ERROR("%s: Malformed metacommand: %s", filepos, line);
382       XBT_ERROR("Test suite `%s': NOK (syntax error)", testsuite_name);
383       rctx_armageddon(rctx, 1);
384       return;
385     }
386     break;
387   }
388 }
389
390 /*
391  * Actually doing the job
392  */
393
394 /* The IO of the childs are handled by the two following threads
395    (one pair per child) */
396
397 static void *thread_writer(void *r)
398 {
399   int posw;
400   rctx_t rctx = (rctx_t) r;
401   for (posw = 0; posw < rctx->input->used && !rctx->brokenpipe;) {
402     int got;
403     XBT_DEBUG("Still %d chars to write", rctx->input->used - posw);
404     got =
405         write(rctx->child_to, rctx->input->data + posw,
406               rctx->input->used - posw);
407     if (got > 0)
408       posw += got;
409     if (got < 0) {
410       if (errno == EPIPE) {
411         rctx->brokenpipe = 1;
412       } else if (errno != EINTR && errno != EAGAIN && errno != EPIPE) {
413         perror("Error while writing input to child");
414         XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
415         rctx_armageddon(rctx, 4);
416         return NULL;
417       }
418     }
419     XBT_DEBUG("written %d chars so far", posw);
420
421     if (got <= 0){
422       struct timespec ts;
423       ts.tv_sec = 0;
424       ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
425       nanosleep (&ts, NULL);
426     }
427   }
428   rctx->input->data[0] = '\0';
429   rctx->input->used = 0;
430   close(rctx->child_to);
431
432   return NULL;
433 }
434
435 static void *thread_reader(void *r)
436 {
437   rctx_t rctx = (rctx_t) r;
438   char *buffout = malloc(4096);
439   int posr, got_pid;
440
441   do {
442     posr = read(rctx->child_from, buffout, 4095);
443     if (posr < 0 && errno != EINTR && errno != EAGAIN) {
444       perror("Error while reading output of child");
445       XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
446       rctx_armageddon(rctx, 4);
447       return NULL;
448     }
449     if (posr > 0) {
450       buffout[posr] = '\0';
451       xbt_strbuff_append(rctx->output_got, buffout);
452     } else {
453       struct timespec ts;
454       ts.tv_sec = 0;
455       ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
456       nanosleep (&ts, NULL);
457     }
458   } while (!rctx->timeout && posr != 0);
459   free(buffout);
460
461   /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
462   got_pid = waitpid(rctx->pid, &rctx->status, 0);
463   if (got_pid != rctx->pid) {
464     perror(bprintf
465            ("(%s) Cannot wait for the child %s (got pid %d where pid %d were expected;status=%d)",
466             xbt_thread_self_name(), rctx->cmd, (int) got_pid,
467             (int) rctx->pid, rctx->status));
468     XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
469     rctx_armageddon(rctx, 4);
470     return NULL;
471   }
472
473   rctx->reader_done = 1;
474   return NULL;
475 }
476
477 /* Special command: mkfile is a built-in creating a file with the input data as content */
478 static void rctx_mkfile(void)
479 {
480   char *filename = xbt_strdup(rctx->cmd + strlen("mkfile "));
481   FILE *OUT;
482   int err;
483   xbt_str_trim(filename, NULL);
484   OUT = fopen(filename, "w");
485   if (!OUT) {
486     THROWF(system_error, errno, "%s: Cannot create file %s: %s",
487            rctx->filepos, filename, strerror(errno));
488   }
489   err = (fprintf(OUT, "%s", rctx->input->data) < 0);
490   err = (fclose(OUT) == -1) || err;
491   if (err) {
492     THROWF(system_error, errno, "%s: Cannot write file %s: %s",
493            rctx->filepos, filename, strerror(errno));
494   }
495   free(filename);
496 }
497
498 /* function to be called from the child to start the actual process */
499 static void start_command(rctx_t rctx)
500 {
501   xbt_dynar_t cmd;
502   char *binary_name = NULL;
503   unsigned int it;
504   char *str;
505   char **args;
506   int errcode;
507
508   if (!strncmp(rctx->cmd, "mkfile ", strlen("mkfile "))) {
509     rctx_mkfile();
510     /* Valgrind detects memory leaks here.
511      * To correct those leaks, we must free objects allocated in main() or in
512      * handle_suite(), but we have no more reference to them at this point.
513      * A quick and dirty hack to make valgrind happy it to uncomment the
514      * following line.
515      */
516     /* execlp("true", "true", (const char *)0); */
517     exit(0);                    /* end the working child */
518   }
519
520   cmd = xbt_str_split_quoted(rctx->cmd);
521   xbt_dynar_get_cpy(cmd, 0, &binary_name);
522   args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
523   xbt_dynar_foreach(cmd, it, str) {
524     args[it] = xbt_strdup(str);
525   }
526   args[it] = NULL;
527   xbt_dynar_free_container(&cmd);
528
529   /* To search for the right executable path when not trivial */
530   struct stat stat_buf;
531
532   /* build the command line */
533   if (stat(binary_name, &stat_buf)) {
534     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
535     int i;
536
537     for (i = 0; environ[i]; i++) {
538       if (!strncmp("PATH=", environ[i], 5)) {
539         xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
540
541         xbt_dynar_foreach(path, it, str) {
542           free(binary_name);
543           binary_name = bprintf("%s/%s", str, args[0]);
544           if (!stat(binary_name, &stat_buf)) {
545             /* Found. */
546             XBT_DEBUG("Looked in the PATH for the binary. Found %s",
547                    binary_name);
548             xbt_dynar_free(&path);
549             break;
550           }
551         }
552         xbt_dynar_free(&path);
553         if (stat(binary_name, &stat_buf)) {
554           /* not found */
555           printf("TESH_ERROR Command %s not found\n", args[0]);
556           exit(127);
557         }
558         break;
559       }
560     }
561   } else {
562     binary_name = xbt_strdup(args[0]);
563   }
564
565   errcode = execve(binary_name, args, rctx->env);
566   printf("TESH_ERROR %s: Cannot start %s: %s\n", rctx->filepos, rctx->cmd,
567          strerror(errcode));
568   exit(127);
569 }
570
571 /* Start a new child, plug the pipes as expected and fire up the
572    helping threads. Is also waits for the child to end if this is a
573    foreground job, or fire up a thread to wait otherwise. */
574 void rctx_start(void)
575 {
576   int child_in[2];
577   int child_out[2];
578
579   XBT_DEBUG("Cmd before rewriting %s", rctx->cmd);
580   char *newcmd = xbt_str_varsubst(rctx->cmd, env);
581   free(rctx->cmd);
582   rctx->cmd = newcmd;
583   XBT_VERB("Start %s %s", rctx->cmd,
584         (rctx->is_background ? "(background job)" : ""));
585   xbt_os_mutex_acquire(armageddon_mutex);
586   if (armageddon_initiator) {
587     XBT_VERB("Armageddon in progress. Do not start job.");
588     xbt_os_mutex_release(armageddon_mutex);
589     return;
590   }
591   if (pipe(child_in) || pipe(child_out)) {
592     perror("Cannot open the pipes");
593     XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
594     xbt_os_mutex_release(armageddon_mutex);
595     rctx_armageddon(rctx, 4);
596   }
597
598   rctx->pid = fork();
599   if (rctx->pid < 0) {
600     perror("Cannot fork the command");
601     XBT_ERROR("Test suite `%s': NOK (system error)", testsuite_name);
602     xbt_os_mutex_release(armageddon_mutex);
603     rctx_armageddon(rctx, 4);
604     return;
605   }
606
607   if (rctx->pid) {              /* father */
608     close(child_in[0]);
609     rctx->child_to = child_in[1];
610
611     close(child_out[1]);
612     rctx->child_from = child_out[0];
613
614     if (timeout_value > 0)
615       rctx->end_time = time(NULL) + timeout_value;
616     else
617       rctx->end_time = -1;
618
619     rctx->reader_done = 0;
620     rctx->reader =
621         xbt_os_thread_create("reader", thread_reader, (void *) rctx, NULL);
622     rctx->writer =
623         xbt_os_thread_create("writer", thread_writer, (void *) rctx, NULL);
624
625   } else {                      /* child */
626     close(child_in[1]);
627     dup2(child_in[0], 0);
628     close(child_in[0]);
629
630     close(child_out[0]);
631     dup2(child_out[1], 1);
632     dup2(child_out[1], 2);
633     close(child_out[1]);
634
635     start_command(rctx);
636   }
637
638   rctx->is_stoppable = 1;
639
640   if (!rctx->is_background) {
641     fg_job = 1;
642     xbt_os_mutex_release(armageddon_mutex);
643     rctx_wait(rctx);
644     fg_job = 0;
645   } else {
646     /* Damn. Copy the rctx and launch a thread to handle it */
647     rctx_t old = rctx;
648     xbt_os_thread_t runner;
649
650     rctx = rctx_new();
651     XBT_DEBUG("RCTX: new bg=%p, new fg=%p", old, rctx);
652
653     XBT_DEBUG("Launch a thread to wait for %s %d", old->cmd, old->pid);
654     runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old, NULL);
655     old->runner = runner;
656     XBT_VERB("Launched thread %p to wait for %s %d", runner, old->cmd,
657           old->pid);
658     xbt_dynar_push(bg_jobs, &old);
659     xbt_os_mutex_release(armageddon_mutex);
660   }
661 }
662
663 /* Helper function to sort the output */
664 static int cmpstringp(const void *p1, const void *p2) {
665   /* Sort only using the sort_len first chars
666    * If they are the same, then, sort using pointer address
667    * (be stable wrt output of each process)
668    */
669   const char **s1 = *(const char***)p1;
670   const char **s2 = *(const char***)p2;
671
672   XBT_DEBUG("Compare strings '%s' and '%s'", *s1, *s2);
673
674   int res = strncmp(*s1, *s2, sort_len);
675   if (res == 0)
676     res = s1 > s2 ? 1 : (s1 < s2 ? -1 : 0);
677   return res;
678 }
679
680 static void stable_sort(xbt_dynar_t a)
681 {
682   unsigned long len = xbt_dynar_length(a);
683   void **b = xbt_new(void*, len);
684   unsigned long i;
685   for (i = 0 ; i < len ; i++)   /* fill the array b with pointers to strings */
686     b[i] = xbt_dynar_get_ptr(a, i);
687   qsort(b, len, sizeof *b, cmpstringp); /* sort it */
688   for (i = 0 ; i < len ; i++) /* dereference the pointers to get the strings */
689     b[i] = *(char**)b[i];
690   for (i = 0 ; i < len ; i++)   /* put everything in place */
691     xbt_dynar_set_as(a, i, char*, b[i]);
692   xbt_free(b);
693 }
694
695 /* Waits for the child to end (or to timeout), and check its
696    ending conditions. This is launched from rctx_start but either in main
697    thread (for foreground jobs) or in a separate one for background jobs.
698    That explains the prototype, forced by xbt_os_thread_create. */
699
700 void *rctx_wait(void *r)
701 {
702   rctx_t rctx = (rctx_t) r;
703   int errcode = 0;
704   int now = time(NULL);
705
706   rctx_dump(rctx, "wait");
707
708   if (!rctx->is_stoppable)
709     THROWF(unknown_error, 0, "Cmd '%s' not started yet. Cannot wait it",
710            rctx->cmd);
711
712   /* Wait for the child to die or the timeout to happen (or an armageddon to happen) */
713   while (!rctx->reader_done
714          && (rctx->end_time < 0 || rctx->end_time >= now)) {
715     struct timespec ts;
716     ts.tv_sec = 0;
717     ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
718     nanosleep (&ts, NULL);
719     now = time(NULL);
720   }
721
722   xbt_os_mutex_acquire(rctx->interruption);
723   if (!rctx->interrupted && rctx->end_time > 0 && rctx->end_time < now) {
724     XBT_INFO("<%s> timeouted. Kill the process.", rctx->filepos);
725     rctx->timeout = 1;
726     kill(rctx->pid, SIGTERM);
727     struct timespec ts;
728     ts.tv_sec = 0;
729     ts.tv_nsec = (100e-6 - floor(100e-6)) * 1e9;
730     nanosleep (&ts, NULL);
731     kill(rctx->pid, SIGKILL);
732   }
733
734   /* Make sure helper threads die.
735      Cannot block since they wait for the child we just killed
736      if not already dead. */
737   xbt_os_thread_join(rctx->writer, NULL);
738   xbt_os_thread_join(rctx->reader, NULL);
739
740   /*  xbt_os_mutex_release(rctx->interruption);
741      if (rctx->interrupted)
742      return NULL;
743      xbt_os_mutex_acquire(rctx->interruption); */
744
745   { // Sorting output got
746     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
747     xbt_dynar_t b = xbt_dynar_new(sizeof(char *), NULL);
748     unsigned cpt;
749     char *str;
750     xbt_dynar_foreach(a, cpt, str) {
751       if (strncmp(str, "TESH_ERROR ", (sizeof "TESH_ERROR ") - 1) == 0) {
752         XBT_CRITICAL("%s", str);
753         errcode = 1;
754       } else if (coverage &&
755                  strncmp(str, "profiling:", (sizeof "profiling:") - 1) == 0) {
756         XBT_DEBUG("Remove line [%u]: '%s'", cpt, str);
757       } else {
758         xbt_dynar_push_as(b, char *, str);
759       }
760     }
761
762     if (rctx->output_sort) {
763       stable_sort(b);
764       /* If empty lines moved in first position, remove them */
765       while (!xbt_dynar_is_empty(b) && *xbt_dynar_getfirst_as(b, char*) == '\0')
766         xbt_dynar_shift(b, NULL);
767     }
768
769     if (rctx->output_sort || xbt_dynar_length(b) != xbt_dynar_length(a)) {
770       char *newbuf = xbt_str_join(b, "\n");
771       strcpy(rctx->output_got->data, newbuf);
772       rctx->output_got->used = strlen(newbuf);
773       xbt_free(newbuf);
774     }
775
776     xbt_dynar_free(&b);
777     xbt_dynar_free(&a);
778   }
779
780   if (rctx->output_sort) { // Sorting output wanted
781     char *newbuf;
782     xbt_dynar_t a = xbt_str_split(rctx->output_wanted->data, "\n");
783
784     stable_sort(a);
785     /* If empty lines moved in first position, remove them */
786     while (!xbt_dynar_is_empty(a) && *xbt_dynar_getfirst_as(a, char*) == '\0')
787         xbt_dynar_shift(a, NULL);
788
789     newbuf = xbt_str_join(a, "\n");
790     strcpy(rctx->output_wanted->data, newbuf);
791     rctx->output_wanted->used = strlen(newbuf);
792     xbt_free(newbuf);
793
794     xbt_dynar_free(&a);
795   }
796   xbt_strbuff_chomp(rctx->output_got);
797   xbt_strbuff_chomp(rctx->output_wanted);
798   xbt_strbuff_trim(rctx->output_got);
799   xbt_strbuff_trim(rctx->output_wanted);
800
801   /* Check for broken pipe */
802   if (rctx->brokenpipe)
803     XBT_VERB
804         ("Warning: Child did not consume all its input (I got broken pipe)");
805
806   /* Check for timeouts */
807   if (rctx->timeout) {
808     if (rctx->output_got->data[0])
809       XBT_INFO("<%s> Output on timeout:\n%s",
810             rctx->filepos, rctx->output_got->data);
811     else
812       XBT_INFO("<%s> No output before timeout", rctx->filepos);
813     XBT_ERROR("Test suite `%s': NOK (<%s> timeout after %d sec)",
814            testsuite_name, rctx->filepos, timeout_value);
815     XBT_DEBUG("<%s> Interrupted = %d", rctx->filepos, (int)rctx->interrupted);
816     if (!rctx->interrupted) {
817       xbt_os_mutex_release(rctx->interruption);
818       rctx_armageddon(rctx, 3);
819       return NULL;
820     }
821   }
822
823   XBT_DEBUG("RCTX=%p (pid=%d)", rctx, rctx->pid);
824   XBT_DEBUG("Status(%s|%d)=%d", rctx->cmd, rctx->pid, rctx->status);
825
826   if (!rctx->interrupted) {
827     if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
828       XBT_ERROR("Test suite `%s': NOK (<%s> got signal %s)",
829              testsuite_name, rctx->filepos,
830              signal_name(WTERMSIG(rctx->status), NULL));
831       errcode = WTERMSIG(rctx->status) + 4;
832     }
833
834     if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
835         strcmp(signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
836                rctx->expected_signal)) {
837       XBT_ERROR("Test suite `%s': NOK (%s got signal %s instead of %s)",
838              testsuite_name, rctx->filepos,
839              signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
840              rctx->expected_signal);
841       errcode = WTERMSIG(rctx->status) + 4;
842     }
843
844     if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
845       XBT_ERROR("Test suite `%s': NOK (child %s expected signal %s)",
846              testsuite_name, rctx->filepos, rctx->expected_signal);
847       errcode = 5;
848     }
849
850     if (WIFEXITED(rctx->status)
851         && WEXITSTATUS(rctx->status) != rctx->expected_return) {
852       if (rctx->expected_return)
853         XBT_ERROR
854             ("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
855              testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status),
856              rctx->expected_return);
857       else
858         XBT_ERROR("Test suite `%s': NOK (<%s> returned code %d)",
859                testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
860       errcode = 40 + WEXITSTATUS(rctx->status);
861
862     }
863     rctx->expected_return = 0;
864
865     free(rctx->expected_signal);
866     rctx->expected_signal = NULL;
867   }
868
869   if ((errcode && errcode != 1) || rctx->interrupted) {
870     /* checking output, and matching */
871     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
872     char *out = xbt_str_join(a, "\n||");
873     xbt_dynar_free(&a);
874     XBT_INFO("Output of <%s> so far: \n||%s", rctx->filepos, out);
875     free(out);
876   } else if (rctx->output == e_output_check
877              && (rctx->output_got->used != rctx->output_wanted->used
878                  || strcmp(rctx->output_got->data,
879                            rctx->output_wanted->data))) {
880     if (XBT_LOG_ISENABLED(tesh, xbt_log_priority_info)) {
881       char *diff =
882           xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
883       XBT_ERROR("Output of <%s> mismatch:\n%s", rctx->filepos, diff);
884       free(diff);
885     }
886     XBT_ERROR("Test suite `%s': NOK (<%s> output mismatch)",
887            testsuite_name, rctx->filepos);
888
889     errcode = 2;
890   } else if (rctx->output == e_output_ignore) {
891     XBT_INFO("(ignoring the output of <%s> as requested)", rctx->filepos);
892   } else if (rctx->output == e_output_display) {
893     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
894     char *out = xbt_str_join(a, "\n||");
895     xbt_dynar_free(&a);
896     XBT_INFO("Here is the (ignored) command output: \n||%s", out);
897     free(out);
898   }
899
900   if (!rctx->is_background) {
901     xbt_os_mutex_acquire(armageddon_mutex);
902     /* Don't touch rctx if armageddon is in progress. */
903     if (!armageddon_initiator)
904       rctx_empty(rctx);
905     xbt_os_mutex_release(armageddon_mutex);
906   }
907   if (errcode) {
908     if (!rctx->interrupted) {
909       xbt_os_mutex_release(rctx->interruption);
910       rctx_armageddon(rctx, errcode);
911       return NULL;
912     }
913   }
914
915   xbt_os_mutex_release(rctx->interruption);
916   return NULL;
917 }