8 MEM_VEC_FUNCTIONS(qc_program, prog_section_statement, code)
9 MEM_VEC_FUNCTIONS(qc_program, prog_section_def, defs)
10 MEM_VEC_FUNCTIONS(qc_program, prog_section_def, fields)
11 MEM_VEC_FUNCTIONS(qc_program, prog_section_function, functions)
12 MEM_VEC_FUNCTIONS(qc_program, char, strings)
13 MEM_VEC_FUN_APPEND(qc_program, char, strings)
14 MEM_VEC_FUN_RESIZE(qc_program, char, strings)
15 MEM_VEC_FUNCTIONS(qc_program, qcint, globals)
16 MEM_VEC_FUNCTIONS(qc_program, qcint, entitydata)
17 MEM_VEC_FUNCTIONS(qc_program, bool, entitypool)
19 MEM_VEC_FUNCTIONS(qc_program, qcint, localstack)
20 MEM_VEC_FUN_APPEND(qc_program, qcint, localstack)
21 MEM_VEC_FUN_RESIZE(qc_program, qcint, localstack)
22 MEM_VEC_FUNCTIONS(qc_program, qc_exec_stack, stack)
24 MEM_VEC_FUNCTIONS(qc_program, size_t, profile)
25 MEM_VEC_FUN_RESIZE(qc_program, size_t, profile)
27 MEM_VEC_FUNCTIONS(qc_program, prog_builtin, builtins)
29 static void loaderror(const char *fmt, ...)
36 printf(": %s\n", strerror(err));
39 static void qcvmerror(qc_program *prog, const char *fmt, ...)
51 qc_program* prog_load(const char *filename)
58 file = util_fopen(filename, "rb");
62 if (fread(&header, sizeof(header), 1, file) != 1) {
63 loaderror("failed to read header from '%s'", filename);
68 if (header.version != 6) {
69 loaderror("header says this is a version %i progs, we need version 6\n", header.version);
74 prog = (qc_program*)mem_a(sizeof(qc_program));
77 printf("failed to allocate program data\n");
80 memset(prog, 0, sizeof(*prog));
82 prog->entityfields = header.entfield;
83 prog->crc16 = header.crc16;
85 prog->filename = util_strdup(filename);
86 if (!prog->filename) {
87 loaderror("failed to store program name");
91 #define read_data(hdrvar, progvar, type) \
92 if (fseek(file, header.hdrvar.offset, SEEK_SET) != 0) { \
93 loaderror("seek failed"); \
96 prog->progvar##_alloc = header.hdrvar.length; \
97 prog->progvar##_count = header.hdrvar.length; \
98 prog->progvar = (type*)mem_a(header.hdrvar.length * sizeof(*prog->progvar)); \
101 if (fread(prog->progvar, sizeof(*prog->progvar), header.hdrvar.length, file) \
102 != header.hdrvar.length) { \
103 loaderror("read failed"); \
106 #define read_data1(x, y) read_data(x, x, y)
108 read_data (statements, code, prog_section_statement);
109 read_data1(defs, prog_section_def);
110 read_data1(fields, prog_section_def);
111 read_data1(functions, prog_section_function);
112 read_data1(strings, char);
113 read_data1(globals, qcint);
117 /* profile counters */
118 if (!qc_program_profile_resize(prog, prog->code_count))
121 /* Add tempstring area */
122 prog->tempstring_start = prog->strings_count;
123 prog->tempstring_at = prog->strings_count;
124 if (!qc_program_strings_resize(prog, prog->strings_count + 16*1024))
127 /* spawn the world entity */
128 if (!qc_program_entitypool_add(prog, true)) {
129 loaderror("failed to allocate world entity\n");
132 for (i = 0; i < prog->entityfields; ++i) {
133 if (!qc_program_entitydata_add(prog, 0)) {
134 loaderror("failed to allocate world data\n");
143 if (prog->filename) mem_d(prog->filename);
144 if (prog->code) mem_d(prog->code);
145 if (prog->defs) mem_d(prog->defs);
146 if (prog->fields) mem_d(prog->fields);
147 if (prog->functions) mem_d(prog->functions);
148 if (prog->strings) mem_d(prog->strings);
149 if (prog->globals) mem_d(prog->globals);
150 if (prog->entitydata) mem_d(prog->entitydata);
151 if (prog->entitypool) mem_d(prog->entitypool);
156 void prog_delete(qc_program *prog)
158 if (prog->filename) mem_d(prog->filename);
159 MEM_VECTOR_CLEAR(prog, code);
160 MEM_VECTOR_CLEAR(prog, defs);
161 MEM_VECTOR_CLEAR(prog, fields);
162 MEM_VECTOR_CLEAR(prog, functions);
163 MEM_VECTOR_CLEAR(prog, strings);
164 MEM_VECTOR_CLEAR(prog, globals);
165 MEM_VECTOR_CLEAR(prog, entitydata);
166 MEM_VECTOR_CLEAR(prog, entitypool);
167 MEM_VECTOR_CLEAR(prog, localstack);
168 MEM_VECTOR_CLEAR(prog, stack);
169 MEM_VECTOR_CLEAR(prog, profile);
171 if (prog->builtins_alloc) {
172 MEM_VECTOR_CLEAR(prog, builtins);
174 /* otherwise the builtins were statically allocated */
178 /***********************************************************************
182 char* prog_getstring(qc_program *prog, qcint str)
184 if (str < 0 || str >= prog->strings_count)
185 return "<<<invalid string>>>";
186 return prog->strings + str;
189 prog_section_def* prog_entfield(qc_program *prog, qcint off)
192 for (i = 0; i < prog->fields_count; ++i) {
193 if (prog->fields[i].offset == off)
194 return (prog->fields + i);
199 prog_section_def* prog_getdef(qc_program *prog, qcint off)
202 for (i = 0; i < prog->defs_count; ++i) {
203 if (prog->defs[i].offset == off)
204 return (prog->defs + i);
209 qcany* prog_getedict(qc_program *prog, qcint e)
211 if (e >= prog->entitypool_count) {
213 printf("Accessing out of bounds edict %i\n", (int)e);
216 return (qcany*)(prog->entitydata + (prog->entityfields * e));
219 qcint prog_spawn_entity(qc_program *prog)
224 for (e = 0; e < (qcint)prog->entitypool_count; ++e) {
225 if (!prog->entitypool[e]) {
226 data = (char*)(prog->entitydata + (prog->entityfields * e));
227 memset(data, 0, prog->entityfields * sizeof(qcint));
231 if (!qc_program_entitypool_add(prog, true)) {
233 printf("Failed to allocate entity\n");
237 for (i = 0; i < prog->entityfields; ++i) {
238 if (!qc_program_entitydata_add(prog, 0)) {
239 printf("Failed to allocate entity\n");
243 data = (char*)(prog->entitydata + (prog->entityfields * e));
244 memset(data, 0, prog->entityfields * sizeof(qcint));
248 void prog_free_entity(qc_program *prog, qcint e)
252 printf("Trying to free world entity\n");
255 if (e >= prog->entitypool_count) {
257 printf("Trying to free out of bounds entity\n");
260 if (!prog->entitypool[e]) {
262 printf("Double free on entity\n");
265 prog->entitypool[e] = false;
268 qcint prog_tempstring(qc_program *prog, const char *_str)
270 /* we don't access it, but the macro-generated functions don't use
273 char *str = (char*)_str;
275 size_t len = strlen(str);
276 size_t at = prog->tempstring_at;
278 /* when we reach the end we start over */
279 if (at + len >= prog->strings_count)
280 at = prog->tempstring_start;
282 /* when it doesn't fit, reallocate */
283 if (at + len >= prog->strings_count)
285 prog->strings_count = at;
286 if (!qc_program_strings_append(prog, str, len+1)) {
287 prog->vmerror = VMERR_TEMPSTRING_ALLOC;
293 /* when it fits, just copy */
294 memcpy(prog->strings + at, str, len+1);
295 prog->tempstring_at += len+1;
299 static int print_escaped_string(const char *str, size_t maxlen)
303 --maxlen; /* because we're lazy and have escape sequences */
313 case '\a': len += 2; putchar('\\'); putchar('a'); break;
314 case '\b': len += 2; putchar('\\'); putchar('b'); break;
315 case '\r': len += 2; putchar('\\'); putchar('r'); break;
316 case '\n': len += 2; putchar('\\'); putchar('n'); break;
317 case '\t': len += 2; putchar('\\'); putchar('t'); break;
318 case '\f': len += 2; putchar('\\'); putchar('f'); break;
319 case '\v': len += 2; putchar('\\'); putchar('v'); break;
320 case '\\': len += 2; putchar('\\'); putchar('\\'); break;
321 case '"': len += 2; putchar('\\'); putchar('"'); break;
333 static void trace_print_global(qc_program *prog, unsigned int glob, int vtype)
335 static char spaces[28+1] = " ";
336 prog_section_def *def;
341 len = printf("<null>,");
345 def = prog_getdef(prog, glob);
346 value = (qcany*)(&prog->globals[glob]);
349 const char *name = prog_getstring(prog, def->name);
353 len = printf("%s ", name);
357 len = printf("[@%u] ", glob);
365 len += printf("(%i),", value->_int);
368 len += printf("'%g %g %g',", value->vector[0],
373 len += print_escaped_string(prog_getstring(prog, value->string), sizeof(spaces)-len-5);
375 /* len += printf("\"%s\",", prog_getstring(prog, value->string)); */
379 len += printf("%g,", value->_float);
383 if (len < sizeof(spaces)-1) {
384 spaces[sizeof(spaces)-1-len] = 0;
386 spaces[sizeof(spaces)-1-len] = ' ';
390 static void prog_print_statement(qc_program *prog, prog_section_statement *st)
392 if (st->opcode >= (sizeof(asm_instr)/sizeof(asm_instr[0]))) {
393 printf("<illegal instruction %d>\n", st->opcode);
396 printf(" <> %-12s", asm_instr[st->opcode].m);
397 if (st->opcode >= INSTR_IF &&
398 st->opcode <= INSTR_IFNOT)
400 trace_print_global(prog, st->o1.u1, TYPE_FLOAT);
401 printf("%d\n", st->o2.s1);
403 else if (st->opcode >= INSTR_CALL0 &&
404 st->opcode <= INSTR_CALL8)
408 else if (st->opcode == INSTR_GOTO)
410 printf("%i\n", st->o1.s1);
414 int t[3] = { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT };
418 t[1] = t[2] = TYPE_VECTOR;
421 t[0] = t[2] = TYPE_VECTOR;
424 t[0] = t[1] = TYPE_VECTOR;
430 t[0] = t[1] = t[2] = TYPE_VECTOR;
434 t[0] = t[1] = TYPE_STRING;
441 t[0] = t[1] = TYPE_VECTOR; t[2] = -1;
444 t[0] = t[1] = TYPE_STRING; t[2] = -1;
446 case INSTR_STORE_ENT:
447 t[0] = t[1] = TYPE_ENTITY; t[2] = -1;
449 case INSTR_STORE_FLD:
450 t[0] = t[1] = TYPE_FIELD; t[2] = -1;
452 case INSTR_STORE_FNC:
453 t[0] = t[1] = TYPE_FUNCTION; t[2] = -1;
456 t[0] = TYPE_VECTOR; t[1] = TYPE_ENTITY; t[2] = -1;
459 t[0] = TYPE_STRING; t[1] = TYPE_ENTITY; t[2] = -1;
461 case INSTR_STOREP_ENT:
462 t[0] = TYPE_ENTITY; t[1] = TYPE_ENTITY; t[2] = -1;
464 case INSTR_STOREP_FLD:
465 t[0] = TYPE_FIELD; t[1] = TYPE_ENTITY; t[2] = -1;
467 case INSTR_STOREP_FNC:
468 t[0] = TYPE_FUNCTION; t[1] = TYPE_ENTITY; t[2] = -1;
471 if (t[0] >= 0) trace_print_global(prog, st->o1.u1, t[0]);
472 else printf("(none), ");
473 if (t[1] >= 0) trace_print_global(prog, st->o2.u1, t[1]);
474 else printf("(none), ");
475 if (t[2] >= 0) trace_print_global(prog, st->o3.u1, t[2]);
476 else printf("(none)");
482 static qcint prog_enterfunction(qc_program *prog, prog_section_function *func)
488 st.localsp = prog->localstack_count;
489 st.stmt = prog->statement;
492 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
493 if (prog->stack_count)
495 prog_section_function *cur;
496 cur = prog->stack[prog->stack_count-1].function;
499 qcint *globals = prog->globals + cur->firstlocal;
500 if (!qc_program_localstack_append(prog, globals, cur->locals))
502 printf("out of memory\n");
509 qcint *globals = prog->globals + func->firstlocal;
510 if (!qc_program_localstack_append(prog, globals, func->locals))
512 printf("out of memory\n");
518 /* copy parameters */
519 parampos = func->firstlocal;
520 for (p = 0; p < func->nargs; ++p)
523 for (s = 0; s < func->argsize[p]; ++s) {
524 prog->globals[parampos] = prog->globals[OFS_PARM0 + 3*p + s];
529 if (!qc_program_stack_add(prog, st)) {
530 printf("out of memory\n");
537 static qcint prog_leavefunction(qc_program *prog)
539 prog_section_function *prev = NULL;
542 qc_exec_stack st = prog->stack[prog->stack_count-1];
544 #ifdef QCVM_BACKUP_STRATEGY_CALLER_VARS
545 if (prog->stack_count > 1) {
546 prev = prog->stack[prog->stack_count-2].function;
547 oldsp = prog->stack[prog->stack_count-2].localsp;
550 prev = prog->stack[prog->stack_count-1].function;
551 oldsp = prog->stack[prog->stack_count-1].localsp;
554 qcint *globals = prog->globals + prev->firstlocal;
555 memcpy(globals, prog->localstack + oldsp, prev->locals);
556 if (!qc_program_localstack_resize(prog, oldsp)) {
557 printf("out of memory\n");
562 if (!qc_program_stack_remove(prog, prog->stack_count-1)) {
563 printf("out of memory\n");
567 return st.stmt - 1; /* offset the ++st */
570 bool prog_exec(qc_program *prog, prog_section_function *func, size_t flags, long maxjumps)
573 size_t oldxflags = prog->xflags;
574 prog_section_statement *st;
577 prog->xflags = flags;
579 st = prog->code + prog_enterfunction(prog, func);
586 #define QCVM_PROFILE 0
588 # include "execloop.h"
593 #define QCVM_PROFILE 0
595 # include "execloop.h"
600 #define QCVM_PROFILE 1
602 # include "execloop.h"
605 case (VMXF_TRACE|VMXF_PROFILE):
607 #define QCVM_PROFILE 1
609 # include "execloop.h"
615 prog->xflags = oldxflags;
616 prog->localstack_count = 0;
617 prog->stack_count = 0;
623 /***********************************************************************
624 * main for when building the standalone executor
627 #if defined(QCVM_EXECUTOR)
630 const char *type_name[TYPE_COUNT] = {
645 bool opts_debug = false;
646 bool opts_memchk = false;
653 VECTOR_MAKE(qcvm_parameter, main_params);
655 #define CheckArgs(num) do { \
656 if (prog->argc != (num)) { \
658 printf("ERROR: invalid number of arguments for %s: %i, expected %i\n", \
659 __FUNCTION__, prog->argc, (num)); \
664 #define GetGlobal(idx) ((qcany*)(prog->globals + (idx)))
665 #define GetArg(num) GetGlobal(OFS_PARM0 + 3*(num))
666 #define Return(any) *(GetGlobal(OFS_RETURN)) = (any)
668 static int qc_print(qc_program *prog)
671 const char *laststr = NULL;
672 for (i = 0; i < prog->argc; ++i) {
673 qcany *str = (qcany*)(prog->globals + OFS_PARM0 + 3*i);
674 printf("%s", (laststr = prog_getstring(prog, str->string)));
676 if (laststr && (prog->xflags & VMXF_TRACE)) {
677 size_t len = strlen(laststr);
678 if (!len || laststr[len-1] != '\n')
684 static int qc_error(qc_program *prog)
686 printf("*** VM raised an error:\n");
692 static int qc_ftos(qc_program *prog)
699 snprintf(buffer, sizeof(buffer), "%g", num->_float);
700 str.string = prog_tempstring(prog, buffer);
705 static int qc_vtos(qc_program *prog)
712 snprintf(buffer, sizeof(buffer), "'%g %g %g'", num->vector[0], num->vector[1], num->vector[2]);
713 str.string = prog_tempstring(prog, buffer);
718 static int qc_etos(qc_program *prog)
725 snprintf(buffer, sizeof(buffer), "%i", num->_int);
726 str.string = prog_tempstring(prog, buffer);
731 static int qc_spawn(qc_program *prog)
735 ent.edict = prog_spawn_entity(prog);
737 return (ent.edict ? 0 : -1);
740 static int qc_kill(qc_program *prog)
745 prog_free_entity(prog, ent->edict);
749 static int qc_vlen(qc_program *prog)
754 len._float = sqrt(vec->vector[0] * vec->vector[0] +
755 vec->vector[1] * vec->vector[1] +
756 vec->vector[2] * vec->vector[2]);
761 static prog_builtin qc_builtins[] = {
772 static size_t qc_builtins_count = sizeof(qc_builtins) / sizeof(qc_builtins[0]);
774 static const char *arg0 = NULL;
778 printf("usage: [-debug] %s file\n", arg0);
782 static void prog_main_setparams(qc_program *prog)
787 for (i = 0; i < main_params_elements; ++i) {
788 arg = GetGlobal(OFS_PARM0 + 3*i);
792 switch (main_params_data[i].vtype) {
795 (void)sscanf_s(main_params_data[i].value, " %f %f %f ",
800 (void)sscanf(main_params_data[i].value, " %f %f %f ",
807 arg->_float = atof(main_params_data[i].value);
810 arg->string = prog_tempstring(prog, main_params_data[i].value);
813 printf("error: unhandled parameter type: %i\n", main_params_data[i].vtype);
819 int main(int argc, char **argv)
824 size_t xflags = VMXF_DEFAULT;
825 bool opts_printfields = false;
826 bool opts_printdefs = false;
827 bool opts_info = false;
835 if (!strcmp(argv[1], "-trace")) {
838 xflags |= VMXF_TRACE;
840 else if (!strcmp(argv[1], "-profile")) {
843 xflags |= VMXF_PROFILE;
845 else if (!strcmp(argv[1], "-info")) {
850 else if (!strcmp(argv[1], "-printdefs")) {
853 opts_printdefs = true;
855 else if (!strcmp(argv[1], "-printfields")) {
858 opts_printfields = true;
860 else if (!strcmp(argv[1], "-vector") ||
861 !strcmp(argv[1], "-string") ||
862 !strcmp(argv[1], "-float") )
865 if (argv[1][1] == 'f')
866 p.vtype = TYPE_FLOAT;
867 else if (argv[1][1] == 's')
868 p.vtype = TYPE_STRING;
869 else if (argv[1][1] == 'v')
870 p.vtype = TYPE_VECTOR;
878 if (main_params_add(p) < 0) {
879 if (main_params_data)
880 mem_d(main_params_data);
881 printf("cannot add parameter\n");
892 prog = prog_load(argv[1]);
894 printf("failed to load program '%s'\n", argv[1]);
898 prog->builtins = qc_builtins;
899 prog->builtins_count = qc_builtins_count;
900 prog->builtins_alloc = 0;
903 printf("Program's system-checksum = 0x%04x\n", (int)prog->crc16);
904 printf("Entity field space: %i\n", (int)prog->entityfields);
907 for (i = 1; i < prog->functions_count; ++i) {
908 const char *name = prog_getstring(prog, prog->functions[i].name);
909 /* printf("Found function: %s\n", name); */
910 if (!strcmp(name, "main"))
917 if (opts_printdefs) {
918 for (i = 0; i < prog->defs_count; ++i) {
919 printf("Global: %8s %-16s at %u\n",
920 type_name[prog->defs[i].type & DEF_TYPEMASK],
921 prog_getstring(prog, prog->defs[i].name),
922 (unsigned int)prog->defs[i].offset);
925 else if (opts_printfields) {
926 for (i = 0; i < prog->fields_count; ++i) {
927 printf("Field: %8s %-16s at %u\n",
928 type_name[prog->fields[i].type],
929 prog_getstring(prog, prog->fields[i].name),
930 (unsigned int)prog->fields[i].offset);
937 prog_main_setparams(prog);
938 prog_exec(prog, &prog->functions[fnmain], xflags, VM_JUMPS_DEFAULT);
941 printf("No main function found\n");