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