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