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