Logo AND Algorithmique Numérique Distribuée

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