]> git.xonotic.org Git - xonotic/gmqcc.git/blob - test.cpp
Initial movement to std::vector
[xonotic/gmqcc.git] / test.cpp
1 #include <stdlib.h>
2 #include <string.h>
3 #include <stdio.h>
4
5 #include <sys/types.h>
6 #include <sys/wait.h>
7 #include <sys/stat.h>
8
9 #include <dirent.h>
10 #include <unistd.h>
11
12 #include "gmqcc.h"
13
14 static const char *task_bins[] = {
15     "./gmqcc",
16     "./qcvm"
17 };
18
19 typedef struct {
20     FILE *handles[3];
21     int pipes[3];
22     int stderr_fd;
23     int stdout_fd;
24     int pid;
25 } popen_t;
26
27 static FILE **task_popen(const char *command, const char *mode) {
28     int     inhandle  [2];
29     int     outhandle [2];
30     int     errhandle [2];
31     int     trypipe;
32
33     popen_t *data = (popen_t*)mem_a(sizeof(popen_t));
34
35     /*
36      * Parse the command now into a list for execv, this is a pain
37      * in the ass.
38      */
39     char  *line = (char*)command;
40     char **argv = NULL;
41     {
42
43         while (*line != '\0') {
44             while (*line == ' ' || *line == '\t' || *line == '\n')
45                 *line++ = '\0';
46             vec_push(argv, line);
47
48             while (*line != '\0' && *line != ' ' &&
49                    *line != '\t' && *line != '\n') line++;
50         }
51         vec_push(argv, (char *)0);
52     }
53
54
55     if ((trypipe = pipe(inhandle))  < 0) goto task_popen_error_0;
56     if ((trypipe = pipe(outhandle)) < 0) goto task_popen_error_1;
57     if ((trypipe = pipe(errhandle)) < 0) goto task_popen_error_2;
58
59     if ((data->pid = fork()) > 0) {
60         /* parent */
61         close(inhandle [0]);
62         close(outhandle [1]);
63         close(errhandle [1]);
64         data->pipes[0] = inhandle [1];
65         data->pipes[1] = outhandle[0];
66         data->pipes[2] = errhandle[0];
67         data->handles[0] = fdopen(inhandle [1], "w");
68         data->handles[1] = fdopen(outhandle[0], mode);
69         data->handles[2] = fdopen(errhandle[0], mode);
70
71         /* sigh */
72         vec_free(argv);
73         return data->handles;
74     } else if (data->pid == 0) {
75         /* child */
76         close(inhandle [1]);
77         close(outhandle[0]);
78         close(errhandle[0]);
79
80         /* see piping documentation for this sillyness :P */
81         dup2(inhandle [0], 0);
82         dup2(outhandle[1], 1);
83         dup2(errhandle[1], 2);
84
85         execvp(*argv, argv);
86         exit(EXIT_FAILURE);
87     } else {
88         /* fork failed */
89         goto task_popen_error_3;
90     }
91
92 task_popen_error_3: close(errhandle[0]), close(errhandle[1]);
93 task_popen_error_2: close(outhandle[0]), close(outhandle[1]);
94 task_popen_error_1: close(inhandle [0]), close(inhandle [1]);
95 task_popen_error_0:
96
97     vec_free(argv);
98     return NULL;
99 }
100
101 static int task_pclose(FILE **handles) {
102     popen_t *data   = (popen_t*)handles;
103     int      status = 0;
104
105     close(data->pipes[0]); /* stdin  */
106     close(data->pipes[1]); /* stdout */
107     close(data->pipes[2]); /* stderr */
108
109     waitpid(data->pid, &status, 0);
110
111     mem_d(data);
112
113     return status;
114 }
115
116 #define TASK_COMPILE    0
117 #define TASK_EXECUTE    1
118 /*
119  * Task template system:
120  *  templates are rules for a specific test, used to create a "task" that
121  *  is executed with those set of rules (arguments, and what not). Tests
122  *  that don't have a template with them cannot become tasks, since without
123  *  the information for that test there is no way to properly "test" them.
124  *  Rules for these templates are described in a template file, using a
125  *  task template language.
126  *
127  *  The language is a basic finite statemachine, top-down single-line
128  *  description language.
129  *
130  *  The languge is composed entierly of "tags" which describe a string of
131  *  text for a task.  Think of it much like a configuration file.  Except
132  *  it's been designed to allow flexibility and future support for prodecual
133  *  semantics.
134  *
135  *  The following "tags" are suported by the language
136  *
137  *      D:
138  *          Used to set a description of the current test, this must be
139  *          provided, this tag is NOT optional.
140  *
141  *      T:
142  *          Used to set the procedure for the given task, there are two
143  *          options for this:
144  *              -compile
145  *                  This simply performs compilation only
146  *              -execute
147  *                  This will perform compilation and execution
148  *              -fail
149  *                  This will perform compilation, but requires
150  *                  the compilation to fail in order to succeed.
151  *
152  *          This must be provided, this tag is NOT optional.
153  *
154  *      C:
155  *          Used to set the compilation flags for the given task, this
156  *          must be provided, this tag is NOT optional.
157  *
158  *      F:  Used to set some test suite flags, currently the only option
159  *          is -no-defs (to including of defs.qh)
160  *
161  *      E:
162  *          Used to set the execution flags for the given task. This tag
163  *          must be provided if T == -execute, otherwise it's erroneous
164  *          as compilation only takes place.
165  *
166  *      M:
167  *          Used to describe a string of text that should be matched from
168  *          the output of executing the task.  If this doesn't match the
169  *          task fails.  This tag must be provided if T == -execute, otherwise
170  *          it's erroneous as compilation only takes place.
171  *
172  *      I:
173  *          Used to specify the INPUT source file to operate on, this must be
174  *          provided, this tag is NOT optional
175  *
176  *
177  *  Notes:
178  *      These tags have one-time use, using them more than once will result
179  *      in template compilation errors.
180  *
181  *      Lines beginning with # or // in the template file are comments and
182  *      are ignored by the template parser.
183  *
184  *      Whitespace is optional, with exception to the colon ':' between the
185  *      tag and it's assignment value/
186  *
187  *      The template compiler will detect erronrous tags (optional tags
188  *      that need not be set), as well as missing tags, and error accordingly
189  *      this will result in the task failing.
190  */
191 typedef struct {
192     char  *description;
193     char  *compileflags;
194     char  *executeflags;
195     char  *proceduretype;
196     char  *sourcefile;
197     char  *tempfilename;
198     char **comparematch;
199     char  *rulesfile;
200     char  *testflags;
201 } task_template_t;
202
203 /*
204  * This is very much like a compiler code generator :-).  This generates
205  * a value from some data observed from the compiler.
206  */
207 static bool task_template_generate(task_template_t *tmpl, char tag, const char *file, size_t line, char *value, size_t *pad) {
208     size_t desclen = 0;
209     size_t filelen = 0;
210     char **destval = NULL;
211
212     if (!tmpl)
213         return false;
214
215     switch(tag) {
216         case 'D': destval = &tmpl->description;    break;
217         case 'T': destval = &tmpl->proceduretype;  break;
218         case 'C': destval = &tmpl->compileflags;   break;
219         case 'E': destval = &tmpl->executeflags;   break;
220         case 'I': destval = &tmpl->sourcefile;     break;
221         case 'F': destval = &tmpl->testflags;      break;
222         default:
223             con_printmsg(LVL_ERROR, __FILE__, __LINE__, 0, "internal error",
224                 "invalid tag `%c:` during code generation\n",
225                 tag
226             );
227             return false;
228     }
229
230     /*
231      * Ensure if for the given tag, there already exists a
232      * assigned value.
233      */
234     if (*destval) {
235         con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "compile error",
236             "tag `%c:` already assigned value: %s\n",
237             tag, *destval
238         );
239         return false;
240     }
241
242     /*
243      * Strip any whitespace that might exist in the value for assignments
244      * like "D:      foo"
245      */
246     if (value && *value && (*value == ' ' || *value == '\t'))
247         value++;
248     else if (!value)
249         exit(EXIT_FAILURE);
250
251     /*
252      * Value will contain a newline character at the end, we need to strip
253      * this otherwise kaboom, seriously, kaboom :P
254      */
255     if (strchr(value, '\n'))
256         *strrchr(value, '\n')='\0';
257
258     /*
259      * Now allocate and set the actual value for the specific tag. Which
260      * was properly selected and can be accessed with *destval.
261      */
262     *destval = util_strdup(value);
263
264
265     if (*destval == tmpl->description) {
266         /*
267          * Create some padding for the description to align the
268          * printing of the rules file.
269          */
270         if ((desclen = strlen(tmpl->description)) > pad[0])
271             pad[0] = desclen;
272     }
273
274     if ((filelen = strlen(file)) > pad[2])
275         pad[2] = filelen;
276
277     return true;
278 }
279
280 static bool task_template_parse(const char *file, task_template_t *tmpl, FILE *fp, size_t *pad) {
281     char  *data = NULL;
282     char  *back = NULL;
283     size_t size = 0;
284     size_t line = 1;
285
286     if (!tmpl)
287         return false;
288
289     /* top down parsing */
290     while (util_getline(&back, &size, fp) != EOF) {
291         /* skip whitespace */
292         data = back;
293         if (*data && (*data == ' ' || *data == '\t'))
294             data++;
295
296         switch (*data) {
297             /*
298              * Handle comments inside task tmpl files.  We're strict
299              * about the language for fun :-)
300              */
301             case '/':
302                 if (data[1] != '/') {
303                     con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error",
304                         "invalid character `/`, perhaps you meant `//` ?");
305
306                     mem_d(back);
307                     return false;
308                 }
309             case '#':
310                 break;
311
312             /*
313              * Empty newlines are acceptable as well, so we handle that here
314              * despite being just odd since there should't be that many
315              * empty lines to begin with.
316              */
317             case '\r':
318             case '\n':
319                 break;
320
321
322             /*
323              * Now begin the actual "tag" stuff.  This works as you expect
324              * it to.
325              */
326             case 'D':
327             case 'T':
328             case 'C':
329             case 'E':
330             case 'I':
331             case 'F':
332                 if (data[1] != ':') {
333                     con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error",
334                         "expected `:` after `%c`",
335                         *data
336                     );
337                     goto failure;
338                 }
339                 if (!task_template_generate(tmpl, *data, file, line, &data[3], pad)) {
340                     con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl compile error",
341                         "failed to generate for given task\n"
342                     );
343                     goto failure;
344                 }
345                 break;
346
347             /*
348              * Match requires it's own system since we allow multiple M's
349              * for multi-line matching.
350              */
351             case 'M':
352             {
353                 char *value = &data[3];
354                 if (data[1] != ':') {
355                     con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error",
356                         "expected `:` after `%c`",
357                         *data
358                     );
359                     goto failure;
360                 }
361
362                 /*
363                  * Value will contain a newline character at the end, we need to strip
364                  * this otherwise kaboom, seriously, kaboom :P
365                  */
366                 if (strrchr(value, '\n'))
367                     *strrchr(value, '\n')='\0';
368                 else /* cppcheck: possible null pointer dereference */
369                     exit(EXIT_FAILURE);
370
371                 vec_push(tmpl->comparematch, util_strdup(value));
372
373                 break;
374             }
375
376             default:
377                 con_printmsg(LVL_ERROR, file, line, 0, /*TODO: column for match*/ "tmpl parse error",
378                     "invalid tag `%c`", *data
379                 );
380                 goto failure;
381             /* no break required */
382         }
383
384         /* update line and free old sata */
385         line++;
386         mem_d(back);
387         back = NULL;
388     }
389     if (back)
390         mem_d(back);
391     return true;
392
393 failure:
394     mem_d (back);
395     return false;
396 }
397
398 /*
399  * Nullifies the template data: used during initialization of a new
400  * template and free.
401  */
402 static void task_template_nullify(task_template_t *tmpl) {
403     if (!tmpl)
404         return;
405
406     tmpl->description    = NULL;
407     tmpl->proceduretype  = NULL;
408     tmpl->compileflags   = NULL;
409     tmpl->executeflags   = NULL;
410     tmpl->comparematch   = NULL;
411     tmpl->sourcefile     = NULL;
412     tmpl->tempfilename   = NULL;
413     tmpl->rulesfile      = NULL;
414     tmpl->testflags      = NULL;
415 }
416
417 static task_template_t *task_template_compile(const char *file, const char *dir, size_t *pad) {
418     /* a page should be enough */
419     char             fullfile[4096];
420     size_t           filepadd = 0;
421     FILE       *tempfile = NULL;
422     task_template_t *tmpl     = NULL;
423
424     util_snprintf(fullfile,    sizeof(fullfile), "%s/%s", dir, file);
425
426     tempfile = fopen(fullfile, "r");
427     tmpl     = (task_template_t*)mem_a(sizeof(task_template_t));
428     task_template_nullify(tmpl);
429
430     /*
431      * Create some padding for the printing to align the
432      * printing of the rules file to the console.
433      */
434     if ((filepadd = strlen(fullfile)) > pad[1])
435         pad[1] = filepadd;
436
437     tmpl->rulesfile = util_strdup(fullfile);
438
439     /*
440      * Esnure the file even exists for the task, this is pretty useless
441      * to even do.
442      */
443     if (!tempfile) {
444         con_err("template file: %s does not exist or invalid permissions\n",
445             file
446         );
447         goto failure;
448     }
449
450     if (!task_template_parse(file, tmpl, tempfile, pad)) {
451         con_err("template parse error: error during parsing\n");
452         goto failure;
453     }
454
455     /*
456      * Regardless procedure type, the following tags must exist:
457      *  D
458      *  T
459      *  C
460      *  I
461      */
462     if (!tmpl->description) {
463         con_err("template compile error: %s missing `D:` tag\n", file);
464         goto failure;
465     }
466     if (!tmpl->proceduretype) {
467         con_err("template compile error: %s missing `T:` tag\n", file);
468         goto failure;
469     }
470     if (!tmpl->compileflags) {
471         con_err("template compile error: %s missing `C:` tag\n", file);
472         goto failure;
473     }
474     if (!tmpl->sourcefile) {
475         con_err("template compile error: %s missing `I:` tag\n", file);
476         goto failure;
477     }
478
479     /*
480      * Now lets compile the template, compilation is really just
481      * the process of validating the input.
482      */
483     if (!strcmp(tmpl->proceduretype, "-compile")) {
484         if (tmpl->executeflags)
485             con_err("template compile warning: %s erroneous tag `E:` when only compiling\n", file);
486         if (tmpl->comparematch)
487             con_err("template compile warning: %s erroneous tag `M:` when only compiling\n", file);
488         goto success;
489     } else if (!strcmp(tmpl->proceduretype, "-execute")) {
490         if (!tmpl->executeflags) {
491             /* default to $null */
492             tmpl->executeflags = util_strdup("$null");
493         }
494         if (!tmpl->comparematch) {
495             con_err("template compile error: %s missing `M:` tag (use `$null` for exclude)\n", file);
496             goto failure;
497         }
498     } else if (!strcmp(tmpl->proceduretype, "-fail")) {
499         if (tmpl->executeflags)
500             con_err("template compile warning: %s erroneous tag `E:` when only failing\n", file);
501         if (tmpl->comparematch)
502             con_err("template compile warning: %s erroneous tag `M:` when only failing\n", file);
503     } else if (!strcmp(tmpl->proceduretype, "-diagnostic")) {
504         if (tmpl->executeflags)
505             con_err("template compile warning: %s erroneous tag `E:` when only diagnostic\n", file);
506         if (!tmpl->comparematch) {
507             con_err("template compile error: %s missing `M:` tag (use `$null` for exclude)\n", file);
508             goto failure;
509         }
510     } else if (!strcmp(tmpl->proceduretype, "-pp")) {
511         if (tmpl->executeflags)
512             con_err("template compile warning: %s erroneous tag `E:` when only preprocessing\n", file);
513         if (!tmpl->comparematch) {
514             con_err("template compile error: %s missing `M:` tag (use `$null` for exclude)\n", file);
515             goto failure;
516         }
517     } else {
518         con_err("template compile error: %s invalid procedure type: %s\n", file, tmpl->proceduretype);
519         goto failure;
520     }
521
522 success:
523     fclose(tempfile);
524     return tmpl;
525
526 failure:
527     /*
528      * The file might not exist and we jump here when that doesn't happen
529      * so the check to see if it's not null here is required.
530      */
531     if (tempfile)
532         fclose(tempfile);
533     mem_d (tmpl);
534
535     return NULL;
536 }
537
538 static void task_template_destroy(task_template_t *tmpl) {
539     if (!tmpl)
540         return;
541
542     if (tmpl->description)    mem_d(tmpl->description);
543     if (tmpl->proceduretype)  mem_d(tmpl->proceduretype);
544     if (tmpl->compileflags)   mem_d(tmpl->compileflags);
545     if (tmpl->executeflags)   mem_d(tmpl->executeflags);
546     if (tmpl->sourcefile)     mem_d(tmpl->sourcefile);
547     if (tmpl->rulesfile)      mem_d(tmpl->rulesfile);
548     if (tmpl->testflags)      mem_d(tmpl->testflags);
549
550     /*
551      * Delete all allocated string for task tmpl then destroy the
552      * main vector.
553      */
554     {
555         size_t i = 0;
556         for (; i < vec_size(tmpl->comparematch); i++)
557             mem_d(tmpl->comparematch[i]);
558
559         vec_free(tmpl->comparematch);
560     }
561
562     /*
563      * Nullify all the template members otherwise NULL comparision
564      * checks will fail if tmpl pointer is reused.
565      */
566     mem_d(tmpl->tempfilename);
567     mem_d(tmpl);
568 }
569
570 /*
571  * Now comes the task manager, this system allows adding tasks in and out
572  * of a task list.  This is the executor of the tasks essentially as well.
573  */
574 typedef struct {
575     task_template_t *tmpl;
576     FILE **runhandles;
577     FILE *stderrlog;
578     FILE *stdoutlog;
579     char *stdoutlogfile;
580     char *stderrlogfile;
581     bool compiled;
582 } task_t;
583
584 static task_t *task_tasks = NULL;
585
586 /*
587  * Read a directory and searches for all template files in it
588  * which is later used to run all tests.
589  */
590 static bool task_propagate(const char *curdir, size_t *pad, const char *defs) {
591     bool             success = true;
592     DIR       *dir;
593     struct dirent     *files;
594     struct stat      directory;
595     char             buffer[4096];
596     size_t           found = 0;
597     char           **directories = NULL;
598     char            *claim = util_strdup(curdir);
599     size_t           i;
600
601     vec_push(directories, claim);
602     dir = opendir(claim);
603
604     /*
605      * Generate a list of subdirectories since we'll be checking them too
606      * for tmpl files.
607      */
608     while ((files = readdir(dir))) {
609         util_asprintf(&claim, "%s/%s", curdir, files->d_name);
610         if (stat(claim, &directory) == -1) {
611             closedir(dir);
612             mem_d(claim);
613             return false;
614         }
615
616         if (S_ISDIR(directory.st_mode) && files->d_name[0] != '.') {
617             vec_push(directories, claim);
618         } else {
619             mem_d(claim);
620             claim = NULL;
621         }
622     }
623     closedir(dir);
624
625     /*
626      * Now do all the work, by touching all the directories inside
627      * test as well and compile the task templates into data we can
628      * use to run the tests.
629      */
630     for (i = 0; i < vec_size(directories); i++) {
631         dir = opendir(directories[i]);
632
633         while ((files = readdir(dir))) {
634             util_snprintf(buffer, sizeof(buffer), "%s/%s", directories[i], files->d_name);
635             if (stat(buffer, &directory) == -1) {
636                 con_err("internal error: stat failed, aborting\n");
637                 abort();
638             }
639
640             if (S_ISDIR(directory.st_mode))
641                 continue;
642
643             /*
644              * We made it here, which concludes the file/directory is not
645              * actually a directory, so it must be a file :)
646              */
647             if (strcmp(files->d_name + strlen(files->d_name) - 5, ".tmpl") == 0) {
648                 task_template_t *tmpl = task_template_compile(files->d_name, directories[i], pad);
649                 char             buf[4096]; /* one page should be enough */
650                 const char      *qcflags = NULL;
651                 task_t           task;
652
653                 found ++;
654                 if (!tmpl) {
655                     con_err("error compiling task template: %s\n", files->d_name);
656                     success = false;
657                     continue;
658                 }
659                 /*
660                  * Generate a temportary file name for the output binary
661                  * so we don't trample over an existing one.
662                  */
663                 tmpl->tempfilename = NULL;
664                 util_asprintf(&tmpl->tempfilename, "%s/TMPDAT.%s.dat", directories[i], files->d_name);
665
666                 /*
667                  * Additional QCFLAGS enviroment variable may be used
668                  * to test compile flags for all tests.  This needs to be
669                  * BEFORE other flags (so that the .tmpl can override them)
670                  */
671                 qcflags = getenv("QCFLAGS");
672
673                 /*
674                  * Generate the command required to open a pipe to a process
675                  * which will be refered to with a handle in the task for
676                  * reading the data from the pipe.
677                  */
678                 if (strcmp(tmpl->proceduretype, "-pp")) {
679                     if (qcflags) {
680                         if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) {
681                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s %s -o %s",
682                                 task_bins[TASK_COMPILE],
683                                 directories[i],
684                                 tmpl->sourcefile,
685                                 qcflags,
686                                 tmpl->compileflags,
687                                 tmpl->tempfilename
688                             );
689                         } else {
690                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s/%s %s %s -o %s",
691                                 task_bins[TASK_COMPILE],
692                                 curdir,
693                                 defs,
694                                 directories[i],
695                                 tmpl->sourcefile,
696                                 qcflags,
697                                 tmpl->compileflags,
698                                 tmpl->tempfilename
699                             );
700                         }
701                     } else {
702                         if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) {
703                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s -o %s",
704                                 task_bins[TASK_COMPILE],
705                                 directories[i],
706                                 tmpl->sourcefile,
707                                 tmpl->compileflags,
708                                 tmpl->tempfilename
709                             );
710                         } else {
711                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s/%s %s -o %s",
712                                 task_bins[TASK_COMPILE],
713                                 curdir,
714                                 defs,
715                                 directories[i],
716                                 tmpl->sourcefile,
717                                 tmpl->compileflags,
718                                 tmpl->tempfilename
719                             );
720                         }
721                     }
722                 } else {
723                     /* Preprocessing (qcflags mean shit all here we don't allow them) */
724                     if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) {
725                         util_snprintf(buf, sizeof(buf), "%s -E %s/%s %s -o %s",
726                             task_bins[TASK_COMPILE],
727                             directories[i],
728                             tmpl->sourcefile,
729                             tmpl->compileflags,
730                             tmpl->tempfilename
731                         );
732                     } else {
733                         util_snprintf(buf, sizeof(buf), "%s -E %s/%s %s/%s %s -o %s",
734                             task_bins[TASK_COMPILE],
735                             curdir,
736                             defs,
737                             directories[i],
738                             tmpl->sourcefile,
739                             tmpl->compileflags,
740                             tmpl->tempfilename
741                         );
742                     }
743                 }
744
745                 /*
746                  * The task template was compiled, now lets create a task from
747                  * the template data which has now been propagated.
748                  */
749                 task.tmpl = tmpl;
750                 if (!(task.runhandles = task_popen(buf, "r"))) {
751                     con_err("error opening pipe to process for test: %s\n", tmpl->description);
752                     success = false;
753                     continue;
754                 }
755
756                 /*
757                  * Open up some file desciptors for logging the stdout/stderr
758                  * to our own.
759                  */
760                 util_snprintf(buf,  sizeof(buf), "%s.stdout", tmpl->tempfilename);
761                 task.stdoutlogfile = util_strdup(buf);
762                 if (!(task.stdoutlog = fopen(buf, "w"))) {
763                     con_err("error opening %s for stdout\n", buf);
764                     continue;
765                 }
766
767                 util_snprintf(buf,  sizeof(buf), "%s.stderr", tmpl->tempfilename);
768                 task.stderrlogfile = util_strdup(buf);
769                 if (!(task.stderrlog = fopen(buf, "w"))) {
770                     con_err("error opening %s for stderr\n", buf);
771                     continue;
772                 }
773                 vec_push(task_tasks, task);
774             }
775         }
776         closedir(dir);
777         mem_d(directories[i]); /* free claimed memory */
778     }
779     vec_free(directories);
780
781     return success;
782 }
783
784 /*
785  * Task precleanup removes any existing temporary files or log files
786  * left behind from a previous invoke of the test-suite.
787  */
788 static void task_precleanup(const char *curdir) {
789     DIR     *dir;
790     struct dirent  *files;
791     char          buffer[4096];
792
793     dir = opendir(curdir);
794
795     while ((files = readdir(dir))) {
796         if (strstr(files->d_name, "TMP")     ||
797             strstr(files->d_name, ".stdout") ||
798             strstr(files->d_name, ".stderr") ||
799             strstr(files->d_name, ".dat"))
800         {
801             util_snprintf(buffer, sizeof(buffer), "%s/%s", curdir, files->d_name);
802             if (remove(buffer))
803                 con_err("error removing temporary file: %s\n", buffer);
804         }
805     }
806
807     closedir(dir);
808 }
809
810 static void task_destroy(void) {
811     /*
812      * Free all the data in the task list and finally the list itself
813      * then proceed to cleanup anything else outside the program like
814      * temporary files.
815      */
816     size_t i;
817     for (i = 0; i < vec_size(task_tasks); i++) {
818         /*
819          * Close any open handles to files or processes here.  It's mighty
820          * annoying to have to do all this cleanup work.
821          */
822         if (task_tasks[i].stdoutlog) fclose(task_tasks[i].stdoutlog);
823         if (task_tasks[i].stderrlog) fclose(task_tasks[i].stderrlog);
824
825         /*
826          * Only remove the log files if the test actually compiled otherwise
827          * forget about it (or if it didn't compile, and the procedure type
828          * was set to -fail (meaning it shouldn't compile) .. stil remove)
829          */
830         if (task_tasks[i].compiled || !strcmp(task_tasks[i].tmpl->proceduretype, "-fail")) {
831             if (remove(task_tasks[i].stdoutlogfile))
832                 con_err("error removing stdout log file: %s\n", task_tasks[i].stdoutlogfile);
833             if (remove(task_tasks[i].stderrlogfile))
834                 con_err("error removing stderr log file: %s\n", task_tasks[i].stderrlogfile);
835
836             (void)!remove(task_tasks[i].tmpl->tempfilename);
837         }
838
839         /* free util_strdup data for log files */
840         mem_d(task_tasks[i].stdoutlogfile);
841         mem_d(task_tasks[i].stderrlogfile);
842
843         task_template_destroy(task_tasks[i].tmpl);
844     }
845     vec_free(task_tasks);
846 }
847
848 /*
849  * This executes the QCVM task for a specificly compiled progs.dat
850  * using the template passed into it for call-flags and user defined
851  * messages IF the procedure type is -execute, otherwise it matches
852  * the preprocessor output.
853  */
854 static bool task_trymatch(size_t i, char ***line) {
855     bool             success = true;
856     bool             process = true;
857     int              retval  = EXIT_SUCCESS;
858     FILE       *execute;
859     char             buffer[4096];
860     task_template_t *tmpl = task_tasks[i].tmpl;
861
862     memset  (buffer,0,sizeof(buffer));
863
864     if (!strcmp(tmpl->proceduretype, "-execute")) {
865         /*
866          * Drop the execution flags for the QCVM if none where
867          * actually specified.
868          */
869         if (!strcmp(tmpl->executeflags, "$null")) {
870             util_snprintf(buffer,  sizeof(buffer), "%s %s",
871                 task_bins[TASK_EXECUTE],
872                 tmpl->tempfilename
873             );
874         } else {
875             util_snprintf(buffer,  sizeof(buffer), "%s %s %s",
876                 task_bins[TASK_EXECUTE],
877                 tmpl->executeflags,
878                 tmpl->tempfilename
879             );
880         }
881
882         execute = popen(buffer, "r");
883         if (!execute)
884             return false;
885     } else if (!strcmp(tmpl->proceduretype, "-pp")) {
886         /*
887          * we're preprocessing, which means we need to read int
888          * the produced file and do some really weird shit.
889          */
890         if (!(execute = fopen(tmpl->tempfilename, "r")))
891             return false;
892         process = false;
893     } else {
894         /*
895          * we're testing diagnostic output, which means it will be
896          * in runhandles[2] (stderr) since that is where the compiler
897          * puts it's errors.
898          */
899         if (!(execute = fopen(task_tasks[i].stderrlogfile, "r")))
900             return false;
901         process = false;
902     }
903
904     /*
905      * Now lets read the lines and compare them to the matches we expect
906      * and handle accordingly.
907      */
908     {
909         char  *data    = NULL;
910         size_t size    = 0;
911         size_t compare = 0;
912
913         while (util_getline(&data, &size, execute) != EOF) {
914             if (!strcmp(data, "No main function found\n")) {
915                 con_err("test failure: `%s` (No main function found) [%s]\n",
916                     tmpl->description,
917                     tmpl->rulesfile
918                 );
919                 if (!process)
920                     fclose(execute);
921                 else
922                     pclose((FILE*)execute);
923                 return false;
924             }
925
926             /*
927              * Trim newlines from data since they will just break our
928              * ability to properly validate matches.
929              */
930             if  (strrchr(data, '\n'))
931                 *strrchr(data, '\n') = '\0';
932
933             /*
934              * We remove the file/directory and stuff from the error
935              * match messages when testing diagnostics.
936              */
937             if(!strcmp(tmpl->proceduretype, "-diagnostic")) {
938                 if (strstr(data, "there have been errors, bailing out"))
939                     continue; /* ignore it */
940                 if (strstr(data, ": error: ")) {
941                     char *claim = util_strdup(data + (strstr(data, ": error: ") - data) + 9);
942                     mem_d(data);
943                     data = claim;
944                 }
945             }
946
947             /*
948              * We need to ignore null lines for when -pp is used (preprocessor), since
949              * the preprocessor is likely to create empty newlines in certain macro
950              * instantations, otherwise it's in the wrong nature to ignore empty newlines.
951              */
952             if (!strcmp(tmpl->proceduretype, "-pp") && !*data)
953                 continue;
954
955             if (vec_size(tmpl->comparematch) > compare) {
956                 if (strcmp(data, tmpl->comparematch[compare++])) {
957                     success = false;
958                 }
959             } else {
960                 success = false;
961             }
962
963             /*
964              * Copy to output vector for diagnostics if execution match
965              * fails.
966              */
967             vec_push(*line, data);
968
969             /* reset */
970             data = NULL;
971             size = 0;
972         }
973
974         if (compare != vec_size(tmpl->comparematch))
975             success = false;
976
977         mem_d(data);
978         data = NULL;
979     }
980
981     if (process)
982         retval = pclose((FILE*)execute);
983     else
984         fclose(execute);
985
986     return success && retval == EXIT_SUCCESS;
987 }
988
989 static const char *task_type(task_template_t *tmpl) {
990     if (!strcmp(tmpl->proceduretype, "-pp"))
991         return "type: preprocessor";
992     if (!strcmp(tmpl->proceduretype, "-execute"))
993         return "type: execution";
994     if (!strcmp(tmpl->proceduretype, "-compile"))
995         return "type: compile";
996     if (!strcmp(tmpl->proceduretype, "-diagnostic"))
997         return "type: diagnostic";
998     return "type: fail";
999 }
1000
1001 /*
1002  * This schedualizes all tasks and actually runs them individually
1003  * this is generally easy for just -compile variants.  For compile and
1004  * execution this takes more work since a task needs to be generated
1005  * from thin air and executed INLINE.
1006  */
1007 #include <math.h>
1008 static size_t task_schedualize(size_t *pad) {
1009     char   space[2][64];
1010     bool   execute  = false;
1011     char  *data     = NULL;
1012     char **match    = NULL;
1013     size_t size     = 0;
1014     size_t i        = 0;
1015     size_t j        = 0;
1016     size_t failed   = 0;
1017     int    status   = 0;
1018
1019     util_snprintf(space[0], sizeof(space[0]), "%d", (int)vec_size(task_tasks));
1020
1021     for (; i < vec_size(task_tasks); i++) {
1022         memset(space[1], 0, sizeof(space[1]));
1023         util_snprintf(space[1], sizeof(space[1]), "%d", (int)(i + 1));
1024
1025         con_out("test #%u %*s", i + 1, strlen(space[0]) - strlen(space[1]), "");
1026
1027         /*
1028          * Generate a task from thin air if it requires execution in
1029          * the QCVM.
1030          */
1031
1032         /* diagnostic is not executed, but compare tested instead, like preproessor */
1033         execute = !! (!strcmp(task_tasks[i].tmpl->proceduretype, "-execute")) ||
1034                      (!strcmp(task_tasks[i].tmpl->proceduretype, "-pp"))      ||
1035                      (!strcmp(task_tasks[i].tmpl->proceduretype, "-diagnostic"));
1036
1037         /*
1038          * We assume it compiled before we actually compiled :).  On error
1039          * we change the value
1040          */
1041         task_tasks[i].compiled = true;
1042
1043         /*
1044          * Read data from stdout first and pipe that stuff into a log file
1045          * then we do the same for stderr.
1046          */
1047         while (util_getline(&data, &size, task_tasks[i].runhandles[1]) != EOF) {
1048             fputs(data, task_tasks[i].stdoutlog);
1049
1050             if (strstr(data, "failed to open file")) {
1051                 task_tasks[i].compiled = false;
1052                 execute                = false;
1053             }
1054         }
1055         while (util_getline(&data, &size, task_tasks[i].runhandles[2]) != EOF) {
1056             /*
1057              * If a string contains an error we just dissalow execution
1058              * of it in the vm.
1059              *
1060              * TODO: make this more percise, e.g if we print a warning
1061              * that refers to a variable named error, or something like
1062              * that .. then this will blowup :P
1063              */
1064             if (strstr(data, "error") && strcmp(task_tasks[i].tmpl->proceduretype, "-diagnostic")) {
1065                 execute                = false;
1066                 task_tasks[i].compiled = false;
1067             }
1068
1069             fputs(data, task_tasks[i].stderrlog);
1070             fflush(task_tasks[i].stderrlog); /* fast flush for read */
1071         }
1072
1073         if (!task_tasks[i].compiled && strcmp(task_tasks[i].tmpl->proceduretype, "-fail")) {
1074             con_out("failure:   `%s` %*s %*s\n",
1075                 task_tasks[i].tmpl->description,
1076                 (pad[0] + pad[1] - strlen(task_tasks[i].tmpl->description)) + (strlen(task_tasks[i].tmpl->rulesfile) - pad[1]),
1077                 task_tasks[i].tmpl->rulesfile,
1078                 (pad[1] + pad[2] - strlen(task_tasks[i].tmpl->rulesfile)) + (strlen("(failed to compile)") - pad[2]),
1079                 "(failed to compile)"
1080             );
1081             failed++;
1082             continue;
1083         }
1084
1085         status = task_pclose(task_tasks[i].runhandles);
1086         if ((!strcmp(task_tasks[i].tmpl->proceduretype, "-fail") && status == EXIT_SUCCESS)
1087         ||  ( strcmp(task_tasks[i].tmpl->proceduretype, "-fail") && status == EXIT_FAILURE)) {
1088             con_out("failure:   `%s` %*s %*s\n",
1089                 task_tasks[i].tmpl->description,
1090                 (pad[0] + pad[1] - strlen(task_tasks[i].tmpl->description)) + (strlen(task_tasks[i].tmpl->rulesfile) - pad[1]),
1091                 task_tasks[i].tmpl->rulesfile,
1092                 (pad[1] + pad[2] - strlen(task_tasks[i].tmpl->rulesfile)) + (strlen("(compiler didn't return exit success)") - pad[2]),
1093                 "(compiler didn't return exit success)"
1094             );
1095             failed++;
1096             continue;
1097         }
1098
1099         if (!execute) {
1100             con_out("succeeded: `%s` %*s %*s\n",
1101                 task_tasks[i].tmpl->description,
1102                 (pad[0] + pad[1] - strlen(task_tasks[i].tmpl->description)) + (strlen(task_tasks[i].tmpl->rulesfile) - pad[1]),
1103                 task_tasks[i].tmpl->rulesfile,
1104                 (pad[1] + pad[2] - strlen(task_tasks[i].tmpl->rulesfile)) + (strlen(task_type(task_tasks[i].tmpl)) - pad[2]),
1105                 task_type(task_tasks[i].tmpl)
1106
1107             );
1108             continue;
1109         }
1110
1111         /*
1112          * If we made it here that concludes the task is to be executed
1113          * in the virtual machine (or the preprocessor output needs to
1114          * be matched).
1115          */
1116         if (!task_trymatch(i, &match)) {
1117             size_t d = 0;
1118
1119             con_out("failure:   `%s` %*s %*s\n",
1120                 task_tasks[i].tmpl->description,
1121                 (pad[0] + pad[1] - strlen(task_tasks[i].tmpl->description)) + (strlen(task_tasks[i].tmpl->rulesfile) - pad[1]),
1122                 task_tasks[i].tmpl->rulesfile,
1123                 (pad[1] + pad[2] - strlen(task_tasks[i].tmpl->rulesfile)) + (strlen(
1124                     (strcmp(task_tasks[i].tmpl->proceduretype, "-pp"))
1125                         ? "(invalid results from execution)"
1126                         : (strcmp(task_tasks[i].tmpl->proceduretype, "-diagnostic"))
1127                             ? "(invalid results from preprocessing)"
1128                             : "(invalid results from compiler diagnsotics)"
1129                 ) - pad[2]),
1130                 (strcmp(task_tasks[i].tmpl->proceduretype, "-pp"))
1131                     ? "(invalid results from execution)"
1132                     : (strcmp(task_tasks[i].tmpl->proceduretype, "-diagnostic"))
1133                             ? "(invalid results from preprocessing)"
1134                             : "(invalid results from compiler diagnsotics)"
1135             );
1136
1137             /*
1138              * Print nicely formatted expected match lists to console error
1139              * handler for the all the given matches in the template file and
1140              * what was actually returned from executing.
1141              */
1142             con_out("    Expected From %u Matches: (got %u Matches)\n",
1143                 vec_size(task_tasks[i].tmpl->comparematch),
1144                 vec_size(match)
1145             );
1146             for (; d < vec_size(task_tasks[i].tmpl->comparematch); d++) {
1147                 char  *select = task_tasks[i].tmpl->comparematch[d];
1148                 size_t length = 60 - strlen(select);
1149
1150                 con_out("        Expected: \"%s\"", select);
1151                 while (length --)
1152                     con_out(" ");
1153                 con_out("| Got: \"%s\"\n", (d >= vec_size(match)) ? "<<nothing else to compare>>" : match[d]);
1154             }
1155
1156             /*
1157              * Print the non-expected out (since we are simply not expecting it)
1158              * This will help track down bugs in template files that fail to match
1159              * something.
1160              */
1161             if (vec_size(match) > vec_size(task_tasks[i].tmpl->comparematch)) {
1162                 for (d = 0; d < vec_size(match) - vec_size(task_tasks[i].tmpl->comparematch); d++) {
1163                     con_out("        Expected: Nothing                                                       | Got: \"%s\"\n",
1164                         match[d + vec_size(task_tasks[i].tmpl->comparematch)]
1165                     );
1166                 }
1167             }
1168
1169
1170             for (j = 0; j < vec_size(match); j++)
1171                 mem_d(match[j]);
1172             vec_free(match);
1173             failed++;
1174             continue;
1175         }
1176
1177         for (j = 0; j < vec_size(match); j++)
1178             mem_d(match[j]);
1179         vec_free(match);
1180
1181         con_out("succeeded: `%s` %*s %*s\n",
1182             task_tasks[i].tmpl->description,
1183             (pad[0] + pad[1] - strlen(task_tasks[i].tmpl->description)) + (strlen(task_tasks[i].tmpl->rulesfile) - pad[1]),
1184             task_tasks[i].tmpl->rulesfile,
1185             (pad[1] + pad[2] - strlen(task_tasks[i].tmpl->rulesfile)) + (strlen(task_type(task_tasks[i].tmpl))- pad[2]),
1186             task_type(task_tasks[i].tmpl)
1187
1188         );
1189     }
1190     mem_d(data);
1191     return failed;
1192 }
1193
1194 /*
1195  * This is the heart of the whole test-suite process.  This cleans up
1196  * any existing temporary files left behind as well as log files left
1197  * behind.  Then it propagates a list of tests from `curdir` by scaning
1198  * it for template files and compiling them into tasks, in which it
1199  * schedualizes them (executes them) and actually reports errors and
1200  * what not.  It then proceeds to destroy the tasks and return memory
1201  * it's the engine :)
1202  *
1203  * It returns true of tests could be propagated, otherwise it returns
1204  * false.
1205  *
1206  * It expects con_init() was called before hand.
1207  */
1208 static GMQCC_WARN bool test_perform(const char *curdir, const char *defs) {
1209     size_t             failed       = false;
1210     static const char *default_defs = "defs.qh";
1211
1212     size_t pad[] = {
1213         /* test ### [succeed/fail]: `description`      [tests/template.tmpl]     [type] */
1214                     0,                                 0,                        0
1215     };
1216
1217     /*
1218      * If the default definition file isn't set to anything.  We will
1219      * use the default_defs here, which is "defs.qc"
1220      */
1221     if (!defs) {
1222         defs = default_defs;
1223     }
1224
1225
1226     task_precleanup(curdir);
1227     if (!task_propagate(curdir, pad, defs)) {
1228         con_err("error: failed to propagate tasks\n");
1229         task_destroy();
1230         return false;
1231     }
1232     /*
1233      * If we made it here all tasks where propagated from their resultant
1234      * template file.  So we can start the FILO scheduler, this has been
1235      * designed in the most thread-safe way possible for future threading
1236      * it's designed to prevent lock contention, and possible syncronization
1237      * issues.
1238      */
1239     failed = task_schedualize(pad);
1240     if (failed)
1241         con_out("%u out of %u tests failed\n", failed, vec_size(task_tasks));
1242     task_destroy();
1243
1244     return (failed) ? false : true;
1245 }
1246
1247 /*
1248  * Fancy GCC-like LONG parsing allows things like --opt=param with
1249  * assignment operator.  This is used for redirecting stdout/stderr
1250  * console to specific files of your choice.
1251  */
1252 static bool parsecmd(const char *optname, int *argc_, char ***argv_, char **out, int ds, bool split) {
1253     int  argc   = *argc_;
1254     char **argv = *argv_;
1255
1256     size_t len = strlen(optname);
1257
1258     if (strncmp(argv[0]+ds, optname, len))
1259         return false;
1260
1261     /* it's --optname, check how the parameter is supplied */
1262     if (argv[0][ds+len] == '=') {
1263         *out = argv[0]+ds+len+1;
1264         return true;
1265     }
1266
1267     if (!split || argc < ds) /* no parameter was provided, or only single-arg form accepted */
1268         return false;
1269
1270     /* using --opt param */
1271     *out = argv[1];
1272     --*argc_;
1273     ++*argv_;
1274     return true;
1275 }
1276
1277 int main(int argc, char **argv) {
1278     bool succeed  = false;
1279     char *defs = NULL;
1280
1281     con_init();
1282
1283     /*
1284      * Command line option parsing commences now We only need to support
1285      * a few things in the test suite.
1286      */
1287     while (argc > 1) {
1288         ++argv;
1289         --argc;
1290
1291         if (argv[0][0] == '-') {
1292             if (parsecmd("defs", &argc, &argv, &defs, 1, false))
1293                 continue;
1294
1295             if (!strcmp(argv[0]+1, "debug")) {
1296                 OPTS_OPTION_BOOL(OPTION_DEBUG) = true;
1297                 continue;
1298             }
1299             if (!strcmp(argv[0]+1, "nocolor")) {
1300                 con_color(0);
1301                 continue;
1302             }
1303
1304             con_err("invalid argument %s\n", argv[0]+1);
1305             return -1;
1306         }
1307     }
1308     succeed = test_perform("tests", defs);
1309
1310     return (succeed) ? EXIT_SUCCESS : EXIT_FAILURE;
1311 }