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