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