]> git.xonotic.org Git - xonotic/gmqcc.git/blob - exec.c
Replaced it all...
[xonotic/gmqcc.git] / exec.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *     Dale Weiler
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #ifndef QCVM_LOOP
25 #include <errno.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdarg.h>
29
30 #include "gmqcc.h"
31
32 /*
33 (prog_section_statement, code)
34 (prog_section_def,       defs)
35 (prog_section_def,       fields)
36 (prog_section_function,  functions)
37 (char,                   strings)
38 (qcint,                  globals)
39 (qcint,                  entitydata)
40 (bool,                   entitypool)
41 (qcint,         localstack)
42 (qc_exec_stack, stack)
43 (size_t, profile)
44 (prog_builtin, builtins)
45 (const char*, function_stack)
46 */
47
48 static void loaderror(const char *fmt, ...)
49 {
50     int     err = errno;
51     va_list ap;
52     va_start(ap, fmt);
53     vprintf(fmt, ap);
54     va_end(ap);
55     printf(": %s\n", strerror(err));
56 }
57
58 static void qcvmerror(qc_program *prog, const char *fmt, ...)
59 {
60     va_list ap;
61
62     prog->vmerror++;
63
64     va_start(ap, fmt);
65     vprintf(fmt, ap);
66     va_end(ap);
67     putchar('\n');
68 }
69
70 qc_program* prog_load(const char *filename)
71 {
72     qc_program *prog;
73     prog_header header;
74     FILE *file;
75
76     file = util_fopen(filename, "rb");
77     if (!file)
78         return NULL;
79
80     if (fread(&header, sizeof(header), 1, file) != 1) {
81         loaderror("failed to read header from '%s'", filename);
82         fclose(file);
83         return NULL;
84     }
85
86     if (header.version != 6) {
87         loaderror("header says this is a version %i progs, we need version 6\n", header.version);
88         fclose(file);
89         return NULL;
90     }
91
92     prog = (qc_program*)mem_a(sizeof(qc_program));
93     if (!prog) {
94         fclose(file);
95         printf("failed to allocate program data\n");
96         return NULL;
97     }
98     memset(prog, 0, sizeof(*prog));
99
100     prog->entityfields = header.entfield;
101     prog->crc16 = header.crc16;
102
103     prog->filename = util_strdup(filename);
104     if (!prog->filename) {
105         loaderror("failed to store program name");
106         goto error;
107     }
108
109 #define read_data(hdrvar, progvar, reserved)                           \
110     if (fseek(file, header.hdrvar.offset, SEEK_SET) != 0) {            \
111         loaderror("seek failed");                                      \
112         goto error;                                                    \
113     }                                                                  \
114     if (fread(vec_add(prog->progvar, header.hdrvar.length + reserved), \
115               sizeof(*prog->progvar),                                  \
116               header.hdrvar.length, file)                              \
117         != header.hdrvar.length)                                       \
118     {                                                                  \
119         loaderror("read failed");                                      \
120         goto error;                                                    \
121     }
122 #define read_data1(x)    read_data(x, x, 0)
123 #define read_data2(x, y) read_data(x, x, y)
124
125     read_data (statements, code, 0);
126     read_data1(defs);
127     read_data1(fields);
128     read_data1(functions);
129     read_data1(strings);
130     read_data2(globals, 2); /* reserve more in case a RETURN using with the global at "the end" exists */
131
132     fclose(file);
133
134     /* profile counters */
135     memset(vec_add(prog->profile, vec_size(prog->code)), 0, sizeof(prog->profile[0]) * vec_size(prog->code));
136
137     /* Add tempstring area */
138     prog->tempstring_start = vec_size(prog->strings);
139     prog->tempstring_at    = vec_size(prog->strings);
140     memset(vec_add(prog->strings, 16*1024), 0, 16*1024);
141
142     /* spawn the world entity */
143     vec_push(prog->entitypool, true);
144     memset(vec_add(prog->entitydata, prog->entityfields), 0, prog->entityfields * sizeof(prog->entitydata[0]));
145     prog->entities = 1;
146
147     return prog;
148
149 error:
150     if (prog->filename)
151         mem_d(prog->filename);
152     vec_free(prog->code);
153     vec_free(prog->defs);
154     vec_free(prog->fields);
155     vec_free(prog->functions);
156     vec_free(prog->strings);
157     vec_free(prog->globals);
158     vec_free(prog->entitydata);
159     vec_free(prog->entitypool);
160     mem_d(prog);
161     return NULL;
162 }
163
164 void prog_delete(qc_program *prog)
165 {
166     if (prog->filename) mem_d(prog->filename);
167     vec_free(prog->code);
168     vec_free(prog->defs);
169     vec_free(prog->fields);
170     vec_free(prog->functions);
171     vec_free(prog->strings);
172     vec_free(prog->globals);
173     vec_free(prog->entitydata);
174     vec_free(prog->entitypool);
175     vec_free(prog->localstack);
176     vec_free(prog->stack);
177     vec_free(prog->profile);
178     mem_d(prog);
179 }
180
181 /***********************************************************************
182  * VM code
183  */
184
185 char* prog_getstring(qc_program *prog, qcint str)
186 {
187     if (str < 0 || str >= vec_size(prog->strings))
188         return "<<<invalid string>>>";
189     return prog->strings + str;
190 }
191
192 prog_section_def* prog_entfield(qc_program *prog, qcint off)
193 {
194     size_t i;
195     for (i = 0; i < vec_size(prog->fields); ++i) {
196         if (prog->fields[i].offset == off)
197             return (prog->fields + i);
198     }
199     return NULL;
200 }
201
202 prog_section_def* prog_getdef(qc_program *prog, qcint off)
203 {
204     size_t i;
205     for (i = 0; i < vec_size(prog->defs); ++i) {
206         if (prog->defs[i].offset == off)
207             return (prog->defs + i);
208     }
209     return NULL;
210 }
211
212 qcany* prog_getedict(qc_program *prog, qcint e)
213 {
214     if (e >= vec_size(prog->entitypool)) {
215         prog->vmerror++;
216         printf("Accessing out of bounds edict %i\n", (int)e);
217         e = 0;
218     }
219     return (qcany*)(prog->entitydata + (prog->entityfields * e));
220 }
221
222 qcint prog_spawn_entity(qc_program *prog)
223 {
224     char  *data;
225     qcint  e;
226     for (e = 0; e < (qcint)vec_size(prog->entitypool); ++e) {
227         if (!prog->entitypool[e]) {
228             data = (char*)(prog->entitydata + (prog->entityfields * e));
229             memset(data, 0, prog->entityfields * sizeof(qcint));
230             return e;
231         }
232     }
233     vec_push(prog->entitypool, true);
234     prog->entities++;
235     data = (char*)vec_add(prog->entitydata, prog->entityfields);
236     memset(data, 0, prog->entityfields * sizeof(qcint));
237     return e;
238 }
239
240 void prog_free_entity(qc_program *prog, qcint e)
241 {
242     if (!e) {
243         prog->vmerror++;
244         printf("Trying to free world entity\n");
245         return;
246     }
247     if (e >= vec_size(prog->entitypool)) {
248         prog->vmerror++;
249         printf("Trying to free out of bounds entity\n");
250         return;
251     }
252     if (!prog->entitypool[e]) {
253         prog->vmerror++;
254         printf("Double free on entity\n");
255         return;
256     }
257     prog->entitypool[e] = false;
258 }
259
260 qcint prog_tempstring(qc_program *prog, const char *_str)
261 {
262     /* we don't access it, but the macro-generated functions don't use
263      * const
264      */
265     char *str = (char*)_str;
266
267     size_t len = strlen(str);
268     size_t at = prog->tempstring_at;
269
270     /* when we reach the end we start over */
271     if (at + len >= vec_size(prog->strings))
272         at = prog->tempstring_start;
273
274     /* when it doesn't fit, reallocate */
275     if (at + len >= vec_size(prog->strings))
276     {
277         (void)vec_add(prog->strings, len+1);
278         memcpy(prog->strings + at, str, len+1);
279         return at;
280     }
281
282     /* when it fits, just copy */
283     memcpy(prog->strings + at, str, len+1);
284     prog->tempstring_at += len+1;
285     return at;
286 }
287
288 static int print_escaped_string(const char *str, size_t maxlen)
289 {
290     int len = 2;
291     putchar('"');
292     --maxlen; /* because we're lazy and have escape sequences */
293     while (*str) {
294         if (len >= maxlen) {
295             putchar('.');
296             putchar('.');
297             putchar('.');
298             len += 3;
299             break;
300         }
301         switch (*str) {
302             case '\a': len += 2; putchar('\\'); putchar('a'); break;
303             case '\b': len += 2; putchar('\\'); putchar('b'); break;
304             case '\r': len += 2; putchar('\\'); putchar('r'); break;
305             case '\n': len += 2; putchar('\\'); putchar('n'); break;
306             case '\t': len += 2; putchar('\\'); putchar('t'); break;
307             case '\f': len += 2; putchar('\\'); putchar('f'); break;
308             case '\v': len += 2; putchar('\\'); putchar('v'); break;
309             case '\\': len += 2; putchar('\\'); putchar('\\'); break;
310             case '"':  len += 2; putchar('\\'); putchar('"'); break;
311             default:
312                 ++len;
313                 putchar(*str);
314                 break;
315         }
316         ++str;
317     }
318     putchar('"');
319     return len;
320 }
321
322 static void trace_print_global(qc_program *prog, unsigned int glob, int vtype)
323 {
324     static char spaces[28+1] = "                            ";
325     prog_section_def *def;
326     qcany    *value;
327     int       len;
328
329     if (!glob) {
330         len = printf("<null>,");
331         goto done;
332     }
333
334     def = prog_getdef(prog, glob);
335     value = (qcany*)(&prog->globals[glob]);
336
337     if (def) {
338         const char *name = prog_getstring(prog, def->name);
339         if (name[0] == '#')
340             len = printf("$");
341         else
342             len = printf("%s ", name);
343         vtype = def->type & DEF_TYPEMASK;
344     }
345     else
346         len = printf("[@%u] ", glob);
347
348     switch (vtype) {
349         case TYPE_VOID:
350         case TYPE_ENTITY:
351         case TYPE_FIELD:
352         case TYPE_FUNCTION:
353         case TYPE_POINTER:
354             len += printf("(%i),", value->_int);
355             break;
356         case TYPE_VECTOR:
357             len += printf("'%g %g %g',", value->vector[0],
358                                          value->vector[1],
359                                          value->vector[2]);
360             break;
361         case TYPE_STRING:
362             len += print_escaped_string(prog_getstring(prog, value->string), sizeof(spaces)-len-5);
363             len += printf(",");
364             /* len += printf("\"%s\",", prog_getstring(prog, value->string)); */
365             break;
366         case TYPE_FLOAT:
367         default:
368             len += printf("%g,", value->_float);
369             break;
370     }
371 done:
372     if (len < sizeof(spaces)-1) {
373         spaces[sizeof(spaces)-1-len] = 0;
374         printf(spaces);
375         spaces[sizeof(spaces)-1-len] = ' ';
376     }
377 }
378
379 static void prog_print_statement(qc_program *prog, prog_section_statement *st)
380 {
381     if (st->opcode >= (sizeof(asm_instr)/sizeof(asm_instr[0]))) {
382         printf("<illegal instruction %d>\n", st->opcode);
383         return;
384     }
385     if ((prog->xflags & VMXF_TRACE) && vec_size(prog->function_stack)) {
386         size_t i;
387         for (i = 0; i < vec_size(prog->function_stack); ++i)
388             printf("->");
389         printf("%s:", vec_last(prog->function_stack));
390     }
391     printf(" <> %-12s", asm_instr[st->opcode].m);
392     if (st->opcode >= INSTR_IF &&
393         st->opcode <= INSTR_IFNOT)
394     {
395         trace_print_global(prog, st->o1.u1, TYPE_FLOAT);
396         printf("%d\n", st->o2.s1);
397     }
398     else if (st->opcode >= INSTR_CALL0 &&
399              st->opcode <= INSTR_CALL8)
400     {
401         trace_print_global(prog, st->o1.u1, TYPE_FUNCTION);
402         printf("\n");
403     }
404     else if (st->opcode == INSTR_GOTO)
405     {
406         printf("%i\n", st->o1.s1);
407     }
408     else
409     {
410         int t[3] = { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT };
411         switch (st->opcode)
412         {
413             case INSTR_MUL_FV:
414                 t[1] = t[2] = TYPE_VECTOR;
415                 break;
416             case INSTR_MUL_VF:
417                 t[0] = t[2] = TYPE_VECTOR;
418                 break;
419             case INSTR_MUL_V:
420                 t[0] = t[1] = TYPE_VECTOR;
421                 break;
422             case INSTR_ADD_V:
423             case INSTR_SUB_V:
424             case INSTR_EQ_V:
425             case INSTR_NE_V:
426                 t[0] = t[1] = t[2] = TYPE_VECTOR;
427                 break;
428             case INSTR_EQ_S:
429             case INSTR_NE_S:
430                 t[0] = t[1] = TYPE_STRING;
431                 break;
432             case INSTR_STORE_F:
433             case INSTR_STOREP_F:
434                 t[2] = -1;
435                 break;
436             case INSTR_STORE_V:
437                 t[0] = t[1] = TYPE_VECTOR; t[2] = -1;
438                 break;
439             case INSTR_STORE_S:
440                 t[0] = t[1] = TYPE_STRING; t[2] = -1;
441                 break;
442             case INSTR_STORE_ENT:
443                 t[0] = t[1] = TYPE_ENTITY; t[2] = -1;
444                 break;
445             case INSTR_STORE_FLD:
446                 t[0] = t[1] = TYPE_FIELD; t[2] = -1;
447                 break;
448             case INSTR_STORE_FNC:
449                 t[0] = t[1] = TYPE_FUNCTION; t[2] = -1;
450                 break;
451             case INSTR_STOREP_V:
452                 t[0] = TYPE_VECTOR; t[1] = TYPE_ENTITY; t[2] = -1;
453                 break;
454             case INSTR_STOREP_S:
455                 t[0] = TYPE_STRING; t[1] = TYPE_ENTITY; t[2] = -1;
456                 break;
457             case INSTR_STOREP_ENT:
458                 t[0] = TYPE_ENTITY; t[1] = TYPE_ENTITY; t[2] = -1;
459                 break;
460             case INSTR_STOREP_FLD:
461                 t[0] = TYPE_FIELD; t[1] = TYPE_ENTITY; t[2] = -1;
462                 break;
463             case INSTR_STOREP_FNC:
464                 t[0] = TYPE_FUNCTION; t[1] = TYPE_ENTITY; t[2] = -1;
465                 break;
466         }
467         if (t[0] >= 0) trace_print_global(prog, st->o1.u1, t[0]);
468         else           printf("(none),          ");
469         if (t[1] >= 0) trace_print_global(prog, st->o2.u1, t[1]);
470         else           printf("(none),          ");
471         if (t[2] >= 0) trace_print_global(prog, st->o3.u1, t[2]);
472         else           printf("(none)");
473         printf("\n");
474     }
475     fflush(stdout);
476 }
477
478 static qcint prog_enterfunction(qc_program *prog, prog_section_function *func)
479 {
480     qc_exec_stack st;
481     size_t p, parampos;
482
483     /* back up locals */
484     st.localsp  = vec_size(prog->localstack);
485     st.stmt     = prog->statement;
486     st.function = func;
487
488     if (prog->xflags & VMXF_TRACE) {
489         vec_push(prog->function_stack, prog_getstring(prog, func->name));
490     }
491
492 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
493     if (vec_size(prog->stack))
494     {
495         prog_section_function *cur;
496         cur = prog->stack[vec_size(prog->stack)-1].function;
497         if (cur)
498         {
499             qcint *globals = prog->globals + cur->firstlocal;
500             vec_append(prog->localstack, cur->locals, globals);
501         }
502     }
503 #else
504     {
505         qcint *globals = prog->globals + func->firstlocal;
506         vec_append(prog->localstack, func->locals, globals);
507     }
508 #endif
509
510     /* copy parameters */
511     parampos = func->firstlocal;
512     for (p = 0; p < func->nargs; ++p)
513     {
514         size_t s;
515         for (s = 0; s < func->argsize[p]; ++s) {
516             prog->globals[parampos] = prog->globals[OFS_PARM0 + 3*p + s];
517             ++parampos;
518         }
519     }
520
521     vec_push(prog->stack, st);
522
523     return func->entry;
524 }
525
526 static qcint prog_leavefunction(qc_program *prog)
527 {
528     prog_section_function *prev = NULL;
529     size_t oldsp;
530
531     qc_exec_stack st = vec_last(prog->stack);
532
533     if (prog->xflags & VMXF_TRACE) {
534         if (vec_size(prog->function_stack))
535             vec_pop(prog->function_stack);
536     }
537
538 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
539     if (vec_size(prog->stack) > 1) {
540         prev  = prog->stack[vec_size(prog->stack)-2].function;
541         oldsp = prog->stack[vec_size(prog->stack)-2].localsp;
542     }
543 #else
544     prev  = prog->stack[vec_size(prog->stack)-1].function;
545     oldsp = prog->stack[vec_size(prog->stack)-1].localsp;
546 #endif
547     if (prev) {
548         qcint *globals = prog->globals + prev->firstlocal;
549         memcpy(globals, prog->localstack + oldsp, prev->locals);
550         /* vec_remove(prog->localstack, oldsp, vec_size(prog->localstack)-oldsp); */
551         vec_shrinkto(prog->localstack, oldsp);
552     }
553
554     vec_pop(prog->stack);
555
556     return st.stmt - 1; /* offset the ++st */
557 }
558
559 bool prog_exec(qc_program *prog, prog_section_function *func, size_t flags, long maxjumps)
560 {
561     long jumpcount = 0;
562     size_t oldxflags = prog->xflags;
563     prog_section_statement *st;
564
565     prog->vmerror = 0;
566     prog->xflags = flags;
567
568     st = prog->code + prog_enterfunction(prog, func);
569     --st;
570     switch (flags)
571     {
572         default:
573         case 0:
574         {
575 #define QCVM_LOOP    1
576 #define QCVM_PROFILE 0
577 #define QCVM_TRACE   0
578 #           include __FILE__
579             break;
580         }
581         case (VMXF_TRACE):
582         {
583 #define QCVM_PROFILE 0
584 #define QCVM_TRACE   1
585 #           include __FILE__
586             break;
587         }
588         case (VMXF_PROFILE):
589         {
590 #define QCVM_PROFILE 1
591 #define QCVM_TRACE   0
592 #           include __FILE__
593             break;
594         }
595         case (VMXF_TRACE|VMXF_PROFILE):
596         {
597 #define QCVM_PROFILE 1
598 #define QCVM_TRACE   1
599 #           include __FILE__
600             break;
601         }
602     };
603
604 cleanup:
605     prog->xflags = oldxflags;
606     vec_free(prog->localstack);
607     vec_free(prog->stack);
608     if (prog->vmerror)
609         return false;
610     return true;
611 }
612
613 /***********************************************************************
614  * main for when building the standalone executor
615  */
616
617 #if defined(QCVM_EXECUTOR)
618 #include <math.h>
619
620 const char *type_name[TYPE_COUNT] = {
621     "void",
622     "string",
623     "float",
624     "vector",
625     "entity",
626     "field",
627     "function",
628     "pointer",
629 #if 0
630     "integer",
631 #endif
632     "variant"
633 };
634
635 bool        opts_debug    = false;
636 bool        opts_memchk   = false;
637
638 typedef struct {
639     int         vtype;
640     const char *value;
641 } qcvm_parameter;
642
643 qcvm_parameter *main_params = NULL;
644
645 #define CheckArgs(num) do {                                                    \
646     if (prog->argc != (num)) {                                                 \
647         prog->vmerror++;                                                       \
648         printf("ERROR: invalid number of arguments for %s: %i, expected %i\n", \
649         __FUNCTION__, prog->argc, (num));                                      \
650         return -1;                                                             \
651     }                                                                          \
652 } while (0)
653
654 #define GetGlobal(idx) ((qcany*)(prog->globals + (idx)))
655 #define GetArg(num) GetGlobal(OFS_PARM0 + 3*(num))
656 #define Return(any) *(GetGlobal(OFS_RETURN)) = (any)
657
658 static int qc_print(qc_program *prog)
659 {
660     size_t i;
661     const char *laststr = NULL;
662     for (i = 0; i < prog->argc; ++i) {
663         qcany *str = (qcany*)(prog->globals + OFS_PARM0 + 3*i);
664         printf("%s", (laststr = prog_getstring(prog, str->string)));
665     }
666     if (laststr && (prog->xflags & VMXF_TRACE)) {
667         size_t len = strlen(laststr);
668         if (!len || laststr[len-1] != '\n')
669             printf("\n");
670     }
671     return 0;
672 }
673
674 static int qc_error(qc_program *prog)
675 {
676     printf("*** VM raised an error:\n");
677     qc_print(prog);
678     prog->vmerror++;
679     return -1;
680 }
681
682 static int qc_ftos(qc_program *prog)
683 {
684     char buffer[512];
685     qcany *num;
686     qcany str;
687     CheckArgs(1);
688     num = GetArg(0);
689     snprintf(buffer, sizeof(buffer), "%g", num->_float);
690     str.string = prog_tempstring(prog, buffer);
691     Return(str);
692     return 0;
693 }
694
695 static int qc_vtos(qc_program *prog)
696 {
697     char buffer[512];
698     qcany *num;
699     qcany str;
700     CheckArgs(1);
701     num = GetArg(0);
702     snprintf(buffer, sizeof(buffer), "'%g %g %g'", num->vector[0], num->vector[1], num->vector[2]);
703     str.string = prog_tempstring(prog, buffer);
704     Return(str);
705     return 0;
706 }
707
708 static int qc_etos(qc_program *prog)
709 {
710     char buffer[512];
711     qcany *num;
712     qcany str;
713     CheckArgs(1);
714     num = GetArg(0);
715     snprintf(buffer, sizeof(buffer), "%i", num->_int);
716     str.string = prog_tempstring(prog, buffer);
717     Return(str);
718     return 0;
719 }
720
721 static int qc_spawn(qc_program *prog)
722 {
723     qcany ent;
724     CheckArgs(0);
725     ent.edict = prog_spawn_entity(prog);
726     Return(ent);
727     return (ent.edict ? 0 : -1);
728 }
729
730 static int qc_kill(qc_program *prog)
731 {
732     qcany *ent;
733     CheckArgs(1);
734     ent = GetArg(0);
735     prog_free_entity(prog, ent->edict);
736     return 0;
737 }
738
739 static int qc_vlen(qc_program *prog)
740 {
741     qcany *vec, len;
742     CheckArgs(1);
743     vec = GetArg(0);
744     len._float = sqrt(vec->vector[0] * vec->vector[0] + 
745                       vec->vector[1] * vec->vector[1] +
746                       vec->vector[2] * vec->vector[2]);
747     Return(len);
748     return 0;
749 }
750
751 static prog_builtin qc_builtins[] = {
752     NULL,
753     &qc_print, /*   1   */
754     &qc_ftos,  /*   2   */
755     &qc_spawn, /*   3   */
756     &qc_kill,  /*   4   */
757     &qc_vtos,  /*   5   */
758     &qc_error, /*   6   */
759     &qc_vlen,  /*   7   */
760     &qc_etos   /*   8   */
761 };
762 static size_t qc_builtins_count = sizeof(qc_builtins) / sizeof(qc_builtins[0]);
763
764 static const char *arg0 = NULL;
765
766 void usage()
767 {
768     printf("usage: [-debug] %s file\n", arg0);
769     exit(1);
770 }
771
772 static void prog_main_setparams(qc_program *prog)
773 {
774     size_t i;
775     qcany *arg;
776
777     for (i = 0; i < vec_size(main_params); ++i) {
778         arg = GetGlobal(OFS_PARM0 + 3*i);
779         arg->vector[0] = 0;
780         arg->vector[1] = 0;
781         arg->vector[2] = 0;
782         switch (main_params[i].vtype) {
783             case TYPE_VECTOR:
784 #ifdef WIN32
785                 (void)sscanf_s(main_params[i].value, " %f %f %f ",
786                                &arg->vector[0],
787                                &arg->vector[1],
788                                &arg->vector[2]);
789 #else
790                 (void)sscanf(main_params[i].value, " %f %f %f ",
791                              &arg->vector[0],
792                              &arg->vector[1],
793                              &arg->vector[2]);
794 #endif
795                 break;
796             case TYPE_FLOAT:
797                 arg->_float = atof(main_params[i].value);
798                 break;
799             case TYPE_STRING:
800                 arg->string = prog_tempstring(prog, main_params[i].value);
801                 break;
802             default:
803                 printf("error: unhandled parameter type: %i\n", main_params[i].vtype);
804                 break;
805         }
806     }
807 }
808
809 void prog_disasm_function(qc_program *prog, size_t id);
810 int main(int argc, char **argv)
811 {
812     size_t      i;
813     qcint       fnmain = -1;
814     qc_program *prog;
815     size_t      xflags = VMXF_DEFAULT;
816     bool        opts_printfields = false;
817     bool        opts_printdefs   = false;
818     bool        opts_disasm      = false;
819     bool        opts_info  = false;
820
821     arg0 = argv[0];
822
823     if (argc < 2)
824         usage();
825
826     while (argc > 2) {
827         if (!strcmp(argv[1], "-trace")) {
828             --argc;
829             ++argv;
830             xflags |= VMXF_TRACE;
831         }
832         else if (!strcmp(argv[1], "-profile")) {
833             --argc;
834             ++argv;
835             xflags |= VMXF_PROFILE;
836         }
837         else if (!strcmp(argv[1], "-info")) {
838             --argc;
839             ++argv;
840             opts_info = true;
841         }
842         else if (!strcmp(argv[1], "-disasm")) {
843             --argc;
844             ++argv;
845             opts_disasm = true;
846         }
847         else if (!strcmp(argv[1], "-printdefs")) {
848             --argc;
849             ++argv;
850             opts_printdefs = true;
851         }
852         else if (!strcmp(argv[1], "-printfields")) {
853             --argc;
854             ++argv;
855             opts_printfields = true;
856         }
857         else if (!strcmp(argv[1], "-vector") ||
858                  !strcmp(argv[1], "-string") ||
859                  !strcmp(argv[1], "-float") )
860         {
861             qcvm_parameter p;
862             if (argv[1][1] == 'f')
863                 p.vtype = TYPE_FLOAT;
864             else if (argv[1][1] == 's')
865                 p.vtype = TYPE_STRING;
866             else if (argv[1][1] == 'v')
867                 p.vtype = TYPE_VECTOR;
868
869             --argc;
870             ++argv;
871             if (argc < 3)
872                 usage();
873             p.value = argv[1];
874
875             vec_push(main_params, p);
876             --argc;
877             ++argv;
878         }
879         else
880             usage();
881     }
882
883
884     prog = prog_load(argv[1]);
885     if (!prog) {
886         printf("failed to load program '%s'\n", argv[1]);
887         exit(1);
888     }
889
890     prog->builtins       = qc_builtins;
891     prog->builtins_count = qc_builtins_count;
892
893     if (opts_info) {
894         printf("Program's system-checksum = 0x%04x\n", (int)prog->crc16);
895         printf("Entity field space: %i\n", (int)prog->entityfields);
896     }
897
898     for (i = 1; i < vec_size(prog->functions); ++i) {
899         const char *name = prog_getstring(prog, prog->functions[i].name);
900         /* printf("Found function: %s\n", name); */
901         if (!strcmp(name, "main"))
902             fnmain = (qcint)i;
903     }
904     if (opts_info) {
905         prog_delete(prog);
906         return 0;
907     }
908     if (opts_disasm) {
909         for (i = 1; i < vec_size(prog->functions); ++i)
910             prog_disasm_function(prog, i);
911         return 0;
912     }
913     if (opts_printdefs) {
914         for (i = 0; i < vec_size(prog->defs); ++i) {
915             printf("Global: %8s %-16s at %u\n",
916                    type_name[prog->defs[i].type & DEF_TYPEMASK],
917                    prog_getstring(prog, prog->defs[i].name),
918                    (unsigned int)prog->defs[i].offset);
919         }
920     }
921     else if (opts_printfields) {
922         for (i = 0; i < vec_size(prog->fields); ++i) {
923             printf("Field: %8s %-16s at %u\n",
924                    type_name[prog->fields[i].type],
925                    prog_getstring(prog, prog->fields[i].name),
926                    (unsigned int)prog->fields[i].offset);
927         }
928     }
929     else
930     {
931         if (fnmain > 0)
932         {
933             prog_main_setparams(prog);
934             prog_exec(prog, &prog->functions[fnmain], xflags, VM_JUMPS_DEFAULT);
935         }
936         else
937             printf("No main function found\n");
938     }
939
940     prog_delete(prog);
941     return 0;
942 }
943
944 void prog_disasm_function(qc_program *prog, size_t id)
945 {
946     prog_section_function *fdef = prog->functions + id;
947     prog_section_statement *st;
948
949     if (fdef->entry < 0) {
950         printf("FUNCTION \"%s\" = builtin #%i\n", prog_getstring(prog, fdef->name), (int)-fdef->entry);
951         return;
952     }
953     else
954         printf("FUNCTION \"%s\"\n", prog_getstring(prog, fdef->name));
955
956     st = prog->code + fdef->entry;
957     while (st->opcode != AINSTR_END) {
958         prog_print_statement(prog, st);
959         ++st;
960     }
961 }
962 #endif
963 #else /* !QCVM_LOOP */
964 /*
965  * Everything from here on is not including into the compilation of the
966  * executor.  This is simply code that is #included via #include __FILE__
967  * see when QCVM_LOOP is defined, the rest of the code above do not get
968  * re-included.  So this really just acts like one large macro, but it
969  * sort of isn't, which makes it nicer looking.
970  */
971
972 #define OPA ( (qcany*) (prog->globals + st->o1.u1) )
973 #define OPB ( (qcany*) (prog->globals + st->o2.u1) )
974 #define OPC ( (qcany*) (prog->globals + st->o3.u1) )
975
976 #define GLOBAL(x) ( (qcany*) (prog->globals + (x)) )
977
978 /* to be consistent with current darkplaces behaviour */
979 #if !defined(FLOAT_IS_TRUE_FOR_INT)
980 #   define FLOAT_IS_TRUE_FOR_INT(x) ( (x) & 0x7FFFFFFF )
981 #endif
982
983 while (1) {
984     prog_section_function  *newf;
985     qcany          *ed;
986     qcany          *ptr;
987
988     ++st;
989
990 #if QCVM_PROFILE
991     prog->profile[st - prog->code]++;
992 #endif
993
994 #if QCVM_TRACE
995     prog_print_statement(prog, st);
996 #endif
997
998     switch (st->opcode)
999     {
1000         default:
1001             qcvmerror(prog, "Illegal instruction in %s\n", prog->filename);
1002             goto cleanup;
1003
1004         case INSTR_DONE:
1005         case INSTR_RETURN:
1006             /* TODO: add instruction count to function profile count */
1007             GLOBAL(OFS_RETURN)->ivector[0] = OPA->ivector[0];
1008             GLOBAL(OFS_RETURN)->ivector[1] = OPA->ivector[1];
1009             GLOBAL(OFS_RETURN)->ivector[2] = OPA->ivector[2];
1010
1011             st = prog->code + prog_leavefunction(prog);
1012             if (!vec_size(prog->stack))
1013                 goto cleanup;
1014
1015             break;
1016
1017         case INSTR_MUL_F:
1018             OPC->_float = OPA->_float * OPB->_float;
1019             break;
1020         case INSTR_MUL_V:
1021             OPC->_float = OPA->vector[0]*OPB->vector[0] +
1022                           OPA->vector[1]*OPB->vector[1] +
1023                           OPA->vector[2]*OPB->vector[2];
1024             break;
1025         case INSTR_MUL_FV:
1026             OPC->vector[0] = OPA->_float * OPB->vector[0];
1027             OPC->vector[1] = OPA->_float * OPB->vector[1];
1028             OPC->vector[2] = OPA->_float * OPB->vector[2];
1029             break;
1030         case INSTR_MUL_VF:
1031             OPC->vector[0] = OPB->_float * OPA->vector[0];
1032             OPC->vector[1] = OPB->_float * OPA->vector[1];
1033             OPC->vector[2] = OPB->_float * OPA->vector[2];
1034             break;
1035         case INSTR_DIV_F:
1036             if (OPB->_float != 0.0f)
1037                 OPC->_float = OPA->_float / OPB->_float;
1038             else
1039                 OPC->_float = 0;
1040             break;
1041
1042         case INSTR_ADD_F:
1043             OPC->_float = OPA->_float + OPB->_float;
1044             break;
1045         case INSTR_ADD_V:
1046             OPC->vector[0] = OPA->vector[0] + OPB->vector[0];
1047             OPC->vector[1] = OPA->vector[1] + OPB->vector[1];
1048             OPC->vector[2] = OPA->vector[2] + OPB->vector[2];
1049             break;
1050         case INSTR_SUB_F:
1051             OPC->_float = OPA->_float - OPB->_float;
1052             break;
1053         case INSTR_SUB_V:
1054             OPC->vector[0] = OPA->vector[0] - OPB->vector[0];
1055             OPC->vector[1] = OPA->vector[1] - OPB->vector[1];
1056             OPC->vector[2] = OPA->vector[2] - OPB->vector[2];
1057             break;
1058
1059         case INSTR_EQ_F:
1060             OPC->_float = (OPA->_float == OPB->_float);
1061             break;
1062         case INSTR_EQ_V:
1063             OPC->_float = ((OPA->vector[0] == OPB->vector[0]) &&
1064                            (OPA->vector[1] == OPB->vector[1]) &&
1065                            (OPA->vector[2] == OPB->vector[2]) );
1066             break;
1067         case INSTR_EQ_S:
1068             OPC->_float = !strcmp(prog_getstring(prog, OPA->string),
1069                                   prog_getstring(prog, OPB->string));
1070             break;
1071         case INSTR_EQ_E:
1072             OPC->_float = (OPA->_int == OPB->_int);
1073             break;
1074         case INSTR_EQ_FNC:
1075             OPC->_float = (OPA->function == OPB->function);
1076             break;
1077         case INSTR_NE_F:
1078             OPC->_float = (OPA->_float != OPB->_float);
1079             break;
1080         case INSTR_NE_V:
1081             OPC->_float = ((OPA->vector[0] != OPB->vector[0]) ||
1082                            (OPA->vector[1] != OPB->vector[1]) ||
1083                            (OPA->vector[2] != OPB->vector[2]) );
1084             break;
1085         case INSTR_NE_S:
1086             OPC->_float = !!strcmp(prog_getstring(prog, OPA->string),
1087                                    prog_getstring(prog, OPB->string));
1088             break;
1089         case INSTR_NE_E:
1090             OPC->_float = (OPA->_int != OPB->_int);
1091             break;
1092         case INSTR_NE_FNC:
1093             OPC->_float = (OPA->function != OPB->function);
1094             break;
1095
1096         case INSTR_LE:
1097             OPC->_float = (OPA->_float <= OPB->_float);
1098             break;
1099         case INSTR_GE:
1100             OPC->_float = (OPA->_float >= OPB->_float);
1101             break;
1102         case INSTR_LT:
1103             OPC->_float = (OPA->_float < OPB->_float);
1104             break;
1105         case INSTR_GT:
1106             OPC->_float = (OPA->_float > OPB->_float);
1107             break;
1108
1109         case INSTR_LOAD_F:
1110         case INSTR_LOAD_S:
1111         case INSTR_LOAD_FLD:
1112         case INSTR_LOAD_ENT:
1113         case INSTR_LOAD_FNC:
1114             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1115                 qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename);
1116                 goto cleanup;
1117             }
1118             if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields)) {
1119                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1120                           prog->filename,
1121                           OPB->_int);
1122                 goto cleanup;
1123             }
1124             ed = prog_getedict(prog, OPA->edict);
1125             OPC->_int = ((qcany*)( ((qcint*)ed) + OPB->_int ))->_int;
1126             break;
1127         case INSTR_LOAD_V:
1128             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1129                 qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename);
1130                 goto cleanup;
1131             }
1132             if (OPB->_int < 0 || OPB->_int + 3 > prog->entityfields)
1133             {
1134                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1135                           prog->filename,
1136                           OPB->_int + 2);
1137                 goto cleanup;
1138             }
1139             ed = prog_getedict(prog, OPA->edict);
1140             OPC->ivector[0] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[0];
1141             OPC->ivector[1] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[1];
1142             OPC->ivector[2] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[2];
1143             break;
1144
1145         case INSTR_ADDRESS:
1146             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1147                 qcvmerror(prog, "prog `%s` attempted to address an out of bounds entity %i", prog->filename, OPA->edict);
1148                 goto cleanup;
1149             }
1150             if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields))
1151             {
1152                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1153                           prog->filename,
1154                           OPB->_int);
1155                 goto cleanup;
1156             }
1157
1158             ed = prog_getedict(prog, OPA->edict);
1159             OPC->_int = ((qcint*)ed) - prog->entitydata + OPB->_int;
1160             break;
1161
1162         case INSTR_STORE_F:
1163         case INSTR_STORE_S:
1164         case INSTR_STORE_ENT:
1165         case INSTR_STORE_FLD:
1166         case INSTR_STORE_FNC:
1167             OPB->_int = OPA->_int;
1168             break;
1169         case INSTR_STORE_V:
1170             OPB->ivector[0] = OPA->ivector[0];
1171             OPB->ivector[1] = OPA->ivector[1];
1172             OPB->ivector[2] = OPA->ivector[2];
1173             break;
1174
1175         case INSTR_STOREP_F:
1176         case INSTR_STOREP_S:
1177         case INSTR_STOREP_ENT:
1178         case INSTR_STOREP_FLD:
1179         case INSTR_STOREP_FNC:
1180             if (OPB->_int < 0 || OPB->_int >= vec_size(prog->entitydata)) {
1181                 qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int);
1182                 goto cleanup;
1183             }
1184             if (OPB->_int < prog->entityfields && !prog->allowworldwrites)
1185                 qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n",
1186                           prog->filename,
1187                           prog_getstring(prog, prog_entfield(prog, OPB->_int)->name),
1188                           OPB->_int);
1189             ptr = (qcany*)(prog->entitydata + OPB->_int);
1190             ptr->_int = OPA->_int;
1191             break;
1192         case INSTR_STOREP_V:
1193             if (OPB->_int < 0 || OPB->_int + 2 >= vec_size(prog->entitydata)) {
1194                 qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int);
1195                 goto cleanup;
1196             }
1197             if (OPB->_int < prog->entityfields && !prog->allowworldwrites)
1198                 qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n",
1199                           prog->filename,
1200                           prog_getstring(prog, prog_entfield(prog, OPB->_int)->name),
1201                           OPB->_int);
1202             ptr = (qcany*)(prog->entitydata + OPB->_int);
1203             ptr->ivector[0] = OPA->ivector[0];
1204             ptr->ivector[1] = OPA->ivector[1];
1205             ptr->ivector[2] = OPA->ivector[2];
1206             break;
1207
1208         case INSTR_NOT_F:
1209             OPC->_float = !FLOAT_IS_TRUE_FOR_INT(OPA->_int);
1210             break;
1211         case INSTR_NOT_V:
1212             OPC->_float = !OPA->vector[0] &&
1213                           !OPA->vector[1] &&
1214                           !OPA->vector[2];
1215             break;
1216         case INSTR_NOT_S:
1217             OPC->_float = !OPA->string ||
1218                           !*prog_getstring(prog, OPA->string);
1219             break;
1220         case INSTR_NOT_ENT:
1221             OPC->_float = (OPA->edict == 0);
1222             break;
1223         case INSTR_NOT_FNC:
1224             OPC->_float = !OPA->function;
1225             break;
1226
1227         case INSTR_IF:
1228             /* this is consistent with darkplaces' behaviour */
1229             if(FLOAT_IS_TRUE_FOR_INT(OPA->_int))
1230             {
1231                 st += st->o2.s1 - 1;    /* offset the s++ */
1232                 if (++jumpcount >= maxjumps)
1233                     qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1234             }
1235             break;
1236         case INSTR_IFNOT:
1237             if(!FLOAT_IS_TRUE_FOR_INT(OPA->_int))
1238             {
1239                 st += st->o2.s1 - 1;    /* offset the s++ */
1240                 if (++jumpcount >= maxjumps)
1241                     qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1242             }
1243             break;
1244
1245         case INSTR_CALL0:
1246         case INSTR_CALL1:
1247         case INSTR_CALL2:
1248         case INSTR_CALL3:
1249         case INSTR_CALL4:
1250         case INSTR_CALL5:
1251         case INSTR_CALL6:
1252         case INSTR_CALL7:
1253         case INSTR_CALL8:
1254             prog->argc = st->opcode - INSTR_CALL0;
1255             if (!OPA->function)
1256                 qcvmerror(prog, "NULL function in `%s`", prog->filename);
1257
1258             if(!OPA->function || OPA->function >= (unsigned int)vec_size(prog->functions))
1259             {
1260                 qcvmerror(prog, "CALL outside the program in `%s`", prog->filename);
1261                 goto cleanup;
1262             }
1263
1264             newf = &prog->functions[OPA->function];
1265             newf->profile++;
1266
1267             prog->statement = (st - prog->code) + 1;
1268
1269             if (newf->entry < 0)
1270             {
1271                 /* negative statements are built in functions */
1272                 int builtinnumber = -newf->entry;
1273                 if (builtinnumber < prog->builtins_count && prog->builtins[builtinnumber])
1274                     prog->builtins[builtinnumber](prog);
1275                 else
1276                     qcvmerror(prog, "No such builtin #%i in %s! Try updating your gmqcc sources",
1277                               builtinnumber, prog->filename);
1278             }
1279             else
1280                 st = prog->code + prog_enterfunction(prog, newf) - 1; /* offset st++ */
1281             if (prog->vmerror)
1282                 goto cleanup;
1283             break;
1284
1285         case INSTR_STATE:
1286             qcvmerror(prog, "`%s` tried to execute a STATE operation", prog->filename);
1287             break;
1288
1289         case INSTR_GOTO:
1290             st += st->o1.s1 - 1;    /* offset the s++ */
1291             if (++jumpcount == 10000000)
1292                 qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1293             break;
1294
1295         case INSTR_AND:
1296             OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) &&
1297                           FLOAT_IS_TRUE_FOR_INT(OPB->_int);
1298             break;
1299         case INSTR_OR:
1300             OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) ||
1301                           FLOAT_IS_TRUE_FOR_INT(OPB->_int);
1302             break;
1303
1304         case INSTR_BITAND:
1305             OPC->_float = ((int)OPA->_float) & ((int)OPB->_float);
1306             break;
1307         case INSTR_BITOR:
1308             OPC->_float = ((int)OPA->_float) | ((int)OPB->_float);
1309             break;
1310     }
1311 }
1312
1313 #undef QCVM_PROFILE
1314 #undef QCVM_TRACE
1315 #endif /* !QCVM_LOOP */