]> git.xonotic.org Git - xonotic/gmqcc.git/blob - exec.c
fixup qcvm parameter handling, now progs.dat can be specified anywhere not just at...
[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     /* 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         file_puts(stdout, 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         const char *str = prog_getstring(prog, func->name);
479         vec_push(prog->function_stack, str);
480     }
481
482 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
483     if (vec_size(prog->stack))
484     {
485         prog_section_function *cur;
486         cur = prog->stack[vec_size(prog->stack)-1].function;
487         if (cur)
488         {
489             qcint *globals = prog->globals + cur->firstlocal;
490             vec_append(prog->localstack, cur->locals, globals);
491         }
492     }
493 #else
494     {
495         qcint *globals = prog->globals + func->firstlocal;
496         vec_append(prog->localstack, func->locals, globals);
497     }
498 #endif
499
500     /* copy parameters */
501     parampos = func->firstlocal;
502     for (p = 0; p < func->nargs; ++p)
503     {
504         size_t s;
505         for (s = 0; s < func->argsize[p]; ++s) {
506             prog->globals[parampos] = prog->globals[OFS_PARM0 + 3*p + s];
507             ++parampos;
508         }
509     }
510
511     vec_push(prog->stack, st);
512
513     return func->entry;
514 }
515
516 static qcint prog_leavefunction(qc_program *prog)
517 {
518     prog_section_function *prev = NULL;
519     size_t oldsp;
520
521     qc_exec_stack st = vec_last(prog->stack);
522
523     if (prog->xflags & VMXF_TRACE) {
524         if (vec_size(prog->function_stack))
525             vec_pop(prog->function_stack);
526     }
527
528 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
529     if (vec_size(prog->stack) > 1) {
530         prev  = prog->stack[vec_size(prog->stack)-2].function;
531         oldsp = prog->stack[vec_size(prog->stack)-2].localsp;
532     }
533 #else
534     prev  = prog->stack[vec_size(prog->stack)-1].function;
535     oldsp = prog->stack[vec_size(prog->stack)-1].localsp;
536 #endif
537     if (prev) {
538         qcint *globals = prog->globals + prev->firstlocal;
539         memcpy(globals, prog->localstack + oldsp, prev->locals * sizeof(prog->localstack[0]));
540         /* vec_remove(prog->localstack, oldsp, vec_size(prog->localstack)-oldsp); */
541         vec_shrinkto(prog->localstack, oldsp);
542     }
543
544     vec_pop(prog->stack);
545
546     return st.stmt - 1; /* offset the ++st */
547 }
548
549 bool prog_exec(qc_program *prog, prog_section_function *func, size_t flags, long maxjumps)
550 {
551     long jumpcount = 0;
552     size_t oldxflags = prog->xflags;
553     prog_section_statement *st;
554
555     prog->vmerror = 0;
556     prog->xflags = flags;
557
558     st = prog->code + prog_enterfunction(prog, func);
559     --st;
560     switch (flags)
561     {
562         default:
563         case 0:
564         {
565 #define QCVM_LOOP    1
566 #define QCVM_PROFILE 0
567 #define QCVM_TRACE   0
568 #           include __FILE__
569         }
570         case (VMXF_TRACE):
571         {
572 #define QCVM_PROFILE 0
573 #define QCVM_TRACE   1
574 #           include __FILE__
575         }
576         case (VMXF_PROFILE):
577         {
578 #define QCVM_PROFILE 1
579 #define QCVM_TRACE   0
580 #           include __FILE__
581         }
582         case (VMXF_TRACE|VMXF_PROFILE):
583         {
584 #define QCVM_PROFILE 1
585 #define QCVM_TRACE   1
586 #           include __FILE__
587         }
588     };
589
590 cleanup:
591     prog->xflags = oldxflags;
592     vec_free(prog->localstack);
593     vec_free(prog->stack);
594     if (prog->vmerror)
595         return false;
596     return true;
597 }
598
599 /***********************************************************************
600  * main for when building the standalone executor
601  */
602
603 #if defined(QCVM_EXECUTOR)
604 #include <math.h>
605
606 opts_cmd_t opts;
607
608 const char *type_name[TYPE_COUNT] = {
609     "void",
610     "string",
611     "float",
612     "vector",
613     "entity",
614     "field",
615     "function",
616     "pointer",
617 #if 0
618     "integer",
619 #endif
620     "variant"
621 };
622
623 typedef struct {
624     int         vtype;
625     const char *value;
626 } qcvm_parameter;
627
628 qcvm_parameter *main_params = NULL;
629
630 #define CheckArgs(num) do {                                                    \
631     if (prog->argc != (num)) {                                                 \
632         prog->vmerror++;                                                       \
633         printf("ERROR: invalid number of arguments for %s: %i, expected %i\n", \
634         __FUNCTION__, prog->argc, (num));                                      \
635         return -1;                                                             \
636     }                                                                          \
637 } while (0)
638
639 #define GetGlobal(idx) ((qcany*)(prog->globals + (idx)))
640 #define GetArg(num) GetGlobal(OFS_PARM0 + 3*(num))
641 #define Return(any) *(GetGlobal(OFS_RETURN)) = (any)
642
643 static int qc_print(qc_program *prog)
644 {
645     size_t i;
646     const char *laststr = NULL;
647     for (i = 0; i < (size_t)prog->argc; ++i) {
648         qcany *str = (qcany*)(prog->globals + OFS_PARM0 + 3*i);
649         laststr = prog_getstring(prog, str->string);
650         printf("%s", laststr);
651     }
652     if (laststr && (prog->xflags & VMXF_TRACE)) {
653         size_t len = strlen(laststr);
654         if (!len || laststr[len-1] != '\n')
655             printf("\n");
656     }
657     return 0;
658 }
659
660 static int qc_error(qc_program *prog)
661 {
662     printf("*** VM raised an error:\n");
663     qc_print(prog);
664     prog->vmerror++;
665     return -1;
666 }
667
668 static int qc_ftos(qc_program *prog)
669 {
670     char buffer[512];
671     qcany *num;
672     qcany str;
673     CheckArgs(1);
674     num = GetArg(0);
675     snprintf(buffer, sizeof(buffer), "%g", num->_float);
676     str.string = prog_tempstring(prog, buffer);
677     Return(str);
678     return 0;
679 }
680
681 static int qc_stof(qc_program *prog)
682 {
683     qcany *str;
684     qcany num;
685     CheckArgs(1);
686     str = GetArg(0);
687     num._float = strtof(prog_getstring(prog, str->string), NULL);
688     Return(num);
689     return 0;
690 }
691
692 static int qc_vtos(qc_program *prog)
693 {
694     char buffer[512];
695     qcany *num;
696     qcany str;
697     CheckArgs(1);
698     num = GetArg(0);
699     snprintf(buffer, sizeof(buffer), "'%g %g %g'", num->vector[0], num->vector[1], num->vector[2]);
700     str.string = prog_tempstring(prog, buffer);
701     Return(str);
702     return 0;
703 }
704
705 static int qc_etos(qc_program *prog)
706 {
707     char buffer[512];
708     qcany *num;
709     qcany str;
710     CheckArgs(1);
711     num = GetArg(0);
712     snprintf(buffer, sizeof(buffer), "%i", num->_int);
713     str.string = prog_tempstring(prog, buffer);
714     Return(str);
715     return 0;
716 }
717
718 static int qc_spawn(qc_program *prog)
719 {
720     qcany ent;
721     CheckArgs(0);
722     ent.edict = prog_spawn_entity(prog);
723     Return(ent);
724     return (ent.edict ? 0 : -1);
725 }
726
727 static int qc_kill(qc_program *prog)
728 {
729     qcany *ent;
730     CheckArgs(1);
731     ent = GetArg(0);
732     prog_free_entity(prog, ent->edict);
733     return 0;
734 }
735
736 static int qc_vlen(qc_program *prog)
737 {
738     qcany *vec, len;
739     CheckArgs(1);
740     vec = GetArg(0);
741     len._float = sqrt(vec->vector[0] * vec->vector[0] +
742                       vec->vector[1] * vec->vector[1] +
743                       vec->vector[2] * vec->vector[2]);
744     Return(len);
745     return 0;
746 }
747
748 static int qc_strcat(qc_program *prog)
749 {
750     char  *buffer;
751     size_t len1,   len2;
752     char  *cstr1, *cstr2;
753     qcany *str1,  *str2;
754     qcany  out;
755
756     CheckArgs(2);
757     str1 = GetArg(0);
758     str2 = GetArg(1);
759     cstr1 = prog_getstring(prog, str1->string);
760     cstr2 = prog_getstring(prog, str2->string);
761     len1 = strlen(cstr1);
762     len2 = strlen(cstr2);
763     buffer = (char*)mem_a(len1 + len2 + 1);
764     memcpy(buffer, cstr1, len1);
765     memcpy(buffer+len1, cstr2, len2+1);
766     out.string = prog_tempstring(prog, buffer);
767     mem_d(buffer);
768     Return(out);
769     return 0;
770 }
771
772 static int qc_strcmp(qc_program *prog)
773 {
774     char  *cstr1, *cstr2;
775     qcany *str1,  *str2;
776     qcany out;
777
778     if (prog->argc != 2 && prog->argc != 3) {
779         printf("ERROR: invalid number of arguments for strcmp/strncmp: %i, expected 2 or 3\n",
780                prog->argc);
781         return -1;
782     }
783
784     str1 = GetArg(0);
785     str2 = GetArg(1);
786     cstr1 = prog_getstring(prog, str1->string);
787     cstr2 = prog_getstring(prog, str2->string);
788     if (prog->argc == 3)
789         out._float = strncmp(cstr1, cstr2, GetArg(2)->_float);
790     else
791         out._float = strcmp(cstr1, cstr2);
792     Return(out);
793     return 0;
794 }
795
796 static prog_builtin qc_builtins[] = {
797     NULL,
798     &qc_print,  /*   1   */
799     &qc_ftos,   /*   2   */
800     &qc_spawn,  /*   3   */
801     &qc_kill,   /*   4   */
802     &qc_vtos,   /*   5   */
803     &qc_error,  /*   6   */
804     &qc_vlen,   /*   7   */
805     &qc_etos,   /*   8   */
806     &qc_stof,   /*   9   */
807     &qc_strcat, /*   10  */
808     &qc_strcmp  /*   11  */
809 };
810 static size_t qc_builtins_count = sizeof(qc_builtins) / sizeof(qc_builtins[0]);
811
812 static const char *arg0 = NULL;
813
814 static void version() {
815     printf("GMQCC-QCVM %d.%d.%d Built %s %s\n",
816            GMQCC_VERSION_MAJOR,
817            GMQCC_VERSION_MINOR,
818            GMQCC_VERSION_PATCH,
819            __DATE__,
820            __TIME__
821     );
822 }
823
824 static void usage()
825 {
826     printf("usage: %s [options] [parameters] file\n", arg0);
827     printf("options:\n");
828     printf("  -h, --help         print this message\n"
829            "  -trace             trace the execution\n"
830            "  -profile           perform profiling during execution\n"
831            "  -info              print information from the prog's header\n"
832            "  -disasm            disassemble and exit\n"
833            "  -disasm-func func  disassemble and exit\n"
834            "  -printdefs         list the defs section\n"
835            "  -printfields       list the field section\n"
836            "  -printfuns         list functions information\n"
837            "  -v                 be verbose\n"
838            "  -vv                be even more verbose\n");
839     printf("parameters:\n");
840     printf("  -vector <V>   pass a vector parameter to main()\n"
841            "  -float  <f>   pass a float parameter to main()\n"
842            "  -string <s>   pass a string parameter to main() \n");
843 }
844
845 static void prog_main_setparams(qc_program *prog)
846 {
847     size_t i;
848     qcany *arg;
849
850     for (i = 0; i < vec_size(main_params); ++i) {
851         arg = GetGlobal(OFS_PARM0 + 3*i);
852         arg->vector[0] = 0;
853         arg->vector[1] = 0;
854         arg->vector[2] = 0;
855         switch (main_params[i].vtype) {
856             case TYPE_VECTOR:
857 #ifdef _MSC_VER
858                 (void)sscanf_s(main_params[i].value, " %f %f %f ",
859                                &arg->vector[0],
860                                &arg->vector[1],
861                                &arg->vector[2]);
862 #else
863                 (void)sscanf(main_params[i].value, " %f %f %f ",
864                              &arg->vector[0],
865                              &arg->vector[1],
866                              &arg->vector[2]);
867 #endif
868                 break;
869             case TYPE_FLOAT:
870                 arg->_float = atof(main_params[i].value);
871                 break;
872             case TYPE_STRING:
873                 arg->string = prog_tempstring(prog, main_params[i].value);
874                 break;
875             default:
876                 printf("error: unhandled parameter type: %i\n", main_params[i].vtype);
877                 break;
878         }
879     }
880 }
881
882 void prog_disasm_function(qc_program *prog, size_t id);
883 int main(int argc, char **argv)
884 {
885     size_t      i;
886     qcint       fnmain = -1;
887     qc_program *prog;
888     size_t      xflags = VMXF_DEFAULT;
889     bool        opts_printfields = false;
890     bool        opts_printdefs   = false;
891     bool        opts_printfuns   = false;
892     bool        opts_disasm      = false;
893     bool        opts_info        = false;
894     bool        noexec           = false;
895     const char *progsfile        = NULL;
896     const char **dis_list        = NULL;
897     int         opts_v           = 0;
898
899     arg0 = argv[0];
900
901     if (argc < 2) {
902         usage();
903         exit(1);
904     }
905
906     while (argc > 1) {
907         if (!strcmp(argv[1], "-h") ||
908             !strcmp(argv[1], "-help") ||
909             !strcmp(argv[1], "--help"))
910         {
911             usage();
912             exit(0);
913         }
914         else if (!strcmp(argv[1], "-v")) {
915             ++opts_v;
916             --argc;
917             ++argv;
918         }
919         else if (!strncmp(argv[1], "-vv", 3)) {
920             const char *av = argv[1]+1;
921             for (; *av; ++av) {
922                 if (*av == 'v')
923                     ++opts_v;
924                 else {
925                     usage();
926                     exit(1);
927                 }
928             }
929             --argc;
930             ++argv;
931         }
932         else if (!strcmp(argv[1], "-version") ||
933                  !strcmp(argv[1], "--version"))
934         {
935             version();
936             exit(0);
937         }
938         else if (!strcmp(argv[1], "-trace")) {
939             --argc;
940             ++argv;
941             xflags |= VMXF_TRACE;
942         }
943         else if (!strcmp(argv[1], "-profile")) {
944             --argc;
945             ++argv;
946             xflags |= VMXF_PROFILE;
947         }
948         else if (!strcmp(argv[1], "-info")) {
949             --argc;
950             ++argv;
951             opts_info = true;
952             noexec = true;
953         }
954         else if (!strcmp(argv[1], "-disasm")) {
955             --argc;
956             ++argv;
957             opts_disasm = true;
958             noexec = true;
959         }
960         else if (!strcmp(argv[1], "-disasm-func")) {
961             --argc;
962             ++argv;
963             if (argc <= 1) {
964                 usage();
965                 exit(1);
966             }
967             vec_push(dis_list, argv[1]);
968             --argc;
969             ++argv;
970             noexec = true;
971         }
972         else if (!strcmp(argv[1], "-printdefs")) {
973             --argc;
974             ++argv;
975             opts_printdefs = true;
976             noexec = true;
977         }
978         else if (!strcmp(argv[1], "-printfuns")) {
979             --argc;
980             ++argv;
981             opts_printfuns = true;
982             noexec = true;
983         }
984         else if (!strcmp(argv[1], "-printfields")) {
985             --argc;
986             ++argv;
987             opts_printfields = true;
988             noexec = true;
989         }
990         else if (!strcmp(argv[1], "-vector") ||
991                  !strcmp(argv[1], "-string") ||
992                  !strcmp(argv[1], "-float") )
993         {
994             qcvm_parameter p;
995             if (argv[1][1] == 'f')
996                 p.vtype = TYPE_FLOAT;
997             else if (argv[1][1] == 's')
998                 p.vtype = TYPE_STRING;
999             else if (argv[1][1] == 'v')
1000                 p.vtype = TYPE_VECTOR;
1001
1002             --argc;
1003             ++argv;
1004             if (argc < 2) {
1005                 usage();
1006                 exit(1);
1007             }
1008             p.value = argv[1];
1009
1010             vec_push(main_params, p);
1011             --argc;
1012             ++argv;
1013         }
1014         else if (!strcmp(argv[1], "--")) {
1015             --argc;
1016             ++argv;
1017             break;
1018         }
1019         else if (argv[1][0] != '-') {
1020             if (progsfile) {
1021                 printf("only 1 program file may be specified\n");
1022                 usage();
1023                 exit(1);
1024             }
1025             progsfile = argv[1];
1026             --argc;
1027             ++argv;
1028         }
1029         else
1030         {
1031             printf("unknown parameter: %s\n", argv[1]);
1032             usage();
1033             exit(1);
1034         }
1035     }
1036
1037     if (argc == 2 && !progsfile) {
1038         progsfile = argv[1];
1039         --argc;
1040         ++argv;
1041     }
1042
1043     if (!progsfile) {
1044         printf("must specify a program to execute\n");
1045         usage();
1046         exit(1);
1047     }
1048
1049     prog = prog_load(progsfile);
1050     if (!prog) {
1051         printf("failed to load program '%s'\n", progsfile);
1052         exit(1);
1053     }
1054
1055     prog->builtins       = qc_builtins;
1056     prog->builtins_count = qc_builtins_count;
1057
1058     if (opts_info) {
1059         printf("Program's system-checksum = 0x%04x\n", (unsigned int)prog->crc16);
1060         printf("Entity field space: %u\n", (unsigned int)prog->entityfields);
1061         printf("Globals: %u\n", (unsigned int)vec_size(prog->globals));
1062         printf("Counts:\n"
1063                "      code: %lu\n"
1064                "      defs: %lu\n"
1065                "    fields: %lu\n"
1066                " functions: %lu\n"
1067                "   strings: %lu\n",
1068                (unsigned long)vec_size(prog->code),
1069                (unsigned long)vec_size(prog->defs),
1070                (unsigned long)vec_size(prog->fields),
1071                (unsigned long)vec_size(prog->functions),
1072                (unsigned long)vec_size(prog->strings));
1073     }
1074
1075     if (opts_info) {
1076         prog_delete(prog);
1077         return 0;
1078     }
1079     for (i = 0; i < vec_size(dis_list); ++i) {
1080         size_t k;
1081         printf("Looking for `%s`\n", dis_list[i]);
1082         for (k = 1; k < vec_size(prog->functions); ++k) {
1083             const char *name = prog_getstring(prog, prog->functions[k].name);
1084             if (!strcmp(name, dis_list[i])) {
1085                 prog_disasm_function(prog, k);
1086                 break;
1087             }
1088         }
1089     }
1090     if (opts_disasm) {
1091         for (i = 1; i < vec_size(prog->functions); ++i)
1092             prog_disasm_function(prog, i);
1093         return 0;
1094     }
1095     if (opts_printdefs) {
1096         for (i = 0; i < vec_size(prog->defs); ++i) {
1097             printf("Global: %8s %-16s at %u%s\n",
1098                    type_name[prog->defs[i].type & DEF_TYPEMASK],
1099                    prog_getstring(prog, prog->defs[i].name),
1100                    (unsigned int)prog->defs[i].offset,
1101                    ((prog->defs[i].type & DEF_SAVEGLOBAL) ? " [SAVE]" : ""));
1102         }
1103     }
1104     if (opts_printfields) {
1105         for (i = 0; i < vec_size(prog->fields); ++i) {
1106             printf("Field: %8s %-16s at %u%s\n",
1107                    type_name[prog->fields[i].type],
1108                    prog_getstring(prog, prog->fields[i].name),
1109                    (unsigned int)prog->fields[i].offset,
1110                    ((prog->fields[i].type & DEF_SAVEGLOBAL) ? " [SAVE]" : ""));
1111         }
1112     }
1113     if (opts_printfuns) {
1114         for (i = 0; i < vec_size(prog->functions); ++i) {
1115             int32_t a;
1116             printf("Function: %-16s taking %i parameters:(",
1117                    prog_getstring(prog, prog->functions[i].name),
1118                    (unsigned int)prog->functions[i].nargs);
1119             for (a = 0; a < prog->functions[i].nargs; ++a) {
1120                 printf(" %i", prog->functions[i].argsize[a]);
1121             }
1122             if (opts_v > 1) {
1123                 int32_t start = prog->functions[i].entry;
1124                 if (start < 0)
1125                     printf(") builtin %i\n", (int)-start);
1126                 else {
1127                     size_t funsize = 0;
1128                     prog_section_statement *st = prog->code + start;
1129                     for (;st->opcode != INSTR_DONE; ++st)
1130                         ++funsize;
1131                     printf(") - %lu instructions", (unsigned long)funsize);
1132                     if (opts_v > 2) {
1133                         printf(" - locals: %i + %i\n",
1134                                prog->functions[i].firstlocal,
1135                                prog->functions[i].locals);
1136                     }
1137                     else
1138                         printf("\n");
1139                 }
1140             }
1141             else if (opts_v) {
1142                 printf(") locals: %i + %i\n",
1143                        prog->functions[i].firstlocal,
1144                        prog->functions[i].locals);
1145             }
1146             else
1147                 printf(")\n");
1148         }
1149     }
1150     if (!noexec) {
1151         for (i = 1; i < vec_size(prog->functions); ++i) {
1152             const char *name = prog_getstring(prog, prog->functions[i].name);
1153             if (!strcmp(name, "main"))
1154                 fnmain = (qcint)i;
1155         }
1156         if (fnmain > 0)
1157         {
1158             prog_main_setparams(prog);
1159             prog_exec(prog, &prog->functions[fnmain], xflags, VM_JUMPS_DEFAULT);
1160         }
1161         else
1162             printf("No main function found\n");
1163     }
1164
1165     prog_delete(prog);
1166     return 0;
1167 }
1168
1169 void prog_disasm_function(qc_program *prog, size_t id)
1170 {
1171     prog_section_function *fdef = prog->functions + id;
1172     prog_section_statement *st;
1173
1174     if (fdef->entry < 0) {
1175         printf("FUNCTION \"%s\" = builtin #%i\n", prog_getstring(prog, fdef->name), (int)-fdef->entry);
1176         return;
1177     }
1178     else
1179         printf("FUNCTION \"%s\"\n", prog_getstring(prog, fdef->name));
1180
1181     st = prog->code + fdef->entry;
1182     while (st->opcode != INSTR_DONE) {
1183         prog_print_statement(prog, st);
1184         ++st;
1185     }
1186 }
1187 #endif
1188 #else /* !QCVM_LOOP */
1189 /*
1190  * Everything from here on is not including into the compilation of the
1191  * executor.  This is simply code that is #included via #include __FILE__
1192  * see when QCVM_LOOP is defined, the rest of the code above do not get
1193  * re-included.  So this really just acts like one large macro, but it
1194  * sort of isn't, which makes it nicer looking.
1195  */
1196
1197 #define OPA ( (qcany*) (prog->globals + st->o1.u1) )
1198 #define OPB ( (qcany*) (prog->globals + st->o2.u1) )
1199 #define OPC ( (qcany*) (prog->globals + st->o3.u1) )
1200
1201 #define GLOBAL(x) ( (qcany*) (prog->globals + (x)) )
1202
1203 /* to be consistent with current darkplaces behaviour */
1204 #if !defined(FLOAT_IS_TRUE_FOR_INT)
1205 #   define FLOAT_IS_TRUE_FOR_INT(x) ( (x) & 0x7FFFFFFF )
1206 #endif
1207
1208 while (1) {
1209     prog_section_function  *newf;
1210     qcany          *ed;
1211     qcany          *ptr;
1212
1213     ++st;
1214
1215 #if QCVM_PROFILE
1216     prog->profile[st - prog->code]++;
1217 #endif
1218
1219 #if QCVM_TRACE
1220     prog_print_statement(prog, st);
1221 #endif
1222
1223     switch (st->opcode)
1224     {
1225         default:
1226             qcvmerror(prog, "Illegal instruction in %s\n", prog->filename);
1227             goto cleanup;
1228
1229         case INSTR_DONE:
1230         case INSTR_RETURN:
1231             /* TODO: add instruction count to function profile count */
1232             GLOBAL(OFS_RETURN)->ivector[0] = OPA->ivector[0];
1233             GLOBAL(OFS_RETURN)->ivector[1] = OPA->ivector[1];
1234             GLOBAL(OFS_RETURN)->ivector[2] = OPA->ivector[2];
1235
1236             st = prog->code + prog_leavefunction(prog);
1237             if (!vec_size(prog->stack))
1238                 goto cleanup;
1239
1240             break;
1241
1242         case INSTR_MUL_F:
1243             OPC->_float = OPA->_float * OPB->_float;
1244             break;
1245         case INSTR_MUL_V:
1246             OPC->_float = OPA->vector[0]*OPB->vector[0] +
1247                           OPA->vector[1]*OPB->vector[1] +
1248                           OPA->vector[2]*OPB->vector[2];
1249             break;
1250         case INSTR_MUL_FV:
1251             OPC->vector[0] = OPA->_float * OPB->vector[0];
1252             OPC->vector[1] = OPA->_float * OPB->vector[1];
1253             OPC->vector[2] = OPA->_float * OPB->vector[2];
1254             break;
1255         case INSTR_MUL_VF:
1256             OPC->vector[0] = OPB->_float * OPA->vector[0];
1257             OPC->vector[1] = OPB->_float * OPA->vector[1];
1258             OPC->vector[2] = OPB->_float * OPA->vector[2];
1259             break;
1260         case INSTR_DIV_F:
1261             if (OPB->_float != 0.0f)
1262                 OPC->_float = OPA->_float / OPB->_float;
1263             else
1264                 OPC->_float = 0;
1265             break;
1266
1267         case INSTR_ADD_F:
1268             OPC->_float = OPA->_float + OPB->_float;
1269             break;
1270         case INSTR_ADD_V:
1271             OPC->vector[0] = OPA->vector[0] + OPB->vector[0];
1272             OPC->vector[1] = OPA->vector[1] + OPB->vector[1];
1273             OPC->vector[2] = OPA->vector[2] + OPB->vector[2];
1274             break;
1275         case INSTR_SUB_F:
1276             OPC->_float = OPA->_float - OPB->_float;
1277             break;
1278         case INSTR_SUB_V:
1279             OPC->vector[0] = OPA->vector[0] - OPB->vector[0];
1280             OPC->vector[1] = OPA->vector[1] - OPB->vector[1];
1281             OPC->vector[2] = OPA->vector[2] - OPB->vector[2];
1282             break;
1283
1284         case INSTR_EQ_F:
1285             OPC->_float = (OPA->_float == OPB->_float);
1286             break;
1287         case INSTR_EQ_V:
1288             OPC->_float = ((OPA->vector[0] == OPB->vector[0]) &&
1289                            (OPA->vector[1] == OPB->vector[1]) &&
1290                            (OPA->vector[2] == OPB->vector[2]) );
1291             break;
1292         case INSTR_EQ_S:
1293             OPC->_float = !strcmp(prog_getstring(prog, OPA->string),
1294                                   prog_getstring(prog, OPB->string));
1295             break;
1296         case INSTR_EQ_E:
1297             OPC->_float = (OPA->_int == OPB->_int);
1298             break;
1299         case INSTR_EQ_FNC:
1300             OPC->_float = (OPA->function == OPB->function);
1301             break;
1302         case INSTR_NE_F:
1303             OPC->_float = (OPA->_float != OPB->_float);
1304             break;
1305         case INSTR_NE_V:
1306             OPC->_float = ((OPA->vector[0] != OPB->vector[0]) ||
1307                            (OPA->vector[1] != OPB->vector[1]) ||
1308                            (OPA->vector[2] != OPB->vector[2]) );
1309             break;
1310         case INSTR_NE_S:
1311             OPC->_float = !!strcmp(prog_getstring(prog, OPA->string),
1312                                    prog_getstring(prog, OPB->string));
1313             break;
1314         case INSTR_NE_E:
1315             OPC->_float = (OPA->_int != OPB->_int);
1316             break;
1317         case INSTR_NE_FNC:
1318             OPC->_float = (OPA->function != OPB->function);
1319             break;
1320
1321         case INSTR_LE:
1322             OPC->_float = (OPA->_float <= OPB->_float);
1323             break;
1324         case INSTR_GE:
1325             OPC->_float = (OPA->_float >= OPB->_float);
1326             break;
1327         case INSTR_LT:
1328             OPC->_float = (OPA->_float < OPB->_float);
1329             break;
1330         case INSTR_GT:
1331             OPC->_float = (OPA->_float > OPB->_float);
1332             break;
1333
1334         case INSTR_LOAD_F:
1335         case INSTR_LOAD_S:
1336         case INSTR_LOAD_FLD:
1337         case INSTR_LOAD_ENT:
1338         case INSTR_LOAD_FNC:
1339             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1340                 qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename);
1341                 goto cleanup;
1342             }
1343             if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields)) {
1344                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1345                           prog->filename,
1346                           OPB->_int);
1347                 goto cleanup;
1348             }
1349             ed = prog_getedict(prog, OPA->edict);
1350             OPC->_int = ((qcany*)( ((qcint*)ed) + OPB->_int ))->_int;
1351             break;
1352         case INSTR_LOAD_V:
1353             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1354                 qcvmerror(prog, "progs `%s` attempted to read an out of bounds entity", prog->filename);
1355                 goto cleanup;
1356             }
1357             if (OPB->_int < 0 || OPB->_int + 3 > (qcint)prog->entityfields)
1358             {
1359                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1360                           prog->filename,
1361                           OPB->_int + 2);
1362                 goto cleanup;
1363             }
1364             ed = prog_getedict(prog, OPA->edict);
1365             OPC->ivector[0] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[0];
1366             OPC->ivector[1] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[1];
1367             OPC->ivector[2] = ((qcany*)( ((qcint*)ed) + OPB->_int ))->ivector[2];
1368             break;
1369
1370         case INSTR_ADDRESS:
1371             if (OPA->edict < 0 || OPA->edict >= prog->entities) {
1372                 qcvmerror(prog, "prog `%s` attempted to address an out of bounds entity %i", prog->filename, OPA->edict);
1373                 goto cleanup;
1374             }
1375             if ((unsigned int)(OPB->_int) >= (unsigned int)(prog->entityfields))
1376             {
1377                 qcvmerror(prog, "prog `%s` attempted to read an invalid field from entity (%i)",
1378                           prog->filename,
1379                           OPB->_int);
1380                 goto cleanup;
1381             }
1382
1383             ed = prog_getedict(prog, OPA->edict);
1384             OPC->_int = ((qcint*)ed) - prog->entitydata + OPB->_int;
1385             break;
1386
1387         case INSTR_STORE_F:
1388         case INSTR_STORE_S:
1389         case INSTR_STORE_ENT:
1390         case INSTR_STORE_FLD:
1391         case INSTR_STORE_FNC:
1392             OPB->_int = OPA->_int;
1393             break;
1394         case INSTR_STORE_V:
1395             OPB->ivector[0] = OPA->ivector[0];
1396             OPB->ivector[1] = OPA->ivector[1];
1397             OPB->ivector[2] = OPA->ivector[2];
1398             break;
1399
1400         case INSTR_STOREP_F:
1401         case INSTR_STOREP_S:
1402         case INSTR_STOREP_ENT:
1403         case INSTR_STOREP_FLD:
1404         case INSTR_STOREP_FNC:
1405             if (OPB->_int < 0 || OPB->_int >= (qcint)vec_size(prog->entitydata)) {
1406                 qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int);
1407                 goto cleanup;
1408             }
1409             if (OPB->_int < (qcint)prog->entityfields && !prog->allowworldwrites)
1410                 qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n",
1411                           prog->filename,
1412                           prog_getstring(prog, prog_entfield(prog, OPB->_int)->name),
1413                           OPB->_int);
1414             ptr = (qcany*)(prog->entitydata + OPB->_int);
1415             ptr->_int = OPA->_int;
1416             break;
1417         case INSTR_STOREP_V:
1418             if (OPB->_int < 0 || OPB->_int + 2 >= (qcint)vec_size(prog->entitydata)) {
1419                 qcvmerror(prog, "`%s` attempted to write to an out of bounds edict (%i)", prog->filename, OPB->_int);
1420                 goto cleanup;
1421             }
1422             if (OPB->_int < (qcint)prog->entityfields && !prog->allowworldwrites)
1423                 qcvmerror(prog, "`%s` tried to assign to world.%s (field %i)\n",
1424                           prog->filename,
1425                           prog_getstring(prog, prog_entfield(prog, OPB->_int)->name),
1426                           OPB->_int);
1427             ptr = (qcany*)(prog->entitydata + OPB->_int);
1428             ptr->ivector[0] = OPA->ivector[0];
1429             ptr->ivector[1] = OPA->ivector[1];
1430             ptr->ivector[2] = OPA->ivector[2];
1431             break;
1432
1433         case INSTR_NOT_F:
1434             OPC->_float = !FLOAT_IS_TRUE_FOR_INT(OPA->_int);
1435             break;
1436         case INSTR_NOT_V:
1437             OPC->_float = !OPA->vector[0] &&
1438                           !OPA->vector[1] &&
1439                           !OPA->vector[2];
1440             break;
1441         case INSTR_NOT_S:
1442             OPC->_float = !OPA->string ||
1443                           !*prog_getstring(prog, OPA->string);
1444             break;
1445         case INSTR_NOT_ENT:
1446             OPC->_float = (OPA->edict == 0);
1447             break;
1448         case INSTR_NOT_FNC:
1449             OPC->_float = !OPA->function;
1450             break;
1451
1452         case INSTR_IF:
1453             /* this is consistent with darkplaces' behaviour */
1454             if(FLOAT_IS_TRUE_FOR_INT(OPA->_int))
1455             {
1456                 st += st->o2.s1 - 1;    /* offset the s++ */
1457                 if (++jumpcount >= maxjumps)
1458                     qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1459             }
1460             break;
1461         case INSTR_IFNOT:
1462             if(!FLOAT_IS_TRUE_FOR_INT(OPA->_int))
1463             {
1464                 st += st->o2.s1 - 1;    /* offset the s++ */
1465                 if (++jumpcount >= maxjumps)
1466                     qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1467             }
1468             break;
1469
1470         case INSTR_CALL0:
1471         case INSTR_CALL1:
1472         case INSTR_CALL2:
1473         case INSTR_CALL3:
1474         case INSTR_CALL4:
1475         case INSTR_CALL5:
1476         case INSTR_CALL6:
1477         case INSTR_CALL7:
1478         case INSTR_CALL8:
1479             prog->argc = st->opcode - INSTR_CALL0;
1480             if (!OPA->function)
1481                 qcvmerror(prog, "NULL function in `%s`", prog->filename);
1482
1483             if(!OPA->function || OPA->function >= (qcint)vec_size(prog->functions))
1484             {
1485                 qcvmerror(prog, "CALL outside the program in `%s`", prog->filename);
1486                 goto cleanup;
1487             }
1488
1489             newf = &prog->functions[OPA->function];
1490             newf->profile++;
1491
1492             prog->statement = (st - prog->code) + 1;
1493
1494             if (newf->entry < 0)
1495             {
1496                 /* negative statements are built in functions */
1497                 qcint builtinnumber = -newf->entry;
1498                 if (builtinnumber < (qcint)prog->builtins_count && prog->builtins[builtinnumber])
1499                     prog->builtins[builtinnumber](prog);
1500                 else
1501                     qcvmerror(prog, "No such builtin #%i in %s! Try updating your gmqcc sources",
1502                               builtinnumber, prog->filename);
1503             }
1504             else
1505                 st = prog->code + prog_enterfunction(prog, newf) - 1; /* offset st++ */
1506             if (prog->vmerror)
1507                 goto cleanup;
1508             break;
1509
1510         case INSTR_STATE:
1511             qcvmerror(prog, "`%s` tried to execute a STATE operation", prog->filename);
1512             break;
1513
1514         case INSTR_GOTO:
1515             st += st->o1.s1 - 1;    /* offset the s++ */
1516             if (++jumpcount == 10000000)
1517                 qcvmerror(prog, "`%s` hit the runaway loop counter limit of %li jumps", prog->filename, jumpcount);
1518             break;
1519
1520         case INSTR_AND:
1521             OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) &&
1522                           FLOAT_IS_TRUE_FOR_INT(OPB->_int);
1523             break;
1524         case INSTR_OR:
1525             OPC->_float = FLOAT_IS_TRUE_FOR_INT(OPA->_int) ||
1526                           FLOAT_IS_TRUE_FOR_INT(OPB->_int);
1527             break;
1528
1529         case INSTR_BITAND:
1530             OPC->_float = ((int)OPA->_float) & ((int)OPB->_float);
1531             break;
1532         case INSTR_BITOR:
1533             OPC->_float = ((int)OPA->_float) | ((int)OPB->_float);
1534             break;
1535     }
1536 }
1537
1538 #undef QCVM_PROFILE
1539 #undef QCVM_TRACE
1540 #endif /* !QCVM_LOOP */