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