Debian Codegraph @

code/qcommon/vm.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22 // vm.c -- virtual machine
23
24 /*
25
26
27 intermix code and data
28 symbol table
29
30 a dll has one imported function: VM_SystemCall
31 and one exported function: Perform
32
33
34 */
35
36 #include "vm_local.h"
37
38
39 vm_t *currentVM = NULL;
40 vm_t *lastVM = NULL;
41 int vm_debugLevel;
42
43 // used by Com_Error to get rid of running vm's before longjmp
44 static int forced_unload;
45
46 #define MAX_VM 3
47 vm_t vmTable[MAX_VM];
48
49
50 void VM_VmInfo_f( void );
51 void VM_VmProfile_f( void );
52
53
54
55 #if 0 // 64bit!
56 // converts a VM pointer to a C pointer and
57 // checks to make sure that the range is acceptable
58 void *VM_VM2C( vmptr_t p, int length ) {
59 return (void *)p;
60 }
61 #endif
62
63 void VM_Debug( int level ) {
64 vm_debugLevel = level;
65 }
66
67 /*
68 ==============
69 VM_Init
70 ==============
71 */
72 void VM_Init( void ) {
73 Cvar_Get( "vm_cgame", "2", CVAR_ARCHIVE ); // !@# SHIP WITH SET TO 2
74 Cvar_Get( "vm_game", "2", CVAR_ARCHIVE ); // !@# SHIP WITH SET TO 2
75 Cvar_Get( "vm_ui", "2", CVAR_ARCHIVE ); // !@# SHIP WITH SET TO 2
76
77 Cmd_AddCommand ("vmprofile", VM_VmProfile_f );
78 Cmd_AddCommand ("vminfo", VM_VmInfo_f );
79
80 Com_Memset( vmTable, 0, sizeof( vmTable ) );
81 }
82
83
84 /*
85 ===============
86 VM_ValueToSymbol
87
88 Assumes a program counter value
89 ===============
90 */
91 const char *VM_ValueToSymbol( vm_t *vm, int value ) {
92 vmSymbol_t *sym;
93 static char text[MAX_TOKEN_CHARS];
94
95 sym = vm->symbols;
96 if ( !sym ) {
97 return "NO SYMBOLS";
98 }
99
100 // find the symbol
101 while ( sym->next && sym->next->symValue <= value ) {
102 sym = sym->next;
103 }
104
105 if ( value == sym->symValue ) {
106 return sym->symName;
107 }
108
109 Com_sprintf( text, sizeof( text ), "%s+%i", sym->symName, value - sym->symValue );
110
111 return text;
112 }
113
114 /*
115 ===============
116 VM_ValueToFunctionSymbol
117
118 For profiling, find the symbol behind this value
119 ===============
120 */
121 vmSymbol_t *VM_ValueToFunctionSymbol( vm_t *vm, int value ) {
122 vmSymbol_t *sym;
123 static vmSymbol_t nullSym;
124
125 sym = vm->symbols;
126 if ( !sym ) {
127 return &nullSym;
128 }
129
130 while ( sym->next && sym->next->symValue <= value ) {
131 sym = sym->next;
132 }
133
134 return sym;
135 }
136
137
138 /*
139 ===============
140 VM_SymbolToValue
141 ===============
142 */
143 int VM_SymbolToValue( vm_t *vm, const char *symbol ) {
144 vmSymbol_t *sym;
145
146 for ( sym = vm->symbols ; sym ; sym = sym->next ) {
147 if ( !strcmp( symbol, sym->symName ) ) {
148 return sym->symValue;
149 }
150 }
151 return 0;
152 }
153
154
155 /*
156 =====================
157 VM_SymbolForCompiledPointer
158 =====================
159 */
160 #if 0 // 64bit!
161 const char *VM_SymbolForCompiledPointer( vm_t *vm, void *code ) {
162 int i;
163
164 if ( code < (void *)vm->codeBase ) {
165 return "Before code block";
166 }
167 if ( code >= (void *)(vm->codeBase + vm->codeLength) ) {
168 return "After code block";
169 }
170
171 // find which original instruction it is after
172 for ( i = 0 ; i < vm->codeLength ; i++ ) {
173 if ( (void *)vm->instructionPointers[i] > code ) {
174 break;
175 }
176 }
177 i--;
178
179 // now look up the bytecode instruction pointer
180 return VM_ValueToSymbol( vm, i );
181 }
182 #endif
183
184
185
186 /*
187 ===============
188 ParseHex
189 ===============
190 */
191 int ParseHex( const char *text ) {
192 int value;
193 int c;
194
195 value = 0;
196 while ( ( c = *text++ ) != 0 ) {
197 if ( c >= '0' && c <= '9' ) {
198 value = value * 16 + c - '0';
199 continue;
200 }
201 if ( c >= 'a' && c <= 'f' ) {
202 value = value * 16 + 10 + c - 'a';
203 continue;
204 }
205 if ( c >= 'A' && c <= 'F' ) {
206 value = value * 16 + 10 + c - 'A';
207 continue;
208 }
209 }
210
211 return value;
212 }
213
214 /*
215 ===============
216 VM_LoadSymbols
217 ===============
218 */
219 void VM_LoadSymbols( vm_t *vm ) {
220 union {
221 char *c;
222 void *v;
223 } mapfile;
224 char *text_p, *token;
225 char name[MAX_QPATH];
226 char symbols[MAX_QPATH];
227 vmSymbol_t **prev, *sym;
228 int count;
229 int value;
230 int chars;
231 int segment;
232 int numInstructions;
233
234 // don't load symbols if not developer
235 if ( !com_developer->integer ) {
236 return;
237 }
238
239 COM_StripExtension(vm->name, name, sizeof(name));
240 Com_sprintf( symbols, sizeof( symbols ), "vm/%s.map", name );
241 FS_ReadFile( symbols, &mapfile.v );
242 if ( !mapfile.c ) {
243 Com_Printf( "Couldn't load symbol file: %s\n", symbols );
244 return;
245 }
246
247 numInstructions = vm->instructionCount;
248
249 // parse the symbols
250 text_p = mapfile.c;
251 prev = &vm->symbols;
252 count = 0;
253
254 while ( 1 ) {
255 token = COM_Parse( &text_p );
256 if ( !token[0] ) {
257 break;
258 }
259 segment = ParseHex( token );
260 if ( segment ) {
261 COM_Parse( &text_p );
262 COM_Parse( &text_p );
263 continue; // only load code segment values
264 }
265
266 token = COM_Parse( &text_p );
267 if ( !token[0] ) {
268 Com_Printf( "WARNING: incomplete line at end of file\n" );
269 break;
270 }
271 value = ParseHex( token );
272
273 token = COM_Parse( &text_p );
274 if ( !token[0] ) {
275 Com_Printf( "WARNING: incomplete line at end of file\n" );
276 break;
277 }
278 chars = strlen( token );
279 sym = Hunk_Alloc( sizeof( *sym ) + chars, h_high );
280 *prev = sym;
281 prev = &sym->next;
282 sym->next = NULL;
283
284 // convert value from an instruction number to a code offset
285 if ( value >= 0 && value < numInstructions ) {
286 value = vm->instructionPointers[value];
287 }
288
289 sym->symValue = value;
290 Q_strncpyz( sym->symName, token, chars + 1 );
291
292 count++;
293 }
294
295 vm->numSymbols = count;
296 Com_Printf( "%i symbols parsed from %s\n", count, symbols );
297 FS_FreeFile( mapfile.v );
298 }
299
300 /*
301 ============
302 VM_DllSyscall
303
304 Dlls will call this directly
305
306 rcg010206 The horror; the horror.
307
308 The syscall mechanism relies on stack manipulation to get its args.
309 This is likely due to C's inability to pass "..." parameters to
310 a function in one clean chunk. On PowerPC Linux, these parameters
311 are not necessarily passed on the stack, so while (&arg[0] == arg)
312 is true, (&arg[1] == 2nd function parameter) is not necessarily
313 accurate, as arg's value might have been stored to the stack or
314 other piece of scratch memory to give it a valid address, but the
315 next parameter might still be sitting in a register.
316
317 Quake's syscall system also assumes that the stack grows downward,
318 and that any needed types can be squeezed, safely, into a signed int.
319
320 This hack below copies all needed values for an argument to a
321 array in memory, so that Quake can get the correct values. This can
322 also be used on systems where the stack grows upwards, as the
323 presumably standard and safe stdargs.h macros are used.
324
325 As for having enough space in a signed int for your datatypes, well,
326 it might be better to wait for DOOM 3 before you start porting. :)
327
328 The original code, while probably still inherently dangerous, seems
329 to work well enough for the platforms it already works on. Rather
330 than add the performance hit for those platforms, the original code
331 is still in use there.
332
333 For speed, we just grab 15 arguments, and don't worry about exactly
334 how many the syscall actually needs; the extra is thrown away.
335
336 ============
337 */
338 intptr_t QDECL VM_DllSyscall( intptr_t arg, ... ) {
339 #if !id386 || defined __clang__
340 // rcg010206 - see commentary above
341 intptr_t args[MAX_VMSYSCALL_ARGS];
342 int i;
343 va_list ap;
344
345 args[0] = arg;
346
347 va_start(ap, arg);
348 for (i = 1; i < ARRAY_LEN (args); i++)
349 args[i] = va_arg(ap, intptr_t);
350 va_end(ap);
351
352 return currentVM->systemCall( args );
353 #else // original id code
354 return currentVM->systemCall( &arg );
355 #endif
356 }
357
358
359 /*
360 =================
361 VM_LoadQVM
362
363 Load a .qvm file
364 =================
365 */
366 vmHeader_t *VM_LoadQVM( vm_t *vm, qboolean alloc, qboolean unpure)
367 {
368 int dataLength;
369 int i;
370 char filename[MAX_QPATH];
371 union {
372 vmHeader_t *h;
373 void *v;
•374 unsigned char *bytes;
375 } header;
376
377 // load the image
378 Com_sprintf( filename, sizeof(filename), "vm/%s.qvm", vm->name );
379 Com_Printf( "Loading vm file %s...\n", filename );
380
381 FS_ReadFileDir(filename, vm->searchPath, unpure, &header.v);
382
383 if ( !header.h ) {
384 Com_Printf( "Failed.\n" );
385 VM_Free( vm );
386
387 Com_Printf(S_COLOR_YELLOW "Warning: Couldn't open VM file %s\n", filename);
388
389 return NULL;
390 }
391
392 // show where the qvm was loaded from
393 FS_Which(filename, vm->searchPath);
394
•395 if (LittleLong( header.h->vmMagic ) == VM_MAGIC_USE_NATIVE) {
396 char module[MAX_OSPATH];
397 char filename[MAX_OSPATH];
398 int retval = -1;
399 void *startSearch = NULL;
400
401 Com_Printf("...which has vmMagic VM_MAGIC_USE_NATIVE.\n");
402
403 if (header.bytes[sizeof(int)] != '\0') {
404 // FS_ReadFileDir guarantees a trailing \0, even if
405 // there wasn't actually one in the file
406 Com_sprintf(module, sizeof(module), "%s/%s",
407 header.bytes + sizeof(int), vm->name);
408 Com_Printf("... trying %s\n", module);
409 startSearch = NULL;
410
411 if (FS_CheckDirTraversal(module)) {
412 Com_Printf("Directory traversal detected! %s\n", module);
413 VM_Free(vm);
414 return NULL;
415 }
416
417 retval = FS_FindVM(&startSearch, filename, sizeof(filename), module, qtrue, qtrue);
418 }
419
420 if (retval != VMI_NATIVE) {
421 Com_sprintf(module, sizeof(module), "%s", vm->name);
422 Com_Printf("... trying %s\n", module);
423 startSearch = NULL;
424
425 retval = FS_FindVM(&startSearch, filename, sizeof(filename), module, qtrue, qtrue);
426 }
427
428 if (retval != VMI_NATIVE) {
429 VM_Free(vm);
430 return NULL;
431 }
432
433 Com_Printf("Loading DLL file %s instead.\n", filename);
434 vm->dllHandle = Sys_LoadGameDll(filename, &vm->entryPoint, VM_DllSyscall);
435 if (!vm->dllHandle) {
436 Com_Printf("Failed to load DLL %s.\n", filename);
437 VM_Free(vm);
438 return NULL;
439 }
440 return header.h;
441 }
442
443 if( LittleLong( header.h->vmMagic ) == VM_MAGIC_VER2 ) {
444 Com_Printf( "...which has vmMagic VM_MAGIC_VER2\n" );
445
446 // byte swap the header
447 for ( i = 0 ; i < sizeof( vmHeader_t ) / 4 ; i++ ) {
448 ((int *)header.h)[i] = LittleLong( ((int *)header.h)[i] );
449 }
450
451 // validate
452 if ( header.h->jtrgLength < 0
453 || header.h->bssLength < 0
454 || header.h->dataLength < 0
455 || header.h->litLength < 0
456 || header.h->codeLength <= 0 )
457 {
458 VM_Free(vm);
459 FS_FreeFile(header.v);
460
461 Com_Printf(S_COLOR_YELLOW "Warning: %s has bad header\n", filename);
462 return NULL;
463 }
464 } else if( LittleLong( header.h->vmMagic ) == VM_MAGIC ) {
465 // byte swap the header
466 // sizeof( vmHeader_t ) - sizeof( int ) is the 1.32b vm header size
467 for ( i = 0 ; i < ( sizeof( vmHeader_t ) - sizeof( int ) ) / 4 ; i++ ) {
468 ((int *)header.h)[i] = LittleLong( ((int *)header.h)[i] );
469 }
470
471 // validate
472 if ( header.h->bssLength < 0
473 || header.h->dataLength < 0
474 || header.h->litLength < 0
475 || header.h->codeLength <= 0 )
476 {
477 VM_Free(vm);
478 FS_FreeFile(header.v);
479
480 Com_Printf(S_COLOR_YELLOW "Warning: %s has bad header\n", filename);
481 return NULL;
482 }
483 } else {
484 VM_Free( vm );
485 FS_FreeFile(header.v);
486
487 Com_Printf(S_COLOR_YELLOW "Warning: %s does not have a recognisable "
488 "magic number in its header\n", filename);
489 return NULL;
490 }
491
492 // round up to next power of 2 so all data operations can
493 // be mask protected
494 dataLength = header.h->dataLength + header.h->litLength +
495 header.h->bssLength;
496 for ( i = 0 ; dataLength > ( 1 << i ) ; i++ ) {
497 }
498 dataLength = 1 << i;
499
500 if(alloc)
501 {
502 // allocate zero filled space for initialized and uninitialized data
503 // leave some space beyond data mask so we can secure all mask operations
504 vm->dataAlloc = dataLength + 4;
505 vm->dataBase = Hunk_Alloc(vm->dataAlloc, h_high);
506 vm->dataMask = dataLength - 1;
507 }
508 else
509 {
510 // clear the data, but make sure we're not clearing more than allocated
511 if(vm->dataAlloc != dataLength + 4)
512 {
513 VM_Free(vm);
514 FS_FreeFile(header.v);
515
516 Com_Printf(S_COLOR_YELLOW "Warning: Data region size of %s not matching after "
517 "VM_Restart()\n", filename);
518 return NULL;
519 }
520
521 Com_Memset(vm->dataBase, 0, vm->dataAlloc);
522 }
523
524 // copy the intialized data
525 Com_Memcpy( vm->dataBase, (byte *)header.h + header.h->dataOffset,
526 header.h->dataLength + header.h->litLength );
527
528 // byte swap the longs
529 for ( i = 0 ; i < header.h->dataLength ; i += 4 ) {
530 *(int *)(vm->dataBase + i) = LittleLong( *(int *)(vm->dataBase + i ) );
531 }
532
533 if(header.h->vmMagic == VM_MAGIC_VER2)
534 {
535 int previousNumJumpTableTargets = vm->numJumpTableTargets;
536
537 header.h->jtrgLength &= ~0x03;
538
539 vm->numJumpTableTargets = header.h->jtrgLength >> 2;
540 Com_Printf("Loading %d jump table targets\n", vm->numJumpTableTargets);
541
542 if(alloc)
543 {
544 vm->jumpTableTargets = Hunk_Alloc(header.h->jtrgLength, h_high);
545 }
546 else
547 {
548 if(vm->numJumpTableTargets != previousNumJumpTableTargets)
549 {
550 VM_Free(vm);
551 FS_FreeFile(header.v);
552
553 Com_Printf(S_COLOR_YELLOW "Warning: Jump table size of %s not matching after "
554 "VM_Restart()\n", filename);
555 return NULL;
556 }
557
558 Com_Memset(vm->jumpTableTargets, 0, header.h->jtrgLength);
559 }
560
561 Com_Memcpy(vm->jumpTableTargets, (byte *) header.h + header.h->dataOffset +
562 header.h->dataLength + header.h->litLength, header.h->jtrgLength);
563
564 // byte swap the longs
565 for ( i = 0 ; i < header.h->jtrgLength ; i += 4 ) {
566 *(int *)(vm->jumpTableTargets + i) = LittleLong( *(int *)(vm->jumpTableTargets + i ) );
567 }
568 }
569
570 return header.h;
571 }
572
573 /*
574 =================
575 VM_Restart
576
577 Reload the data, but leave everything else in place
578 This allows a server to do a map_restart without changing memory allocation
579
580 We need to make sure that servers can access unpure QVMs (not contained in any pak)
581 even if the client is pure, so take "unpure" as argument.
582 =================
583 */
584 vm_t *VM_Restart(vm_t *vm, qboolean unpure)
585 {
586 vmHeader_t *header;
587
588 // DLL's can't be restarted in place
589 if ( vm->dllHandle ) {
590 char name[MAX_QPATH];
591 intptr_t (*systemCall)( intptr_t *parms );
592
593 systemCall = vm->systemCall;
594 Q_strncpyz( name, vm->name, sizeof( name ) );
595
596 VM_Free( vm );
597
598 vm = VM_Create( name, systemCall, VMI_NATIVE );
599 return vm;
600 }
601
602 // load the image
603 Com_Printf("VM_Restart()\n");
604
605 if(!(header = VM_LoadQVM(vm, qfalse, unpure)))
606 {
607 Com_Error(ERR_DROP, "VM_Restart failed");
608 return NULL;
609 }
610
611 // free the original file
612 FS_FreeFile(header);
613
614 return vm;
615 }
616
617 /*
618 ================
619 VM_Create
620
621 If image ends in .qvm it will be interpreted, otherwise
622 it will attempt to load as a system dll
623 ================
624 */
625 vm_t *VM_Create( const char *module, intptr_t (*systemCalls)(intptr_t *),
626 vmInterpret_t interpret ) {
627 vm_t *vm;
628 vmHeader_t *header = NULL;
629 int i, remaining, retval;
630 char filename[MAX_OSPATH];
631 void *startSearch = NULL;
632
633 if ( !module || !module[0] || !systemCalls ) {
634 Com_Error( ERR_FATAL, "VM_Create: bad parms" );
635 }
636
637 remaining = Hunk_MemoryRemaining();
638
639 // see if we already have the VM
640 for ( i = 0 ; i < MAX_VM ; i++ ) {
641 if (!Q_stricmp(vmTable[i].name, module)) {
642 vm = &vmTable[i];
643 return vm;
644 }
645 }
646
647 // find a free vm
648 for ( i = 0 ; i < MAX_VM ; i++ ) {
649 if ( !vmTable[i].name[0] ) {
650 break;
651 }
652 }
653
654 if ( i == MAX_VM ) {
655 Com_Error( ERR_FATAL, "VM_Create: no free vm_t" );
656 }
657
658 vm = &vmTable[i];
659
660 Q_strncpyz(vm->name, module, sizeof(vm->name));
661
662 do
663 {
•664 retval = FS_FindVM(&startSearch, filename, sizeof(filename), module, (interpret == VMI_NATIVE), qfalse);
665
666 if(retval == VMI_NATIVE)
667 {
668 Com_Printf("Try loading dll file %s\n", filename);
669
670 vm->dllHandle = Sys_LoadGameDll(filename, &vm->entryPoint, VM_DllSyscall);
671
672 if(vm->dllHandle)
673 {
674 vm->systemCall = systemCalls;
675 return vm;
676 }
677
678 Com_Printf("Failed loading dll, trying next\n");
679 }
680 else if(retval == VMI_COMPILED)
681 {
682 vm->searchPath = startSearch;
683 if((header = VM_LoadQVM(vm, qtrue, qfalse)))
684 break;
685
686 // VM_Free overwrites the name on failed load
687 Q_strncpyz(vm->name, module, sizeof(vm->name));
688 }
689 } while(retval >= 0);
690
691 if(retval < 0)
692 return NULL;
693
694 vm->systemCall = systemCalls;
695
•696 if ( vm->dllHandle ) {
697 // it was replaced by a DLL anyway
698 FS_FreeFile( header );
699 return vm;
700 }
701
702 // allocate space for the jump targets, which will be filled in by the compile/prep functions
703 vm->instructionCount = header->instructionCount;
704 vm->instructionPointers = Hunk_Alloc(vm->instructionCount * sizeof(*vm->instructionPointers), h_high);
705
706 // copy or compile the instructions
707 vm->codeLength = header->codeLength;
708
709 vm->compiled = qfalse;
710
711 #ifndef HAVE_VM_COMPILED
712 if(interpret >= VMI_COMPILED) {
713 Com_Printf("Architecture doesn't have a bytecode compiler, using interpreter\n");
714 interpret = VMI_BYTECODE;
715 }
716 #else
717 if(interpret != VMI_BYTECODE)
718 {
719 vm->compiled = qtrue;
720 VM_Compile( vm, header );
721 }
722 #endif
723 // VM_Compile may have reset vm->compiled if compilation failed
724 if (!vm->compiled)
725 {
726 VM_PrepareInterpreter( vm, header );
727 }
728
729 // free the original file
730 FS_FreeFile( header );
731
732 // load the map file
733 VM_LoadSymbols( vm );
734
735 // the stack is implicitly at the end of the image
736 vm->programStack = vm->dataMask + 1;
737 vm->stackBottom = vm->programStack - PROGRAM_STACK_SIZE;
738
739 Com_Printf("%s loaded in %d bytes on the hunk\n", module, remaining - Hunk_MemoryRemaining());
740
741 return vm;
742 }
743
744 /*
745 ==============
746 VM_Free
747 ==============
748 */
749 void VM_Free( vm_t *vm ) {
750
751 if(!vm) {
752 return;
753 }
754
755 if(vm->callLevel) {
756 if(!forced_unload) {
757 Com_Error( ERR_FATAL, "VM_Free(%s) on running vm", vm->name );
758 return;
759 } else {
760 Com_Printf( "forcefully unloading %s vm\n", vm->name );
761 }
762 }
763
764 if(vm->destroy)
765 vm->destroy(vm);
766
767 if ( vm->dllHandle ) {
768 Sys_UnloadDll( vm->dllHandle );
769 Com_Memset( vm, 0, sizeof( *vm ) );
770 }
771 #if 0 // now automatically freed by hunk
772 if ( vm->codeBase ) {
773 Z_Free( vm->codeBase );
774 }
775 if ( vm->dataBase ) {
776 Z_Free( vm->dataBase );
777 }
778 if ( vm->instructionPointers ) {
779 Z_Free( vm->instructionPointers );
780 }
781 #endif
782 Com_Memset( vm, 0, sizeof( *vm ) );
783
784 currentVM = NULL;
785 lastVM = NULL;
786 }
787
788 void VM_Clear(void) {
789 int i;
790 for (i=0;i<MAX_VM; i++) {
791 VM_Free(&vmTable[i]);
792 }
793 }
794
795 void VM_Forced_Unload_Start(void) {
796 forced_unload = 1;
797 }
798
799 void VM_Forced_Unload_Done(void) {
800 forced_unload = 0;
801 }
802
803 void *VM_ArgPtr( intptr_t intValue ) {
804 if ( !intValue ) {
805 return NULL;
806 }
807 // currentVM is missing on reconnect
808 if ( currentVM==NULL )
809 return NULL;
810
811 if ( currentVM->entryPoint ) {
812 return (void *)(currentVM->dataBase + intValue);
813 }
814 else {
815 return (void *)(currentVM->dataBase + (intValue & currentVM->dataMask));
816 }
817 }
818
819 void *VM_ExplicitArgPtr( vm_t *vm, intptr_t intValue ) {
820 if ( !intValue ) {
821 return NULL;
822 }
823
824 // currentVM is missing on reconnect here as well?
825 if ( currentVM==NULL )
826 return NULL;
827
828 //
829 if ( vm->entryPoint ) {
830 return (void *)(vm->dataBase + intValue);
831 }
832 else {
833 return (void *)(vm->dataBase + (intValue & vm->dataMask));
834 }
835 }
836
837
838 /*
839 ==============
840 VM_Call
841
842
843 Upon a system call, the stack will look like:
844
845 sp+32 parm1
846 sp+28 parm0
847 sp+24 return value
848 sp+20 return address
849 sp+16 local1
850 sp+14 local0
851 sp+12 arg1
852 sp+8 arg0
853 sp+4 return stack
854 sp return address
855
856 An interpreted function will immediately execute
857 an OP_ENTER instruction, which will subtract space for
858 locals from sp
859 ==============
860 */
861
862 intptr_t QDECL VM_Call( vm_t *vm, int callnum, ... )
863 {
864 vm_t *oldVM;
865 intptr_t r;
866 int i;
867
868 if(!vm || !vm->name[0])
869 Com_Error(ERR_FATAL, "VM_Call with NULL vm");
870
871 oldVM = currentVM;
872 currentVM = vm;
873 lastVM = vm;
874
875 if ( vm_debugLevel ) {
876 Com_Printf( "VM_Call( %d )\n", callnum );
877 }
878
879 ++vm->callLevel;
880 // if we have a dll loaded, call it directly
881 if ( vm->entryPoint ) {
882 //rcg010207 - see dissertation at top of VM_DllSyscall() in this file.
883 int args[MAX_VMMAIN_ARGS-1];
884 va_list ap;
885 va_start(ap, callnum);
886 for (i = 0; i < ARRAY_LEN(args); i++) {
887 args[i] = va_arg(ap, int);
888 }
889 va_end(ap);
890
891 r = vm->entryPoint( callnum, args[0], args[1], args[2], args[3],
892 args[4], args[5], args[6], args[7],
893 args[8], args[9], args[10], args[11]);
894 } else {
895 #if ( id386 || idsparc ) && !defined __clang__ // calling convention doesn't need conversion in some cases
896 #ifdef HAVE_VM_COMPILED
897 if ( vm->compiled )
898 r = VM_CallCompiled( vm, (int*)&callnum );
899 else
900 #endif
901 r = VM_CallInterpreted( vm, (int*)&callnum );
902 #else
903 struct {
904 int callnum;
905 int args[MAX_VMMAIN_ARGS-1];
906 } a;
907 va_list ap;
908
909 a.callnum = callnum;
910 va_start(ap, callnum);
911 for (i = 0; i < ARRAY_LEN(a.args); i++) {
912 a.args[i] = va_arg(ap, int);
913 }
914 va_end(ap);
915 #ifdef HAVE_VM_COMPILED
916 if ( vm->compiled )
917 r = VM_CallCompiled( vm, &a.callnum );
918 else
919 #endif
920 r = VM_CallInterpreted( vm, &a.callnum );
921 #endif
922 }
923 --vm->callLevel;
924
925 if ( oldVM != NULL )
926 currentVM = oldVM;
927 return r;
928 }
929
930 //=================================================================
931
932 static int QDECL VM_ProfileSort( const void *a, const void *b ) {
933 vmSymbol_t *sa, *sb;
934
935 sa = *(vmSymbol_t **)a;
936 sb = *(vmSymbol_t **)b;
937
938 if ( sa->profileCount < sb->profileCount ) {
939 return -1;
940 }
941 if ( sa->profileCount > sb->profileCount ) {
942 return 1;
943 }
944 return 0;
945 }
946
947 /*
948 ==============
949 VM_VmProfile_f
950
951 ==============
952 */
953 void VM_VmProfile_f( void ) {
954 vm_t *vm;
955 vmSymbol_t **sorted, *sym;
956 int i;
957 double total;
958
959 if ( !lastVM ) {
960 return;
961 }
962
963 vm = lastVM;
964
965 if ( !vm->numSymbols ) {
966 return;
967 }
968
969 sorted = Z_Malloc( vm->numSymbols * sizeof( *sorted ) );
970 sorted[0] = vm->symbols;
971 total = sorted[0]->profileCount;
972 for ( i = 1 ; i < vm->numSymbols ; i++ ) {
973 sorted[i] = sorted[i-1]->next;
974 total += sorted[i]->profileCount;
975 }
976
977 qsort( sorted, vm->numSymbols, sizeof( *sorted ), VM_ProfileSort );
978
979 for ( i = 0 ; i < vm->numSymbols ; i++ ) {
980 int perc;
981
982 sym = sorted[i];
983
984 perc = 100 * (float) sym->profileCount / total;
985 Com_Printf( "%2i%% %9i %s\n", perc, sym->profileCount, sym->symName );
986 sym->profileCount = 0;
987 }
988
989 Com_Printf(" %9.0f total\n", total );
990
991 Z_Free( sorted );
992 }
993
994 /*
995 ==============
996 VM_VmInfo_f
997
998 ==============
999 */
1000 void VM_VmInfo_f( void ) {
1001 vm_t *vm;
1002 int i;
1003
1004 Com_Printf( "Registered virtual machines:\n" );
1005 for ( i = 0 ; i < MAX_VM ; i++ ) {
1006 vm = &vmTable[i];
1007 if ( !vm->name[0] ) {
1008 break;
1009 }
1010 Com_Printf( "%s : ", vm->name );
1011 if ( vm->dllHandle ) {
1012 Com_Printf( "native\n" );
1013 continue;
1014 }
1015 if ( vm->compiled ) {
1016 Com_Printf( "compiled on load\n" );
1017 } else {
1018 Com_Printf( "interpreted\n" );
1019 }
1020 Com_Printf( " code length : %7i\n", vm->codeLength );
1021 Com_Printf( " table length: %7i\n", vm->instructionCount*4 );
1022 Com_Printf( " data length : %7i\n", vm->dataMask + 1 );
1023 }
1024 }
1025
1026 /*
1027 ===============
1028 VM_LogSyscalls
1029
1030 Insert calls to this while debugging the vm compiler
1031 ===============
1032 */
1033 void VM_LogSyscalls( int *args ) {
1034 static int callnum;
1035 static FILE *f;
1036
1037 if ( !f ) {
1038 f = fopen("syscalls.log", "w" );
1039 }
1040 callnum++;
1041 fprintf(f, "%i: %p (%i) = %i %i %i %i\n", callnum, (void*)(args - (int *)currentVM->dataBase),
1042 args[0], args[1], args[2], args[3], args[4] );
1043 }
1044
1045 /*
1046 =================
1047 VM_BlockCopy
1048 Executes a block copy operation within currentVM data space
1049 =================
1050 */
1051
1052 void VM_BlockCopy(unsigned int dest, unsigned int src, size_t n)
1053 {
1054 unsigned int dataMask = currentVM->dataMask;
1055
1056 if ((dest & dataMask) != dest
1057 || (src & dataMask) != src
1058 || ((dest + n) & dataMask) != dest + n
1059 || ((src + n) & dataMask) != src + n)
1060 {
1061 Com_Error(ERR_DROP, "OP_BLOCK_COPY out of range!");
1062 }
1063
1064 Com_Memcpy(currentVM->dataBase + dest, currentVM->dataBase + src, n);
1065 }