]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - exec.c
ee0fb1b38d149936bac8809779bc6c041b9ebf72
[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         printf("\n");
431     }
432     else if (st->opcode == INSTR_GOTO)
433     {
434         printf("%i\n", st->o1.s1);
435     }
436     else
437     {
438         int t[3] = { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT };
439         switch (st->opcode)
440         {
441             case INSTR_MUL_FV:
442                 t[1] = t[2] = TYPE_VECTOR;
443                 break;
444             case INSTR_MUL_VF:
445                 t[0] = t[2] = TYPE_VECTOR;
446                 break;
447             case INSTR_MUL_V:
448                 t[0] = t[1] = TYPE_VECTOR;
449                 break;
450             case INSTR_ADD_V:
451             case INSTR_SUB_V:
452             case INSTR_EQ_V:
453             case INSTR_NE_V:
454                 t[0] = t[1] = t[2] = TYPE_VECTOR;
455                 break;
456             case INSTR_EQ_S:
457             case INSTR_NE_S:
458                 t[0] = t[1] = TYPE_STRING;
459                 break;
460             case INSTR_STORE_F:
461             case INSTR_STOREP_F:
462                 t[2] = -1;
463                 break;
464             case INSTR_STORE_V:
465                 t[0] = t[1] = TYPE_VECTOR; t[2] = -1;
466                 break;
467             case INSTR_STORE_S:
468                 t[0] = t[1] = TYPE_STRING; t[2] = -1;
469                 break;
470             case INSTR_STORE_ENT:
471                 t[0] = t[1] = TYPE_ENTITY; t[2] = -1;
472                 break;
473             case INSTR_STORE_FLD:
474                 t[0] = t[1] = TYPE_FIELD; t[2] = -1;
475                 break;
476             case INSTR_STORE_FNC:
477                 t[0] = t[1] = TYPE_FUNCTION; t[2] = -1;
478                 break;
479             case INSTR_STOREP_V:
480                 t[0] = TYPE_VECTOR; t[1] = TYPE_ENTITY; t[2] = -1;
481                 break;
482             case INSTR_STOREP_S:
483                 t[0] = TYPE_STRING; t[1] = TYPE_ENTITY; t[2] = -1;
484                 break;
485             case INSTR_STOREP_ENT:
486                 t[0] = TYPE_ENTITY; t[1] = TYPE_ENTITY; t[2] = -1;
487                 break;
488             case INSTR_STOREP_FLD:
489                 t[0] = TYPE_FIELD; t[1] = TYPE_ENTITY; t[2] = -1;
490                 break;
491             case INSTR_STOREP_FNC:
492                 t[0] = TYPE_FUNCTION; t[1] = TYPE_ENTITY; t[2] = -1;
493                 break;
494         }
495         if (t[0] >= 0) trace_print_global(prog, st->o1.u1, t[0]);
496         else           printf("(none),          ");
497         if (t[1] >= 0) trace_print_global(prog, st->o2.u1, t[1]);
498         else           printf("(none),          ");
499         if (t[2] >= 0) trace_print_global(prog, st->o3.u1, t[2]);
500         else           printf("(none)");
501         printf("\n");
502     }
503     fflush(stdout);
504 }
505
506 static qcint prog_enterfunction(qc_program *prog, prog_section_function *func)
507 {
508     qc_exec_stack st;
509     size_t p, parampos;
510
511     /* back up locals */
512     st.localsp  = prog->localstack_count;
513     st.stmt     = prog->statement;
514     st.function = func;
515
516 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
517     if (prog->stack_count)
518     {
519         prog_section_function *cur;
520         cur = prog->stack[prog->stack_count-1].function;
521         if (cur)
522         {
523             qcint *globals = prog->globals + cur->firstlocal;
524             if (!qc_program_localstack_append(prog, globals, cur->locals))
525             {
526                 printf("out of memory\n");
527                 exit(1);
528             }
529         }
530     }
531 #else
532     {
533         qcint *globals = prog->globals + func->firstlocal;
534         if (!qc_program_localstack_append(prog, globals, func->locals))
535         {
536             printf("out of memory\n");
537             exit(1);
538         }
539     }
540 #endif
541
542     /* copy parameters */
543     parampos = func->firstlocal;
544     for (p = 0; p < func->nargs; ++p)
545     {
546         size_t s;
547         for (s = 0; s < func->argsize[p]; ++s) {
548             prog->globals[parampos] = prog->globals[OFS_PARM0 + 3*p + s];
549             ++parampos;
550         }
551     }
552
553     if (!qc_program_stack_add(prog, st)) {
554         printf("out of memory\n");
555         exit(1);
556     }
557
558     return func->entry;
559 }
560
561 static qcint prog_leavefunction(qc_program *prog)
562 {
563     prog_section_function *prev = NULL;
564     size_t oldsp;
565
566     qc_exec_stack st = prog->stack[prog->stack_count-1];
567
568 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
569     if (prog->stack_count > 1) {
570         prev  = prog->stack[prog->stack_count-2].function;
571         oldsp = prog->stack[prog->stack_count-2].localsp;
572     }
573 #else
574     prev  = prog->stack[prog->stack_count-1].function;
575     oldsp = prog->stack[prog->stack_count-1].localsp;
576 #endif
577     if (prev) {
578         qcint *globals = prog->globals + prev->firstlocal;
579         memcpy(globals, prog->localstack + oldsp, prev->locals);
580         if (!qc_program_localstack_resize(prog, oldsp)) {
581             printf("out of memory\n");
582             exit(1);
583         }
584     }
585
586     if (!qc_program_stack_remove(prog, prog->stack_count-1)) {
587         printf("out of memory\n");
588         exit(1);
589     }
590
591     return st.stmt - 1; /* offset the ++st */
592 }
593
594 bool prog_exec(qc_program *prog, prog_section_function *func, size_t flags, long maxjumps)
595 {
596     long jumpcount = 0;
597     size_t oldxflags = prog->xflags;
598     prog_section_statement *st;
599
600     prog->vmerror = 0;
601     prog->xflags = flags;
602
603     st = prog->code + prog_enterfunction(prog, func);
604     --st;
605     switch (flags)
606     {
607         default:
608         case 0:
609         {
610 #define QCVM_LOOP    1
611 #define QCVM_PROFILE 0
612 #define QCVM_TRACE   0
613 #           include __FILE__
614             break;
615         }
616         case (VMXF_TRACE):
617         {
618 #define QCVM_PROFILE 0
619 #define QCVM_TRACE   1
620 #           include __FILE__
621             break;
622         }
623         case (VMXF_PROFILE):
624         {
625 #define QCVM_PROFILE 1
626 #define QCVM_TRACE   0
627 #           include __FILE__
628             break;
629         }
630         case (VMXF_TRACE|VMXF_PROFILE):
631         {
632 #define QCVM_PROFILE 1
633 #define QCVM_TRACE   1
634 #           include __FILE__
635             break;
636         }
637     };
638
639 cleanup:
640     prog->xflags = oldxflags;
641     prog->localstack_count = 0;
642     prog->stack_count = 0;
643     if (prog->vmerror)
644         return false;
645     return true;
646 }
647
648 /***********************************************************************
649  * main for when building the standalone executor
650  */
651
652 #if defined(QCVM_EXECUTOR)
653 #include <math.h>
654
655 const char *type_name[TYPE_COUNT] = {
656     "void",
657     "string",
658     "float",
659     "vector",
660     "entity",
661     "field",
662     "function",
663     "pointer",
664 #if 0
665     "integer",
666 #endif
667     "variant"
668 };
669
670 bool        opts_debug    = false;
671 bool        opts_memchk   = false;
672
673 typedef struct {
674     int         vtype;
675     const char *value;
676 } qcvm_parameter;
677
678 VECTOR_MAKE(qcvm_parameter, main_params);
679
680 #define CheckArgs(num) do {                                                    \
681     if (prog->argc != (num)) {                                                 \
682         prog->vmerror++;                                                       \
683         printf("ERROR: invalid number of arguments for %s: %i, expected %i\n", \
684         __FUNCTION__, prog->argc, (num));                                      \
685         return -1;                                                             \
686     }                                                                          \
687 } while (0)
688
689 #define GetGlobal(idx) ((qcany*)(prog->globals + (idx)))
690 #define GetArg(num) GetGlobal(OFS_PARM0 + 3*(num))
691 #define Return(any) *(GetGlobal(OFS_RETURN)) = (any)
692
693 static int qc_print(qc_program *prog)
694 {
695     size_t i;
696     const char *laststr = NULL;
697     for (i = 0; i < prog->argc; ++i) {
698         qcany *str = (qcany*)(prog->globals + OFS_PARM0 + 3*i);
699         printf("%s", (laststr = prog_getstring(prog, str->string)));
700     }
701     if (laststr && (prog->xflags & VMXF_TRACE)) {
702         size_t len = strlen(laststr);
703         if (!len || laststr[len-1] != '\n')
704             printf("\n");
705     }
706     return 0;
707 }
708
709 static int qc_error(qc_program *prog)
710 {
711     printf("*** VM raised an error:\n");
712     qc_print(prog);
713     prog->vmerror++;
714     return -1;
715 }
716
717 static int qc_ftos(qc_program *prog)
718 {
719     char buffer[512];
720     qcany *num;
721     qcany str;
722     CheckArgs(1);
723     num = GetArg(0);
724     snprintf(buffer, sizeof(buffer), "%g", num->_float);
725     str.string = prog_tempstring(prog, buffer);
726     Return(str);
727     return 0;
728 }
729
730 static int qc_vtos(qc_program *prog)
731 {
732     char buffer[512];
733     qcany *num;
734     qcany str;
735     CheckArgs(1);
736     num = GetArg(0);
737     snprintf(buffer, sizeof(buffer), "'%g %g %g'", num->vector[0], num->vector[1], num->vector[2]);
738     str.string = prog_tempstring(prog, buffer);
739     Return(str);
740     return 0;
741 }
742
743 static int qc_etos(qc_program *prog)
744 {
745     char buffer[512];
746     qcany *num;
747     qcany str;
748     CheckArgs(1);
749     num = GetArg(0);
750     snprintf(buffer, sizeof(buffer), "%i", num->_int);
751     str.string = prog_tempstring(prog, buffer);
752     Return(str);
753     return 0;
754 }
755
756 static int qc_spawn(qc_program *prog)
757 {
758     qcany ent;
759     CheckArgs(0);
760     ent.edict = prog_spawn_entity(prog);
761     Return(ent);
762     return (ent.edict ? 0 : -1);
763 }
764
765 static int qc_kill(qc_program *prog)
766 {
767     qcany *ent;
768     CheckArgs(1);
769     ent = GetArg(0);
770     prog_free_entity(prog, ent->edict);
771     return 0;
772 }
773
774 static int qc_vlen(qc_program *prog)
775 {
776     qcany *vec, len;
777     CheckArgs(1);
778     vec = GetArg(0);
779     len._float = sqrt(vec->vector[0] * vec->vector[0] + 
780                       vec->vector[1] * vec->vector[1] +
781                       vec->vector[2] * vec->vector[2]);
782     Return(len);
783     return 0;
784 }
785
786 static prog_builtin qc_builtins[] = {
787     NULL,
788     &qc_print, /*   1   */
789     &qc_ftos,  /*   2   */
790     &qc_spawn, /*   3   */
791     &qc_kill,  /*   4   */
792     &qc_vtos,  /*   5   */
793     &qc_error, /*   6   */
794     &qc_vlen,  /*   7   */
795     &qc_etos   /*   8   */
796 };
797 static size_t qc_builtins_count = sizeof(qc_builtins) / sizeof(qc_builtins[0]);
798
799 static const char *arg0 = NULL;
800
801 void usage()
802 {
803     printf("usage: [-debug] %s file\n", arg0);
804     exit(1);
805 }
806
807 static void prog_main_setparams(qc_program *prog)
808 {
809     size_t i;
810     qcany *arg;
811
812     for (i = 0; i < main_params_elements; ++i) {
813         arg = GetGlobal(OFS_PARM0 + 3*i);
814         arg->vector[0] = 0;
815         arg->vector[1] = 0;
816         arg->vector[2] = 0;
817         switch (main_params_data[i].vtype) {
818             case TYPE_VECTOR:
819 #ifdef WIN32
820                 (void)sscanf_s(main_params_data[i].value, " %f %f %f ",
821                                &arg->vector[0],
822                                &arg->vector[1],
823                                &arg->vector[2]);
824 #else
825                 (void)sscanf(main_params_data[i].value, " %f %f %f ",
826                              &arg->vector[0],
827                              &arg->vector[1],
828                              &arg->vector[2]);
829 #endif
830                 break;
831             case TYPE_FLOAT:
832                 arg->_float = atof(main_params_data[i].value);
833                 break;
834             case TYPE_STRING:
835                 arg->string = prog_tempstring(prog, main_params_data[i].value);
836                 break;
837             default:
838                 printf("error: unhandled parameter type: %i\n", main_params_data[i].vtype);
839                 break;
840         }
841     }
842 }
843
844 void prog_disasm_function(qc_program *prog, size_t id);
845 int main(int argc, char **argv)
846 {
847     size_t      i;
848     qcint       fnmain = -1;
849     qc_program *prog;
850     size_t      xflags = VMXF_DEFAULT;
851     bool        opts_printfields = false;
852     bool        opts_printdefs   = false;
853     bool        opts_disasm      = false;
854     bool        opts_info  = false;
855
856     arg0 = argv[0];
857
858     if (argc < 2)
859         usage();
860
861     while (argc > 2) {
862         if (!strcmp(argv[1], "-trace")) {
863             --argc;
864             ++argv;
865             xflags |= VMXF_TRACE;
866         }
867         else if (!strcmp(argv[1], "-profile")) {
868             --argc;
869             ++argv;
870             xflags |= VMXF_PROFILE;
871         }
872         else if (!strcmp(argv[1], "-info")) {
873             --argc;
874             ++argv;
875             opts_info = true;
876         }
877         else if (!strcmp(argv[1], "-disasm")) {
878             --argc;
879             ++argv;
880             opts_disasm = true;
881         }
882         else if (!strcmp(argv[1], "-printdefs")) {
883             --argc;
884             ++argv;
885             opts_printdefs = true;
886         }
887         else if (!strcmp(argv[1], "-printfields")) {
888             --argc;
889             ++argv;
890             opts_printfields = true;
891         }
892         else if (!strcmp(argv[1], "-vector") ||
893                  !strcmp(argv[1], "-string") ||
894                  !strcmp(argv[1], "-float") )
895         {
896             qcvm_parameter p;
897             if (argv[1][1] == 'f')
898                 p.vtype = TYPE_FLOAT;
899             else if (argv[1][1] == 's')
900                 p.vtype = TYPE_STRING;
901             else if (argv[1][1] == 'v')
902                 p.vtype = TYPE_VECTOR;
903
904             --argc;
905             ++argv;
906             if (argc < 3)
907                 usage();
908             p.value = argv[1];
909
910             if (main_params_add(p) < 0) {
911                 if (main_params_data)
912                     mem_d(main_params_data);
913                 printf("cannot add parameter\n");
914                 exit(1);
915             }
916             --argc;
917             ++argv;
918         }
919         else
920             usage();
921     }
922
923
924     prog = prog_load(argv[1]);
925     if (!prog) {
926         printf("failed to load program '%s'\n", argv[1]);
927         exit(1);
928     }
929
930     prog->builtins       = qc_builtins;
931     prog->builtins_count = qc_builtins_count;
932     prog->builtins_alloc = 0;
933
934     if (opts_info) {
935         printf("Program's system-checksum = 0x%04x\n", (int)prog->crc16);
936         printf("Entity field space: %i\n", (int)prog->entityfields);
937     }
938
939     for (i = 1; i < prog->functions_count; ++i) {
940         const char *name = prog_getstring(prog, prog->functions[i].name);
941         /* printf("Found function: %s\n", name); */
942         if (!strcmp(name, "main"))
943             fnmain = (qcint)i;
944     }
945     if (opts_info) {
946         prog_delete(prog);
947         return 0;
948     }
949     if (opts_disasm) {
950         for (i = 1; i < prog->functions_count; ++i)
951             prog_disasm_function(prog, i);
952         return 0;
953     }
954     if (opts_printdefs) {
955         for (i = 0; i < prog->defs_count; ++i) {
956             printf("Global: %8s %-16s at %u\n",
957                    type_name[prog->defs[i].type & DEF_TYPEMASK],
958                    prog_getstring(prog, prog->defs[i].name),
959                    (unsigned int)prog->defs[i].offset);
960         }
961     }
962     else if (opts_printfields) {
963         for (i = 0; i < prog->fields_count; ++i) {
964             printf("Field: %8s %-16s at %u\n",
965                    type_name[prog->fields[i].type],
966                    prog_getstring(prog, prog->fields[i].name),
967                    (unsigned int)prog->fields[i].offset);
968         }
969     }
970     else
971     {
972         if (fnmain > 0)
973         {
974             prog_main_setparams(prog);
975             prog_exec(prog, &prog->functions[fnmain], xflags, VM_JUMPS_DEFAULT);
976         }
977         else
978             printf("No main function found\n");
979     }
980
981     prog_delete(prog);
982     return 0;
983 }
984
985 void prog_disasm_function(qc_program *prog, size_t id)
986 {
987     prog_section_function *fdef = prog->functions + id;
988     prog_section_statement *st;
989
990     if (fdef->entry < 0) {
991         printf("FUNCTION \"%s\" = builtin #%i\n", prog_getstring(prog, fdef->name), (int)-fdef->entry);
992         return;
993     }
994     else
995         printf("FUNCTION \"%s\"\n", prog_getstring(prog, fdef->name));
996
997     st = prog->code + fdef->entry;
998     while (st->opcode != AINSTR_END) {
999         prog_print_statement(prog, st);
1000         ++st;
1001     }
1002 }
1003 #endif
1004 #else /* !QCVM_LOOP */
1005 /*
1006  * Everything from here on is not including into the compilation of the
1007  * executor.  This is simply code that is #included via #include __FILE__
1008  * see when QCVM_LOOP is defined, the rest of the code above do not get
1009  * re-included.  So this really just acts like one large macro, but it
1010  * sort of isn't, which makes it nicer looking.
1011  */
1012
1013 #define OPA ( (qcany*) (prog->globals + st->o1.u1) )
1014 #define OPB ( (qcany*) (prog->globals + st->o2.u1) )
1015 #define OPC ( (qcany*) (prog->globals + st->o3.u1) )
1016
1017 #define GLOBAL(x) ( (qcany*) (prog->globals + (x)) )
1018
1019 /* to be consistent with current darkplaces behaviour */
1020 #if !defined(FLOAT_IS_TRUE_FOR_INT)
1021 #   define FLOAT_IS_TRUE_FOR_INT(x) ( (x) & 0x7FFFFFFF )
1022 #endif
1023
1024 while (1) {
1025     prog_section_function  *newf;
1026     qcany          *ed;
1027     qcany          *ptr;
1028
1029     ++st;
1030
1031 #if QCVM_PROFILE
1032     prog->profile[st - prog->code]++;
1033 #endif
1034
1035 #if QCVM_TRACE
1036     prog_print_statement(prog, st);
1037 #endif
1038
1039     switch (st->opcode)
1040     {
1041         default:
1042             qcvmerror(prog, "Illegal instruction in %s\n", prog->filename);
1043             goto cleanup;
1044
1045         case INSTR_DONE:
1046         case INSTR_RETURN:
1047             /* TODO: add instruction count to function profile count */
1048             GLOBAL(OFS_RETURN)->ivector[0] = OPA->ivector[0];
1049             GLOBAL(OFS_RETURN)->ivector[1] = OPA->ivector[1];
1050             GLOBAL(OFS_RETURN)->ivector[2] = OPA->ivector[2];
1051
1052             st = prog->code + prog_leavefunction(prog);
1053             if (!prog->stack_count)
1054                 goto cleanup;
1055
1056             break;
1057
1058         case INSTR_MUL_F:
1059             OPC->_float = OPA->_float * OPB->_float;
1060             break;
1061         case INSTR_MUL_V:
1062             OPC->_float = OPA->vector[0]*OPB->vector[0] +
1063                           OPA->vector[1]*OPB->vector[1] +
1064                           OPA->vector[2]*OPB->vector[2];
1065             break;
1066         case INSTR_MUL_FV:
1067             OPC->vector[0] = OPA->_float * OPB->vector[0];
1068             OPC->vector[1] = OPA->_float * OPB->vector[1];
1069             OPC->vector[2] = OPA->_float * OPB->vector[2];
1070             break;
1071         case INSTR_MUL_VF:
1072             OPC->vector[0] = OPB->_float * OPA->vector[0];
1073             OPC->vector[1] = OPB->_float * OPA->vector[1];
1074             OPC->vector[2] = OPB->_float * OPA->vector[2];
1075             break;
1076         case INSTR_DIV_F:
1077             if (OPB->_float != 0.0f)
1078                 OPC->_float = OPA->_float / OPB->_float;
1079             else
1080                 OPC->_float = 0;
1081             break;
1082
1083         case INSTR_ADD_F:
1084             OPC->_float = OPA->_float + OPB->_float;
1085             break;
1086         case INSTR_ADD_V:
1087             OPC->vector[0] = OPA->vector[0] + OPB->vector[0];
1088             OPC->vector[1] = OPA->vector[1] + OPB->vector[1];
1089             OPC->vector[2] = OPA->vector[2] + OPB->vector[2];
1090             break;
1091         case INSTR_SUB_F:
1092             OPC->_float = OPA->_float - OPB->_float;
1093             break;
1094         case INSTR_SUB_V:
1095             OPC->vector[0] = OPA->vector[0] - OPB->vector[0];
1096             OPC->vector[1] = OPA->vector[1] - OPB->vector[1];
1097             OPC->vector[2] = OPA->vector[2] - OPB->vector[2];
1098             break;
1099
1100         case INSTR_EQ_F:
1101             OPC->_float = (OPA->_float == OPB->_float);
1102             break;
1103         case INSTR_EQ_V:
1104             OPC->_float = ((OPA->vector[0] == OPB->vector[0]) &&
1105                            (OPA->vector[1] == OPB->vector[1]) &&
1106                            (OPA->vector[2] == OPB->vector[2]) );
1107             break;
1108         case INSTR_EQ_S:
1109             OPC->_float = !strcmp(prog_getstring(prog, OPA->string),
1110                                   prog_getstring(prog, OPB->string));
1111             break;
1112         case INSTR_EQ_E:
1113             OPC->_float = (OPA->_int == OPB->_int);
1114             break;
1115         case INSTR_EQ_FNC:
1116             OPC->_float = (OPA->function == OPB->function);
1117             break;
1118         case INSTR_NE_F:
1119             OPC->_float = (OPA->_float != OPB->_float);
1120             break;
1121         case INSTR_NE_V:
1122             OPC->_float = ((OPA->vector[0] != OPB->vector[0]) ||
1123                            (OPA->vector[1] != OPB->vector[1]) ||
1124                            (OPA->vector[2] != OPB->vector[2]) );
1125             break;
1126         case INSTR_NE_S:
1127             OPC->_float = !!strcmp(prog_getstring(prog, OPA->string),
1128                                    prog_getstring(prog, OPB->string));
1129             break;
1130         case INSTR_NE_E:
1131             OPC->_float = (OPA->_int != OPB->_int);
1132             break;
1133         case INSTR_NE_FNC:
1134             OPC->_float = (OPA->function != OPB->function);
1135             break;
1136
1137         case INSTR_LE:
1138             OPC->_float = (OPA->_float <= OPB->_float);
1139             break;
1140         case INSTR_GE:
1141             OPC->_float = (OPA->_float >= OPB->_float);
1142             break;
1143         case INSTR_LT:
1144             OPC->_float = (OPA->_float < OPB->_float);
1145             break;
1146         case INSTR_GT:
1147             OPC->_float = (OPA->_float > OPB->_float);
1148             break;
1149
1150         case INSTR_LOAD_F:
1151         case INSTR_LOAD_S:
1152         case INSTR_LOAD_FLD:
1153         case INSTR_LOAD_ENT:
1154         case INSTR_LOAD_FNC:
1155             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1156                 qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename);
1157                 goto cleanup;
1158             }
1159             if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields)) {
1160                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1161                           prog->filename,
1162                           OPB->_int);
1163                 goto cleanup;
1164             }
1165             ed = prog_getedict(prog, OPA->edict);
1166             OPC->_int = ((qcany*)( ((qcint*)ed) + OPB->_int ))->_int;
1167             break;
1168         case INSTR_LOAD_V:
1169             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1170                 qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename);
1171                 goto cleanup;
1172             }
1173             if (OPB->_int < 0 || OPB->_int + 3 > prog->entityfields)
1174             {
1175                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1176                           prog->filename,
1177                           OPB->_int + 2);
1178                 goto cleanup;
1179             }
1180             ed = prog_getedict(prog, OPA->edict);
1181             OPC->ivector[0] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[0];
1182             OPC->ivector[1] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[1];
1183             OPC->ivector[2] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[2];
1184             break;
1185
1186         case INSTR_ADDRESS:
1187             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1188                 qcvmerror(prog, "prog `%s` attempted to address an out of bounds entity %i", prog->filename, OPA->edict);
1189                 goto cleanup;
1190             }
1191             if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields))
1192             {
1193                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1194                           prog->filename,
1195                           OPB->_int);
1196                 goto cleanup;
1197             }
1198
1199             ed = prog_getedict(prog, OPA->edict);
1200             OPC->_int = ((qcint*)ed) - prog->entitydata;
1201             OPC->_int += OPB->_int;
1202             break;
1203
1204         case INSTR_STORE_F:
1205         case INSTR_STORE_S:
1206         case INSTR_STORE_ENT:
1207         case INSTR_STORE_FLD:
1208         case INSTR_STORE_FNC:
1209             OPB->_int = OPA->_int;
1210             break;
1211         case INSTR_STORE_V:
1212             OPB->ivector[0] = OPA->ivector[0];
1213             OPB->ivector[1] = OPA->ivector[1];
1214             OPB->ivector[2] = OPA->ivector[2];
1215             break;
1216
1217         case INSTR_STOREP_F:
1218         case INSTR_STOREP_S:
1219         case INSTR_STOREP_ENT:
1220         case INSTR_STOREP_FLD:
1221         case INSTR_STOREP_FNC:
1222             if (OPB->_int < 0 || OPB->_int >= prog->entitydata_count) {
1223                 qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int);
1224                 goto cleanup;
1225             }
1226             if (OPB->_int < prog->entityfields && !prog->allowworldwrites)
1227                 qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n",
1228                           prog->filename,
1229                           prog_getstring(prog, prog_entfield(prog, OPB->_int)->name),
1230                           OPB->_int);
1231             ptr = (qcany*)(prog->entitydata + OPB->_int);
1232             ptr->_int = OPA->_int;
1233             break;
1234         case INSTR_STOREP_V:
1235             if (OPB->_int < 0 || OPB->_int + 2 >= prog->entitydata_count) {
1236                 qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int);
1237                 goto cleanup;
1238             }
1239             if (OPB->_int < prog->entityfields && !prog->allowworldwrites)
1240                 qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n",
1241                           prog->filename,
1242                           prog_getstring(prog, prog_entfield(prog, OPB->_int)->name),
1243                           OPB->_int);
1244             ptr = (qcany*)(prog->entitydata + OPB->_int);
1245             ptr->ivector[0] = OPA->ivector[0];
1246             ptr->ivector[1] = OPA->ivector[1];
1247             ptr->ivector[2] = OPA->ivector[2];
1248             break;
1249
1250         case INSTR_NOT_F:
1251             OPC->_float = !FLOAT_IS_TRUE_FOR_INT(OPA->_int);
1252             break;
1253         case INSTR_NOT_V:
1254             OPC->_float = !OPA->vector[0] &&
1255                           !OPA->vector[1] &&
1256                           !OPA->vector[2];
1257             break;
1258         case INSTR_NOT_S:
1259             OPC->_float = !OPA->string ||
1260                           !*prog_getstring(prog, OPA->string);
1261             break;
1262         case INSTR_NOT_ENT:
1263             OPC->_float = (OPA->edict == 0);
1264             break;
1265         case INSTR_NOT_FNC:
1266             OPC->_float = !OPA->function;
1267             break;
1268
1269         case INSTR_IF:
1270             /* this is consistent with darkplaces' behaviour */
1271             if(FLOAT_IS_TRUE_FOR_INT(OPA->_int))
1272             {
1273                 st += st->o2.s1 - 1;    /* offset the s++ */
1274                 if (++jumpcount >= maxjumps)
1275                     qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1276             }
1277             break;
1278         case INSTR_IFNOT:
1279             if(!FLOAT_IS_TRUE_FOR_INT(OPA->_int))
1280             {
1281                 st += st->o2.s1 - 1;    /* offset the s++ */
1282                 if (++jumpcount >= maxjumps)
1283                     qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1284             }
1285             break;
1286
1287         case INSTR_CALL0:
1288         case INSTR_CALL1:
1289         case INSTR_CALL2:
1290         case INSTR_CALL3:
1291         case INSTR_CALL4:
1292         case INSTR_CALL5:
1293         case INSTR_CALL6:
1294         case INSTR_CALL7:
1295         case INSTR_CALL8:
1296             prog->argc = st->opcode - INSTR_CALL0;
1297             if (!OPA->function)
1298                 qcvmerror(prog, "NULL function in `%s`", prog->filename);
1299
1300             if(!OPA->function || OPA->function >= (unsigned int)prog->functions_count)
1301             {
1302                 qcvmerror(prog, "CALL outside the program in `%s`", prog->filename);
1303                 goto cleanup;
1304             }
1305
1306             newf = &prog->functions[OPA->function];
1307             newf->profile++;
1308
1309             prog->statement = (st - prog->code) + 1;
1310
1311             if (newf->entry < 0)
1312             {
1313                 /* negative statements are built in functions */
1314                 int builtinnumber = -newf->entry;
1315                 if (builtinnumber < prog->builtins_count && prog->builtins[builtinnumber])
1316                     prog->builtins[builtinnumber](prog);
1317                 else
1318                     qcvmerror(prog, "No such builtin #%i in %s! Try updating your gmqcc sources",
1319                               builtinnumber, prog->filename);
1320             }
1321             else
1322                 st = prog->code + prog_enterfunction(prog, newf) - 1; /* offset st++ */
1323             if (prog->vmerror)
1324                 goto cleanup;
1325             break;
1326
1327         case INSTR_STATE:
1328             qcvmerror(prog, "`%s` tried to execute a STATE operation", prog->filename);
1329             break;
1330
1331         case INSTR_GOTO:
1332             st += st->o1.s1 - 1;    /* offset the s++ */
1333             if (++jumpcount == 10000000)
1334                 qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1335             break;
1336
1337         case INSTR_AND:
1338             OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) &&
1339                           FLOAT_IS_TRUE_FOR_INT(OPB->_int);
1340             break;
1341         case INSTR_OR:
1342             OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) ||
1343                           FLOAT_IS_TRUE_FOR_INT(OPB->_int);
1344             break;
1345
1346         case INSTR_BITAND:
1347             OPC->_float = ((int)OPA->_float) & ((int)OPB->_float);
1348             break;
1349         case INSTR_BITOR:
1350             OPC->_float = ((int)OPA->_float) | ((int)OPB->_float);
1351             break;
1352     }
1353 }
1354
1355 #undef QCVM_PROFILE
1356 #undef QCVM_TRACE
1357 #endif /* !QCVM_LOOP */