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