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