]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - test.c
Actually commit the new test stuff
[xonotic/gmqcc.git] / test.c
1 /*
2  * Copyright (C) 2012
3  *     Dale Weiler
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include "gmqcc.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <dirent.h>
27
28 bool  opts_memchk = true;
29 bool  opts_debug  = false;
30 char *task_bins[] = {
31     "./gmqcc",
32     "./qcvm"
33 };
34
35 #define TASK_COMPILE 0
36 #define TASK_EXECUTE 1
37
38 /*
39  * Task template system:
40  *  templates are rules for a specific test, used to create a "task" that
41  *  is executed with those set of rules (arguments, and what not). Tests
42  *  that don't have a template with them cannot become tasks, since without
43  *  the information for that test there is no way to properly "test" them.
44  *  Rules for these templates are described in a template file, using a
45  *  task template language.
46  * 
47  *  The language is a basic finite statemachine, top-down single-line
48  *  description language.
49  * 
50  *  The languge is composed entierly of "tags" which describe a string of
51  *  text for a task.  Think of it much like a configuration file.  Except
52  *  it's been designed to allow flexibility and future support for prodecual
53  *  semantics.
54  * 
55  *  The following "tags" are suported by the language
56  * 
57  *      D:
58  *          Used to set a description of the current test, this must be
59  *          provided, this tag is NOT optional.
60  * 
61  *      F:
62  *          Used to set a failure message, this message will be displayed
63  *          if the test fails, this tag is optional
64  * 
65  *      S:
66  *          Used to set a success message, this message will be displayed
67  *          if the test succeeds, this tag is optional.
68  * 
69  *      T:
70  *          Used to set the procedure for the given task, there are two
71  *          options for this:
72  *              -compile
73  *                  This simply performs compilation only
74  *              -execute
75  *                  This will perform compilation and execution
76  * 
77  *          This must be provided, this tag is NOT optional.
78  * 
79  *      C:
80  *          Used to set the compilation flags for the given task, this
81  *          must be provided, this tag is NOT optional.
82  * 
83  *      E:
84  *          Used to set the execution flags for the given task. This tag
85  *          must be provided if T == -execute, otherwise it's erroneous
86  *          as compilation only takes place. 
87  *      
88  *      M:
89  *          Used to describe a string of text that should be matched from
90  *          the output of executing the task.  If this doesn't match the
91  *          task fails.  This tag must be provided if T == -execute, otherwise
92  *          it's erroneous as compilation only takes place.
93  * 
94  *      I:
95  *          Used to specify the INPUT source file to operate on, this must be
96  *          provided, this tag is NOT optional.
97  * 
98  *  Notes:
99  *      These tags have one-time use, using them more than once will result
100  *      in template compilation errors.
101  * 
102  *      Lines beginning with # or // in the template file are comments and
103  *      are ignored by the template parser.
104  * 
105  *      Whitespace is optional, with exception to the colon ':' between the
106  *      tag and it's assignment value/
107  * 
108  *      The template compiler will detect erronrous tags (optional tags
109  *      that need not be set), as well as missing tags, and error accordingly
110  *      this will result in the task failing.
111  */
112 typedef struct {
113     char *description;
114     char *failuremessage;
115     char *successmessage;
116     char *compileflags;
117     char *executeflags;
118     char *comparematch;
119     char *proceduretype;
120     char *sourcefile;
121 } task_template_t;
122
123 /*
124  * This is very much like a compiler code generator :-).  This generates
125  * a value from some data observed from the compiler.
126  */
127 bool task_template_generate(task_template_t *template, char tag, const char *file, size_t line, const char *value) {
128     char **destval = NULL;
129     
130     if (!template)
131         return false;
132     
133     switch(tag) {
134         case 'D': destval = &template->description;    break;
135         case 'F': destval = &template->failuremessage; break;
136         case 'S': destval = &template->successmessage; break;
137         case 'T': destval = &template->proceduretype;  break;
138         case 'C': destval = &template->compileflags;   break;
139         case 'E': destval = &template->executeflags;   break;
140         case 'M': destval = &template->comparematch;   break;
141         case 'I': destval = &template->sourcefile;     break;
142         default:
143             con_printmsg(LVL_ERROR, __FILE__, __LINE__, "internal error",
144                 "invalid tag `%c:` during code generation\n",
145                 tag
146             );
147             return false;
148     }
149     
150     /*
151      * Ensure if for the given tag, there already exists a
152      * assigned value.
153      */
154     if (*destval) {
155         con_printmsg(LVL_ERROR, file, line, "compile error",
156             "tag `%c:` already assigned value: %s\n",
157             tag, *destval
158         );
159         return false;
160     }
161     
162     /*
163      * Strip any whitespace that might exist in the value for assignments
164      * like "D:      foo"
165      */
166     if (value && *value && (*value == ' ' || *value == '\t'))
167         value++;
168     
169     /*
170      * Value will contain a newline character at the end, we need to strip
171      * this otherwise kaboom, seriously, kaboom :P
172      */
173     *strrchr(value, '\n')='\0';
174     
175     /*
176      * Now allocate and set the actual value for the specific tag. Which
177      * was properly selected and can be accessed with *destval.
178      */
179     *destval = util_strdup(value);
180     
181     return true;
182 }
183
184 bool task_template_parse(const char *file, task_template_t *template, FILE *fp) {
185     char  *data = NULL;
186     char  *back = NULL;
187     size_t size = 0;
188     size_t line = 1;
189     
190     if (!template)
191         return false;
192     
193     /* top down parsing */
194     while (util_getline(&back, &size, fp) != EOF) {
195         /* skip whitespace */
196         data = back;
197         if (*data && (*data == ' ' || *data == '\t'))
198             data++;
199             
200         switch (*data) {
201             /*
202              * Handle comments inside task template files.  We're strict
203              * about the language for fun :-)
204              */
205             case '/':
206                 if (data[1] != '/') {
207                     con_printmsg(LVL_ERROR, file, line, "template parse error",
208                         "invalid character `/`, perhaps you meant `//` ?");
209                     
210                     mem_d(back);
211                     return false;
212                 }
213             case '#':
214                 break;
215                 
216             /*
217              * Empty newlines are acceptable as well, so we handle that here
218              * despite being just odd since there should't be that many
219              * empty lines to begin with.
220              */
221             case '\r':
222             case '\n':
223                 break;
224                 
225                 
226             /*
227              * Now begin the actual "tag" stuff.  This works as you expect
228              * it to.
229              */
230             case 'D':
231             case 'F':
232             case 'S':
233             case 'T':
234             case 'C':
235             case 'E':
236             case 'M':
237             case 'I':
238                 if (data[1] != ':') {
239                     con_printmsg(LVL_ERROR, file, line, "template parse error",
240                         "expected `:` after `%c`",
241                         *data
242                     );
243                     goto failure;
244                 }
245                 if (!task_template_generate(template, *data, file, line, &data[3])) {
246                     con_printmsg(LVL_ERROR, file, line, "template compile error",
247                         "failed to generate for given task\n"
248                     );
249                     goto failure;
250                 }
251                 break;
252             
253             default:
254                 con_printmsg(LVL_ERROR, file, line, "template parse error",
255                     "invalid tag `%c`", *data
256                 );
257                 goto failure;
258             /* no break required */
259         }
260         
261         /* update line and free old sata */
262         line++;
263         mem_d(back);
264         back = NULL;
265     }
266     if (back)
267         mem_d(back);
268     return true;
269     
270 failure:
271     if (back)
272         mem_d (back);
273     return false;
274 }
275
276 /*
277  * Nullifies the template data: used during initialization of a new
278  * template and free.
279  */
280 void task_template_nullify(task_template_t *template) {
281     if (!template)
282         return;
283         
284     template->description    = NULL;
285     template->failuremessage = NULL;
286     template->successmessage = NULL;
287     template->proceduretype  = NULL;
288     template->compileflags   = NULL;
289     template->executeflags   = NULL;
290     template->comparematch   = NULL;
291     template->sourcefile     = NULL;
292 }
293
294 task_template_t *task_template_compile(const char *file, const char *dir) {
295     /* a page should be enough */
296     char             fullfile[4096];
297     FILE            *tempfile = NULL;
298     task_template_t *template = NULL;
299     
300     memset  (fullfile, 0, sizeof(fullfile));
301     snprintf(fullfile,    sizeof(fullfile), "%s/%s", dir, file);
302     
303     tempfile = fopen(fullfile, "r");
304     template = mem_a(sizeof(task_template_t));
305     task_template_nullify(template);
306     
307     /*
308      * Esnure the file even exists for the task, this is pretty useless
309      * to even do.
310      */
311     if (!tempfile) {
312         con_err("template file: %s does not exist or invalid permissions\n",
313             file
314         );
315         goto failure;
316     }
317     
318     if (!task_template_parse(file, template, tempfile)) {
319         con_err("template parse error: error during parsing\n");
320         goto failure;
321     }
322     
323     /*
324      * Regardless procedure type, the following tags must exist:
325      *  D
326      *  T
327      *  C
328      *  I
329      */
330     if (!template->description) {
331         con_err("template compile error: %s missing `D:` tag\n", file);
332         goto failure;
333     }
334     if (!template->proceduretype) {
335         con_err("template compile error: %s missing `T:` tag\n", file);
336         goto failure;
337     }
338     if (!template->compileflags) {
339         con_err("template compile error: %s missing `C:` tag\n", file);
340         goto failure;
341     }
342     if (!template->sourcefile) {
343         con_err("template compile error: %s missing `I:` tag\n", file);
344         goto failure;
345     }
346     
347     /*
348      * Now lets compile the template, compilation is really just
349      * the process of validating the input.
350      */
351     if (!strcmp(template->proceduretype, "-compile")) {
352         if (template->executeflags)
353             con_err("template compile warning: %s erroneous tag `E:` when only compiling\n", file);
354         if (template->comparematch)
355             con_err("template compile warning: %s erroneous tag `M:` when only compiling\n", file);
356         goto success;
357     } else if (!strcmp(template->proceduretype, "-execute")) {
358         if (!template->executeflags) {
359             con_err("template compile error: %s missing `E:` tag (use `$null` for exclude)\n", file);
360             goto failure;
361         }
362         if (!template->comparematch) {
363             con_err("template compile error: %s missing `M:` tag (use `$null` for exclude)\n", file);
364             goto failure;
365         }
366     } else {
367         con_err("template compile error: %s invalid procedure type: %s\n", file, template->proceduretype);
368         goto failure;
369     }
370     
371 success:
372     fclose(tempfile);
373     return template;
374     
375 failure:
376     /*
377      * The file might not exist and we jump here when that doesn't happen
378      * so the check to see if it's not null here is required.
379      */
380     if (tempfile)
381         fclose(tempfile);
382     mem_d (template);
383     
384     return NULL;
385 }
386
387 void task_template_destroy(task_template_t **template) {
388     if (!template)
389         return;
390         
391     if ((*template)->description)    mem_d((*template)->description);
392     if ((*template)->failuremessage) mem_d((*template)->failuremessage);
393     if ((*template)->successmessage) mem_d((*template)->successmessage);
394     if ((*template)->proceduretype)  mem_d((*template)->proceduretype);
395     if ((*template)->compileflags)   mem_d((*template)->compileflags);
396     if ((*template)->executeflags)   mem_d((*template)->executeflags);
397     if ((*template)->comparematch)   mem_d((*template)->comparematch);
398     if ((*template)->sourcefile)     mem_d((*template)->sourcefile);
399     
400     /*
401      * Nullify all the template members otherwise NULL comparision
402      * checks will fail if template pointer is reused.
403      */
404     mem_d(*template);
405     task_template_nullify(*template);
406     *template = NULL;
407 }
408
409 /*
410  * Now comes the task manager, this system allows adding tasks in and out
411  * of a task list.  This is the executor of the tasks essentially as well.
412  */
413 typedef struct {
414     task_template_t *template;
415     FILE            *handle;
416 } task_t;
417
418 task_t *task_tasks = NULL;
419
420 /*
421  * Read a directory and searches for all template files in it
422  * which is later used to run all tests.
423  */
424 bool task_propogate(const char *curdir) {
425     bool             success = true;
426     DIR             *dir;
427     struct dirent   *files;
428     struct stat      directory;
429     
430     dir = opendir(curdir);
431     
432     while ((files = readdir(dir))) {
433         stat(files->d_name, &directory);
434         
435         /* skip directories */
436         if (S_ISDIR(directory.st_mode))
437             continue;
438             
439         /*
440          * We made it here, which concludes the file/directory is not
441          * actually a directory, so it must be a file :)
442          */
443         if (strstr(files->d_name, ".tmpl")) {
444             con_out("compiling task template: %s/%s\n", curdir, files->d_name);
445             task_template_t *template = task_template_compile(files->d_name, curdir);
446             if (!template) {
447                 con_err("error compiling task template: %s\n", files->d_name);
448                 success = false;
449                 continue;
450             }
451             
452             /*
453              * Generate the command required to open a pipe to a process
454              * which will be refered to with a handle in the task for
455              * reading the data from the pipe.
456              */
457             char     buf[4096]; /* one page should be enough */
458             memset  (buf,0,sizeof(buf));
459             snprintf(buf,  sizeof(buf), "%s %s/%s %s",
460                 task_bins[TASK_COMPILE],
461                 curdir,
462                 template->sourcefile,
463                 template->compileflags
464             );
465             
466             /*
467              * The task template was compiled, now lets create a task from
468              * the template data which has now been propogated.
469              */
470             task_t task;
471             task.template = template;
472             if (!(task.handle = popen(buf, "r"))) {
473                 con_err("error opening pipe to process for test: %s\n", template->description);
474                 success = false;
475                 continue;
476             }
477             con_out("executing test: `%s` [%s]\n", template->description, buf);
478             
479             vec_push(task_tasks, task);
480         }
481     }
482     return success;
483 }
484
485 void task_destroy() {
486     size_t i;
487     for (i = 0; i < vec_size(task_tasks); i++)
488         task_template_destroy(&task_tasks[i].template);
489     vec_free(task_tasks);
490 }
491
492 /*
493  * This executes the QCVM task for a specificly compiled progs.dat
494  * using the template passed into it for call-flags and user defined
495  * messages.
496  */
497 bool task_execute(task_template_t *template) {
498     bool     success = false;
499     FILE    *execute;
500     char     buffer[4096];
501     memset  (buffer,0,sizeof(buffer));
502     
503     /*
504      * Drop the execution flags for the QCVM if none where
505      * actually specified.
506      */
507     if (!strcmp(template->executeflags, "$null")) {
508         snprintf(buffer,  sizeof(buffer), "%s %s %s",
509             task_bins[TASK_EXECUTE],
510             template->executeflags,
511             "progs.dat"
512         );
513     } else {
514         snprintf(buffer,  sizeof(buffer), "%s %s",
515             task_bins[TASK_EXECUTE],
516             "progs.dat"
517         );
518     }
519     
520     con_out("executing qcvm: `%s` [%s]\n",
521         template->description,
522         buffer
523     );
524     
525     execute = popen(buffer, "r");
526     if (!execute)
527         return false;
528         
529     /*
530      * Now lets read the lines and compare them to the matches we expect
531      * and handle accordingly.
532      */
533     {
534         char  *data  = NULL;
535         size_t size  = 0;
536         while (util_getline(&data, &size, execute) != EOF) {}
537         
538         if (!strcmp(data, "No main function found\n")) {
539             con_err("test failure: `%s` [%s] (No main function found)\n",
540                 template->description,
541                 (template->failuremessage) ?
542                 template->failuremessage : "unknown"
543             );
544             pclose(execute);
545             return false;
546         }
547         
548         /* null list */
549         if (!strcmp(template->comparematch, "$null"))
550             success = true;
551         
552         /*
553          * We only care about the last line from the output for now
554          * implementing multi-line match is TODO.
555          */
556         if (!strcmp(data, template->comparematch))
557             success = true;
558     }
559     pclose(execute);
560     return success;
561 }
562
563 /*
564  * This schedualizes all tasks and actually runs them individually
565  * this is generally easy for just -compile variants.  For compile and
566  * execution this takes more work since a task needs to be generated
567  * from thin air and executed INLINE.
568  */
569 void task_schedualize() {
570     bool   execute = false;
571     char  *back    = NULL;
572     char  *data    = NULL;
573     size_t size    = 0;
574     size_t i;
575     
576     for (i = 0; i < vec_size(task_tasks); i++) {
577         /*
578         * Generate a task from thin air if it requires execution in
579         * the QCVM.
580         */
581         if (!strcmp(task_tasks[i].template->proceduretype, "-execute"))
582             execute = true;
583             
584         while (util_getline(&data, &size, task_tasks[i].handle) != EOF) {
585             back = data;
586             /* chances are we want to print errors */
587             if (strstr(data, "error")) {
588                 con_out("compile failed: %s\n",
589                     /* strip the newline from the end */
590                     (*strrchr(data, '\n')='\0')
591                 );
592                 
593                 /*
594                  * The compilation failed which means it cannot be executed
595                  * as the file simply will not exist.
596                  */
597                 execute = false;
598                 break;
599             }
600         }
601         if (back)
602             mem_d(back);
603         
604         /*
605          * If we can execute we do so after all data has been read and
606          * this paticular task has coupled execution in its procedure type
607          */
608         if (!execute)
609             continue;
610         
611         /*
612          * If we made it here that concludes the task is to be executed
613          * in the virtual machine.
614          */
615         if (!task_execute(task_tasks[i].template)) {
616             con_err("test failure: `%s` [%s]\n",
617                 task_tasks[i].template->description,
618                 (task_tasks[i].template->failuremessage) ?
619                 task_tasks[i].template->failuremessage : "unknown"
620             );
621             continue;
622         }
623         
624         con_out("test succeed: `%s` [%s]\n",
625             task_tasks[i].template->description,
626             (task_tasks[i].template->successmessage) ?
627             task_tasks[i].template->successmessage  : "unknown"
628         );
629         
630         /*
631          * We need to unlink the progs.dat file that is sitting around
632          * collecting dust.
633          */
634         unlink("progs.dat");
635     }
636     if (back)
637         mem_d(back);
638 }
639
640 int main(int argc, char **argv) {
641     con_init();
642     if (!task_propogate("tests")) {
643         con_err("error: failed to propogate tasks\n");
644         task_destroy();
645         return -1;
646     }
647     /*
648      * If we made it here all tasks where propogated from their resultant
649      * template file.  So we can start the FILO scheduler, this has been
650      * designed in the most thread-safe way possible for future threading
651      * it's designed to prevent lock contention, and possible syncronization
652      * issues.
653      */
654     task_schedualize();
655     
656     task_destroy();
657     util_meminfo();
658     return 0;
659 }