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