]> git.xonotic.org Git - xonotic/gmqcc.git/blob - test.cpp
tests: xor peephole optimization regression test
[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                 memset(&task, 0, sizeof(task));
642
643                 found ++;
644                 if (!tmpl) {
645                     con_err("error compiling task template: %s\n", files->d_name);
646                     success = false;
647                     continue;
648                 }
649                 /*
650                  * Generate a temportary file name for the output binary
651                  * so we don't trample over an existing one.
652                  */
653                 tmpl->tempfilename = nullptr;
654                 util_asprintf(&tmpl->tempfilename, "%s/TMPDAT.%s.dat", it, files->d_name);
655
656                 /*
657                  * Additional QCFLAGS enviroment variable may be used
658                  * to test compile flags for all tests.  This needs to be
659                  * BEFORE other flags (so that the .tmpl can override them)
660                  */
661                 qcflags = getenv("QCFLAGS");
662
663                 /*
664                  * Generate the command required to open a pipe to a process
665                  * which will be refered to with a handle in the task for
666                  * reading the data from the pipe.
667                  */
668                 if (strcmp(tmpl->proceduretype, "-pp")) {
669                     if (qcflags) {
670                         if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) {
671                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s %s -o %s",
672                                 task_bins[TASK_COMPILE],
673                                 it,
674                                 tmpl->sourcefile,
675                                 qcflags,
676                                 tmpl->compileflags,
677                                 tmpl->tempfilename
678                             );
679                         } else {
680                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s/%s %s %s -o %s",
681                                 task_bins[TASK_COMPILE],
682                                 curdir,
683                                 defs,
684                                 it,
685                                 tmpl->sourcefile,
686                                 qcflags,
687                                 tmpl->compileflags,
688                                 tmpl->tempfilename
689                             );
690                         }
691                     } else {
692                         if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) {
693                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s -o %s",
694                                 task_bins[TASK_COMPILE],
695                                 it,
696                                 tmpl->sourcefile,
697                                 tmpl->compileflags,
698                                 tmpl->tempfilename
699                             );
700                         } else {
701                             util_snprintf(buf, sizeof(buf), "%s %s/%s %s/%s %s -o %s",
702                                 task_bins[TASK_COMPILE],
703                                 curdir,
704                                 defs,
705                                 it,
706                                 tmpl->sourcefile,
707                                 tmpl->compileflags,
708                                 tmpl->tempfilename
709                             );
710                         }
711                     }
712                 } else {
713                     /* Preprocessing (qcflags mean shit all here we don't allow them) */
714                     if (tmpl->testflags && !strcmp(tmpl->testflags, "-no-defs")) {
715                         util_snprintf(buf, sizeof(buf), "%s -E %s/%s %s -o %s",
716                             task_bins[TASK_COMPILE],
717                             it,
718                             tmpl->sourcefile,
719                             tmpl->compileflags,
720                             tmpl->tempfilename
721                         );
722                     } else {
723                         util_snprintf(buf, sizeof(buf), "%s -E %s/%s %s/%s %s -o %s",
724                             task_bins[TASK_COMPILE],
725                             curdir,
726                             defs,
727                             it,
728                             tmpl->sourcefile,
729                             tmpl->compileflags,
730                             tmpl->tempfilename
731                         );
732                     }
733                 }
734
735                 /*
736                  * The task template was compiled, now lets create a task from
737                  * the template data which has now been propagated.
738                  */
739                 task.tmpl = tmpl;
740                 if (!(task.runhandles = task_popen(buf, "r"))) {
741                     con_err("error opening pipe to process for test: %s\n", tmpl->description);
742                     success = false;
743                     continue;
744                 }
745
746                 /*
747                  * Open up some file desciptors for logging the stdout/stderr
748                  * to our own.
749                  */
750                 util_snprintf(buf, sizeof(buf), "%s.stdout", tmpl->tempfilename);
751                 task.stdoutlogfile = util_strdup(buf);
752                 if (!(task.stdoutlog = fopen(buf, "w"))) {
753                     con_err("error opening %s for stdout\n", buf);
754                     continue;
755                 }
756
757                 util_snprintf(buf, sizeof(buf), "%s.stderr", tmpl->tempfilename);
758                 task.stderrlogfile = util_strdup(buf);
759                 if (!(task.stderrlog = fopen(buf, "w"))) {
760                     con_err("error opening %s for stderr\n", buf);
761                     continue;
762                 }
763                 task_tasks.push_back(task);
764             }
765         }
766         closedir(dir);
767         mem_d(it); /* free claimed memory */
768     }
769     return success;
770 }
771
772 /*
773  * Task precleanup removes any existing temporary files or log files
774  * left behind from a previous invoke of the test-suite.
775  */
776 static void task_precleanup(const char *curdir) {
777     DIR     *dir;
778     struct dirent  *files;
779     char          buffer[4096];
780
781     dir = opendir(curdir);
782
783     while ((files = readdir(dir))) {
784         if (strstr(files->d_name, "TMP")     ||
785             strstr(files->d_name, ".stdout") ||
786             strstr(files->d_name, ".stderr") ||
787             strstr(files->d_name, ".dat"))
788         {
789             util_snprintf(buffer, sizeof(buffer), "%s/%s", curdir, files->d_name);
790             if (remove(buffer))
791                 con_err("error removing temporary file: %s\n", buffer);
792         }
793     }
794
795     closedir(dir);
796 }
797
798 static void task_destroy(void) {
799     /*
800      * Free all the data in the task list and finally the list itself
801      * then proceed to cleanup anything else outside the program like
802      * temporary files.
803      */
804     for (auto &it : task_tasks) {
805         /*
806          * Close any open handles to files or processes here.  It's mighty
807          * annoying to have to do all this cleanup work.
808          */
809         if (it.stdoutlog) fclose(it.stdoutlog);
810         if (it.stderrlog) fclose(it.stderrlog);
811
812         /*
813          * Only remove the log files if the test actually compiled otherwise
814          * forget about it (or if it didn't compile, and the procedure type
815          * was set to -fail (meaning it shouldn't compile) .. stil remove)
816          */
817         if (it.compiled || !strcmp(it.tmpl->proceduretype, "-fail")) {
818             if (remove(it.stdoutlogfile))
819                 con_err("error removing stdout log file: %s\n", it.stdoutlogfile);
820             if (remove(it.stderrlogfile))
821                 con_err("error removing stderr log file: %s\n", it.stderrlogfile);
822
823             (void)!remove(it.tmpl->tempfilename);
824         }
825
826         /* free util_strdup data for log files */
827         mem_d(it.stdoutlogfile);
828         mem_d(it.stderrlogfile);
829
830         task_template_destroy(it.tmpl);
831     }
832 }
833
834 /*
835  * This executes the QCVM task for a specificly compiled progs.dat
836  * using the template passed into it for call-flags and user defined
837  * messages IF the procedure type is -execute, otherwise it matches
838  * the preprocessor output.
839  */
840 static bool task_trymatch(task_t &task, std::vector<char *> &line) {
841     bool success = true;
842     bool process = true;
843     int retval = EXIT_SUCCESS;
844     FILE *execute;
845     char buffer[4096];
846     task_template_t *tmpl = task.tmpl;
847
848     memset(buffer,0,sizeof(buffer));
849
850     if (!strcmp(tmpl->proceduretype, "-execute")) {
851         /*
852          * Drop the execution flags for the QCVM if none where
853          * actually specified.
854          */
855         if (!strcmp(tmpl->executeflags, "$null")) {
856             util_snprintf(buffer,  sizeof(buffer), "%s %s",
857                 task_bins[TASK_EXECUTE],
858                 tmpl->tempfilename
859             );
860         } else {
861             util_snprintf(buffer,  sizeof(buffer), "%s %s %s",
862                 task_bins[TASK_EXECUTE],
863                 tmpl->executeflags,
864                 tmpl->tempfilename
865             );
866         }
867
868         execute = popen(buffer, "r");
869         if (!execute)
870             return false;
871     } else if (!strcmp(tmpl->proceduretype, "-pp")) {
872         /*
873          * we're preprocessing, which means we need to read int
874          * the produced file and do some really weird shit.
875          */
876         if (!(execute = fopen(tmpl->tempfilename, "r")))
877             return false;
878         process = false;
879     } else {
880         /*
881          * we're testing diagnostic output, which means it will be
882          * in runhandles[2] (stderr) since that is where the compiler
883          * puts it's errors.
884          */
885         if (!(execute = fopen(task.stderrlogfile, "r")))
886             return false;
887         process = false;
888     }
889
890     /*
891      * Now lets read the lines and compare them to the matches we expect
892      * and handle accordingly.
893      */
894     {
895         char  *data    = nullptr;
896         size_t size    = 0;
897         size_t compare = 0;
898
899         while (util_getline(&data, &size, execute) != EOF) {
900             if (!strcmp(data, "No main function found\n")) {
901                 con_err("test failure: `%s` (No main function found) [%s]\n",
902                     tmpl->description,
903                     tmpl->rulesfile
904                 );
905                 if (!process)
906                     fclose(execute);
907                 else
908                     pclose((FILE*)execute);
909                 return false;
910             }
911
912             /*
913              * Trim newlines from data since they will just break our
914              * ability to properly validate matches.
915              */
916             if  (strrchr(data, '\n'))
917                 *strrchr(data, '\n') = '\0';
918
919             /*
920              * We remove the file/directory and stuff from the error
921              * match messages when testing diagnostics.
922              */
923             if(!strcmp(tmpl->proceduretype, "-diagnostic")) {
924                 if (strstr(data, "there have been errors, bailing out"))
925                     continue; /* ignore it */
926                 if (strstr(data, ": error: ")) {
927                     char *claim = util_strdup(data + (strstr(data, ": error: ") - data) + 9);
928                     mem_d(data);
929                     data = claim;
930                 }
931             }
932
933             /*
934              * We need to ignore null lines for when -pp is used (preprocessor), since
935              * the preprocessor is likely to create empty newlines in certain macro
936              * instantations, otherwise it's in the wrong nature to ignore empty newlines.
937              */
938             if (!strcmp(tmpl->proceduretype, "-pp") && !*data)
939                 continue;
940
941             if (tmpl->comparematch.size() > compare) {
942                 if (strcmp(data, tmpl->comparematch[compare++])) {
943                     success = false;
944                 }
945             } else {
946                 success = false;
947             }
948
949             line.push_back(data);
950
951             /* reset */
952             data = nullptr;
953             size = 0;
954         }
955
956         if (compare != tmpl->comparematch.size())
957             success = false;
958
959         mem_d(data);
960         data = nullptr;
961     }
962
963     if (process)
964         retval = pclose((FILE*)execute);
965     else
966         fclose(execute);
967
968     return success && retval == EXIT_SUCCESS;
969 }
970
971 static const char *task_type(task_template_t *tmpl) {
972     if (!strcmp(tmpl->proceduretype, "-pp"))
973         return "type: preprocessor";
974     if (!strcmp(tmpl->proceduretype, "-execute"))
975         return "type: execution";
976     if (!strcmp(tmpl->proceduretype, "-compile"))
977         return "type: compile";
978     if (!strcmp(tmpl->proceduretype, "-diagnostic"))
979         return "type: diagnostic";
980     return "type: fail";
981 }
982
983 /*
984  * This schedualizes all tasks and actually runs them individually
985  * this is generally easy for just -compile variants.  For compile and
986  * execution this takes more work since a task needs to be generated
987  * from thin air and executed INLINE.
988  */
989 #include <math.h>
990 static size_t task_schedualize(size_t *pad) {
991     char space[2][64];
992     bool execute = false;
993     char *data = nullptr;
994     std::vector<char *> match;
995     size_t size = 0;
996     size_t i = 0;
997     size_t failed = 0;
998     int status = 0;
999
1000     util_snprintf(space[0], sizeof(space[0]), "%d", (int)task_tasks.size());
1001
1002     for (auto &it : task_tasks) {
1003         i++;
1004         memset(space[1], 0, sizeof(space[1]));
1005         util_snprintf(space[1], sizeof(space[1]), "%d", (int)(i));
1006
1007         con_out("test #%u %*s", i, strlen(space[0]) - strlen(space[1]), "");
1008             //con_out("[[%*s]]",
1009             //    (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]),
1010             //    it.tmpl->rulesfile);
1011             //fflush(stdout);
1012
1013         /*
1014          * Generate a task from thin air if it requires execution in
1015          * the QCVM.
1016          */
1017
1018         /* diagnostic is not executed, but compare tested instead, like preproessor */
1019         execute = !! (!strcmp(it.tmpl->proceduretype, "-execute")) ||
1020                      (!strcmp(it.tmpl->proceduretype, "-pp"))      ||
1021                      (!strcmp(it.tmpl->proceduretype, "-diagnostic"));
1022
1023         /*
1024          * We assume it compiled before we actually compiled :).  On error
1025          * we change the value
1026          */
1027         it.compiled = true;
1028
1029         /*
1030          * Read data from stdout first and pipe that stuff into a log file
1031          * then we do the same for stderr.
1032          */
1033         while (util_getline(&data, &size, it.runhandles[1]) != EOF) {
1034             fputs(data, it.stdoutlog);
1035
1036             if (strstr(data, "failed to open file")) {
1037                 it.compiled = false;
1038                 execute                = false;
1039             }
1040         }
1041         while (util_getline(&data, &size, it.runhandles[2]) != EOF) {
1042             /*
1043              * If a string contains an error we just dissalow execution
1044              * of it in the vm.
1045              *
1046              * TODO: make this more percise, e.g if we print a warning
1047              * that refers to a variable named error, or something like
1048              * that .. then this will blowup :P
1049              */
1050             if (strstr(data, "error") && strcmp(it.tmpl->proceduretype, "-diagnostic")) {
1051                 execute                = false;
1052                 it.compiled = false;
1053             }
1054
1055             fputs(data, it.stderrlog);
1056             fflush(it.stderrlog); /* fast flush for read */
1057         }
1058
1059         if (!it.compiled && strcmp(it.tmpl->proceduretype, "-fail")) {
1060             con_out("failure:   `%s` %*s %*s\n",
1061                 it.tmpl->description,
1062                 (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]),
1063                 it.tmpl->rulesfile,
1064                 (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen("(failed to compile)") - pad[2]),
1065                 "(failed to compile)"
1066             );
1067             failed++;
1068             continue;
1069         }
1070
1071         status = task_pclose(it.runhandles);
1072         if (status != 0 && status != 1) {
1073             con_out("compiler failure (returned: %i):   `%s` %*s\n",
1074                 status,
1075                 it.tmpl->description,
1076                 (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]),
1077                 it.tmpl->rulesfile
1078             );
1079             failed++;
1080             continue;
1081         }
1082         if ((!strcmp(it.tmpl->proceduretype, "-fail") && status == EXIT_SUCCESS)
1083         ||  ( strcmp(it.tmpl->proceduretype, "-fail") && status == EXIT_FAILURE)) {
1084             con_out("failure:   `%s` %*s %*s\n",
1085                 it.tmpl->description,
1086                 (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]),
1087                 it.tmpl->rulesfile,
1088                 (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen("(compiler didn't return exit success)") - pad[2]),
1089                 "(compiler didn't return exit success)"
1090             );
1091             failed++;
1092             continue;
1093         }
1094
1095         if (!execute) {
1096             con_out("succeeded: `%s` %*s %*s\n",
1097                 it.tmpl->description,
1098                 (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]),
1099                 it.tmpl->rulesfile,
1100                 (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen(task_type(it.tmpl)) - pad[2]),
1101                 task_type(it.tmpl)
1102
1103             );
1104             continue;
1105         }
1106
1107         /*
1108          * If we made it here that concludes the task is to be executed
1109          * in the virtual machine (or the preprocessor output needs to
1110          * be matched).
1111          */
1112         if (!task_trymatch(it, match)) {
1113             size_t d = 0;
1114
1115             con_out("failure:   `%s` %*s %*s\n",
1116                 it.tmpl->description,
1117                 (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]),
1118                 it.tmpl->rulesfile,
1119                 (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen(
1120                     (strcmp(it.tmpl->proceduretype, "-pp"))
1121                         ? "(invalid results from execution)"
1122                         : (strcmp(it.tmpl->proceduretype, "-diagnostic"))
1123                             ? "(invalid results from preprocessing)"
1124                             : "(invalid results from compiler diagnsotics)"
1125                 ) - pad[2]),
1126                 (strcmp(it.tmpl->proceduretype, "-pp"))
1127                     ? "(invalid results from execution)"
1128                     : (strcmp(it.tmpl->proceduretype, "-diagnostic"))
1129                             ? "(invalid results from preprocessing)"
1130                             : "(invalid results from compiler diagnsotics)"
1131             );
1132
1133             /*
1134              * Print nicely formatted expected match lists to console error
1135              * handler for the all the given matches in the template file and
1136              * what was actually returned from executing.
1137              */
1138             con_out("    Expected From %u Matches: (got %u Matches)\n",
1139                 it.tmpl->comparematch.size(),
1140                 match.size()
1141             );
1142             for (; d < it.tmpl->comparematch.size(); d++) {
1143                 char *select = it.tmpl->comparematch[d];
1144                 size_t length = 60 - strlen(select);
1145                 con_out("        Expected: \"%s\"", select);
1146                 while (length --)
1147                     con_out(" ");
1148                 con_out("| Got: \"%s\"\n", (d >= match.size()) ? "<<nothing else to compare>>" : match[d]);
1149             }
1150
1151             /*
1152              * Print the non-expected out (since we are simply not expecting it)
1153              * This will help track down bugs in template files that fail to match
1154              * something.
1155              */
1156             if (match.size() > it.tmpl->comparematch.size()) {
1157                 for (d = 0; d < match.size() - it.tmpl->comparematch.size(); d++) {
1158                     con_out("        Expected: Nothing                                                       | Got: \"%s\"\n",
1159                         match[d + it.tmpl->comparematch.size()]
1160                     );
1161                 }
1162             }
1163
1164             for (auto &it : match)
1165                 mem_d(it);
1166             match.clear();
1167             failed++;
1168             continue;
1169         }
1170
1171         for (auto &it : match)
1172             mem_d(it);
1173         match.clear();
1174
1175         con_out("succeeded: `%s` %*s %*s\n",
1176             it.tmpl->description,
1177             (pad[0] + pad[1] - strlen(it.tmpl->description)) + (strlen(it.tmpl->rulesfile) - pad[1]),
1178             it.tmpl->rulesfile,
1179             (pad[1] + pad[2] - strlen(it.tmpl->rulesfile)) + (strlen(task_type(it.tmpl))- pad[2]),
1180             task_type(it.tmpl)
1181
1182         );
1183     }
1184     mem_d(data);
1185     return failed;
1186 }
1187
1188 /*
1189  * This is the heart of the whole test-suite process.  This cleans up
1190  * any existing temporary files left behind as well as log files left
1191  * behind.  Then it propagates a list of tests from `curdir` by scaning
1192  * it for template files and compiling them into tasks, in which it
1193  * schedualizes them (executes them) and actually reports errors and
1194  * what not.  It then proceeds to destroy the tasks and return memory
1195  * it's the engine :)
1196  *
1197  * It returns true of tests could be propagated, otherwise it returns
1198  * false.
1199  *
1200  * It expects con_init() was called before hand.
1201  */
1202 static GMQCC_WARN bool test_perform(const char *curdir, const char *defs) {
1203     size_t             failed       = false;
1204     static const char *default_defs = "defs.qh";
1205
1206     size_t pad[] = {
1207         /* test ### [succeed/fail]: `description`      [tests/template.tmpl]     [type] */
1208                     0,                                 0,                        0
1209     };
1210
1211     /*
1212      * If the default definition file isn't set to anything.  We will
1213      * use the default_defs here, which is "defs.qc"
1214      */
1215     if (!defs) {
1216         defs = default_defs;
1217     }
1218
1219
1220     task_precleanup(curdir);
1221     if (!task_propagate(curdir, pad, defs)) {
1222         con_err("error: failed to propagate tasks\n");
1223         task_destroy();
1224         return false;
1225     }
1226     /*
1227      * If we made it here all tasks where propagated from their resultant
1228      * template file.  So we can start the FILO scheduler, this has been
1229      * designed in the most thread-safe way possible for future threading
1230      * it's designed to prevent lock contention, and possible syncronization
1231      * issues.
1232      */
1233     failed = task_schedualize(pad);
1234     if (failed)
1235         con_out("%u out of %u tests failed\n", failed, task_tasks.size());
1236     task_destroy();
1237
1238     return (failed) ? false : true;
1239 }
1240
1241 /*
1242  * Fancy GCC-like LONG parsing allows things like --opt=param with
1243  * assignment operator.  This is used for redirecting stdout/stderr
1244  * console to specific files of your choice.
1245  */
1246 static bool parsecmd(const char *optname, int *argc_, char ***argv_, char **out, int ds, bool split) {
1247     int  argc   = *argc_;
1248     char **argv = *argv_;
1249
1250     size_t len = strlen(optname);
1251
1252     if (strncmp(argv[0]+ds, optname, len))
1253         return false;
1254
1255     /* it's --optname, check how the parameter is supplied */
1256     if (argv[0][ds+len] == '=') {
1257         *out = argv[0]+ds+len+1;
1258         return true;
1259     }
1260
1261     if (!split || argc < ds) /* no parameter was provided, or only single-arg form accepted */
1262         return false;
1263
1264     /* using --opt param */
1265     *out = argv[1];
1266     --*argc_;
1267     ++*argv_;
1268     return true;
1269 }
1270
1271 int main(int argc, char **argv) {
1272     bool succeed  = false;
1273     char *defs = nullptr;
1274
1275     con_init();
1276
1277     /*
1278      * Command line option parsing commences now We only need to support
1279      * a few things in the test suite.
1280      */
1281     while (argc > 1) {
1282         ++argv;
1283         --argc;
1284
1285         if (argv[0][0] == '-') {
1286             if (parsecmd("defs", &argc, &argv, &defs, 1, false))
1287                 continue;
1288
1289             if (!strcmp(argv[0]+1, "debug")) {
1290                 OPTS_OPTION_BOOL(OPTION_DEBUG) = true;
1291                 continue;
1292             }
1293             if (!strcmp(argv[0]+1, "nocolor")) {
1294                 con_color(0);
1295                 continue;
1296             }
1297
1298             con_err("invalid argument %s\n", argv[0]+1);
1299             return -1;
1300         }
1301     }
1302     succeed = test_perform("tests", defs);
1303
1304     return (succeed) ? EXIT_SUCCESS : EXIT_FAILURE;
1305 }