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