-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathQvm.py
2532 lines (2191 loc) · 110 KB
/
Qvm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
####
# Copyright (C) 2012, 2020 Angelo Cano
#
# This file is part of Qvmdis.
#
# Qvmdis is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Qvmdis is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Qvmdis. If not, see <https://www.gnu.org/licenses/>.
####
import os.path, re, struct, sys
from DecompileStack import DecompileStack
from LEBinFile import LEBinFile
from PythonCompat import atoi, xord, xchr
# python hash() builtin gives different values for 32-bit and 64-bit implementations
# http://effbot.org/zone/python-hash.htm
def c_mul(a, b):
#v = eval(hex((long(a) * b) & 0xFFFFFFFFL)[:-1])
# 32-bit signed
v = a * b
v = v & 0xffffffff
if v > 0x7fffffff:
v = -(0x100000000 - v)
return v
def hash32BitSigned (str):
if not str:
return 0 # empty
value = ord(str[0]) << 7
for char in str:
value = c_mul(1000003, value) ^ ord(char)
value = value ^ len(str)
if value == -1:
value = -2
return value
# detect hex or base 10, also explicitly require 0[xX] hex notation to make
# it easier to check if something is a number or a symbol. Ex: c.isdigit()
def parse_int (s):
# skip '+' and '-'
if len(s) > 0 and (s[0] == '+' or s[0] == '-'):
st = s[1:]
else:
st = s
if len(st) > 2 and st[0] == '0' and (st[1] == 'x' or st[1] == 'X'):
return atoi(s, 16)
else:
return atoi(s, 10)
def valid_symbol_name (s):
if s == None or len(s) == 0:
return False
c = s[0]
if c.isdigit() or c == '+' or c == '-':
return False
if s == "void" or s in basicTypes:
return False
return True
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
CGAME_SYSCALLS_ASM_FILE = "cg_syscalls.asm"
GAME_SYSCALLS_ASM_FILE = "g_syscalls.asm"
UI_SYSCALLS_ASM_FILE = "ui_syscalls.asm"
BASEQ3_CGAME_FUNCTIONS_FILE = "baseq3-cgame-functions.hmap"
BASEQ3_GAME_FUNCTIONS_FILE = "baseq3-game-functions.hmap"
BASEQ3_UI_FUNCTIONS_FILE = "baseq3-ui-functions.hmap"
SYMBOLS_FILE = "symbols.dat"
FUNCTIONS_FILE = "functions.dat"
CONSTANTS_FILE = "constants.dat"
COMMENTS_FILE = "comments.dat"
TEMPLATES_DEFAULT_FILE = "templates-default.dat"
TEMPLATES_FILE = "templates.dat"
QVM_MAGIC_VER1 = 0x12721444
QVM_MAGIC_VER2 = 0x12721445
def output (msg):
sys.stdout.write(msg)
class OutputBuffer:
def __init__ (self):
self.clear()
def write (self, s):
self.stringList.append(s)
def flush (self):
output("".join(self.stringList))
self.clear()
def clear (self):
self.stringList = []
SuppressWarnings = False
def warning_msg (msg):
global SuppressWarnings
if SuppressWarnings:
return
# send to both stdout and stderr since output is usually redirected to file
sys.stdout.write("; warning : %s\n" % msg)
sys.stderr.write("warning: %s\n" % msg)
def error_msg (msg):
# send to both stdout and stderr since output is usually redirected to file
sys.stdout.write("---- error occurred : %s\n" % msg)
sys.stderr.write("ERROR: %s\n" % msg)
def error_exit (msg, exitValue = 1):
error_msg(msg)
sys.exit(exitValue)
OPCODE_NAME = 0
OPCODE_PARM_SIZE = 1
OPCODE_JUMP_PARM = 2
OPCODE_STACK_CHANGE = 3
OPCODE_DESC = 4 # from q3vm_specs.html and ioquake3 source code (2020-01-30)
OPCODE_C_CODE = 5 # 2020-02-16 q3 code/qcommon/vm_interpreted.c: r2 = $PARM, r1 = NIS, r0 = TOS
opcodes = [ \
["undef", 0, False, 0, "undefined opcode.", ""],
["ignore", 0, False, 0, "no-operation (nop) instruction.", ""],
["break", 0, False, 0, "set debugging break point.", ""],
["enter", 4, False, 0, "Begin procedure body, adjust stack $PARM octets for frame (always at least 8 (i.e. 2 words)). Frame contains all local storage/variables and arguments space for any calls within this procedure.", ""], # establishes current stack so 0 relative change
["leave", 4, False, 0, "End procedure body, $PARM is same as that of the matching ENTER.", ""],
["call", 0, False, -1, "make call to procedure (code address <- TOS).", ""], # call address is removed, but by convention the called function leaves a value on the stack
["push", 0, False, 1, "push nonsense (void) value to opstack (TOS <- 0).", ""],
["pop", 0, False, -1, "pop a value from stack (remove TOS, decrease stack by 1).", ""],
["const", 4, False, 1, "push literal value onto stack (TOS <- $PARM)", "r1 = r0;\nr0 = opStack[opStackOfs] = r2;"],
["local", 4, False, 1, "get address of local storage (local variable or argument) (TOS <- (frame + $PARM)).", "r1 = r0;\nr0 = opStack[opStackOfs] = r2+programStack;"],
["jump", 0, False, -1, "branch (code address <- TOS)", ""],
["eq", 4, True, -2, "check equality (signed integer) (compares NIS vs TOS, jump to $PARM if true).", "if ( r1 == r0 ) { programCounter = r2; }"],
["ne", 4, True, -2, "check inequality (signed integer) (NIS vs TOS, jump to $PARM if true).", "if ( r1 != r0 ) { programCounter = r2; }"],
["lti", 4, True, -2, "check less-than (signed integer) (NIS vs TOS, jump to $PARM if true).", "if ( r1 < r0 ) { programCounter = r2; }"],
["lei", 4, True, -2, "check less-than or equal-to (signed integer) (NIS vs TOS, jump to $PARM if true).", "if ( r1 <= r0 ) { programCounter = r2; }"],
["gti", 4, True, -2, "check greater-than (signed integer) (NIS vs TOS), jump to $PARM if true.", "if ( r1 > r0 ) { programCounter = r2; }"],
["gei", 4, True, -2, "check greater-than or equal-to (signed integer) (NIS vs TOS), jump to $PARM if true.", "if ( r1 >= r0 ) { programCounter = r2; }"],
["ltu", 4, True, -2, "check less-than (unsigned integer) (NIS vs TOS), jump to $PARM if true.", "if ( ((unsigned)r1) < ((unsigned)r0) ) { programCounter = r2; }"],
["leu", 4, True, -2, "check less-than or equal-to (unsigned integer) (NIS vs TOS), jump to $PARM if true.", "if ( ((unsigned)r1) <= ((unsigned)r0) ) { programCounter = r2; }\n"],
["gtu", 4, True, -2, "check greater-than (unsigned integer) (NIS vs TOS), jump to $PARM if true.", "if ( ((unsigned)r1) > ((unsigned)r0) ) { programCounter = r2; }\n"],
["geu", 4, True, -2, "check greater-than or equal-to (unsigned integer) (NIS vs TOS), jump to $PARM if true.", "if ( ((unsigned)r1) >= ((unsigned)r0) ) { programCounter = r2; }"],
["eqf", 4, True, -2, "check equality (float) (NIS vs TOS, jump to $PARM if true).", "if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] == ((float *) opStack)[(uint8_t) (opStackOfs + 2)]) { programCounter = r2; }"],
["nef", 4, True, -2, "check inequality (float) (NIS vs TOS, jump to $PARM if true).", "if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] != ((float *) opStack)[(uint8_t) (opStackOfs + 2)]) { programCounter = r2; }"],
["ltf", 4, True, -2, "check less-than (float) (NIS vs TOS, jump to $PARM if true).", "if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] < ((float *) opStack)[(uint8_t) (opStackOfs + 2)]) { programCounter = r2; }"],
["lef", 4, True, -2, "check less-than or equal-to (float) (NIS vs TOS, jump to $PARM if true).", "if(((float *) opStack)[(uint8_t) ((uint8_t) (opStackOfs + 1))] <= ((float *) opStack)[(uint8_t) ((uint8_t) (opStackOfs + 2))]) { programCounter = r2; }"],
["gtf", 4, True, -2, "check greater-than (float) (NIS vs TOS, jump to $PARM if true).", "if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] > ((float *) opStack)[(uint8_t) (opStackOfs + 2)]) { programCounter = r2; }"],
["gef", 4, True, -2, "check greater-than or equal-to (float) (NIS vs TOS, jump to $PARM if true).", "if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] >= ((float *) opStack)[(uint8_t) (opStackOfs + 2)]) { programCounter = r2; }"],
["load1", 0, False, 0, "Load 1-octet value from address in TOS (TOS <- [TOS])", "r0 = opStack[opStackOfs] = image[ r0 & dataMask ];"],
["load2", 0, False, 0, "Load 2-octet value from address in TOS (TOS <- [TOS])", "r0 = opStack[opStackOfs] = *(unsigned short *)&image[ r0 & dataMask ];"],
["load4", 0, False, 0, "Load 4-octet value from address in TOS (TOS <- [TOS])", "r0 = opStack[opStackOfs] = *(int *) &image[ r0 & dataMask ];"],
["store1", 0, False, -2, "lowest octet of TOS is 1-octet value to store, destination address in next-in-stack ([NIS] <- TOS).", "image[ r1 & dataMask ] = r0;"],
["store2", 0, False, -2, "lowest two octets of TOS is 2-octet value to store, destination address in next-in-stack ([NIS] <- TOS).", "*(short *)&image[ r1 & dataMask ] = r0;"],
["store4", 0, False, -2, "TOS is 4-octet value to store, destination address in next-in-stack ([NIS] <- TOS).", "*(int *)&image[ r1 & dataMask ] = r0;"],
["arg", 1, False, -1, "TOS is 4-octet value to store into arguments-marshalling space of the indicated octet offset (ARGS[offset] <- TOS).", "*(int *)&image[ (codeImage[programCounter] + programStack) & dataMask ] = r0;"],
["block_copy", 4, False, -2, "copy $PARM bytes from TOS into NIS.", "VM_BlockCopy(r1, r0, r2);"], # q3vm_specs.html wrong about parameter size
["sex8", 0, False, 0, "Sign-extend 8-bit (TOS <- TOS).", "opStack[opStackOfs] = (signed char) opStack[opStackOfs];"],
["sex16", 0, False, 0, "Sign-extend 16-bit (TOS <- TOS).", "opStack[opStackOfs] = (short) opStack[opStackOfs];"],
["negi", 0, False, 0, "Negate signed integer (TOS <- -TOS).", "opStack[opStackOfs] = -r0;"],
["add", 0, False, -1, "Add integer-wise (TOS <- NIS + TOS).", "opStack[opStackOfs] = r1 + r0;"],
["sub", 0, False, -1, "Subtract integer-wise (TOS <- NIS - TOS).", "opStack[opStackOfs] = r1 - r0;"],
["divi", 0, False, -1, "Divide integer-wise (TOS <- NIS / TOS).", "opStack[opStackOfs] = r1 / r0;"],
["divu", 0, False, -1, "Divide unsigned integer (TOS <- NIS / TOS).", "opStack[opStackOfs] = ((unsigned) r1) / ((unsigned) r0);"],
["modi", 0, False, -1, "Modulo (signed integer) (TOS <- NIS mod TOS).", "opStack[opStackOfs] = r1 % r0;"],
["modu", 0, False, -1, "Modulo (unsigned integer) (TOS <- NIS mod TOS).", "opStack[opStackOfs] = ((unsigned) r1) % ((unsigned) r0);"],
["muli", 0, False, -1, "Multiply (signed integer) (TOS <- NIS * TOS).", "opStack[opStackOfs] = r1 * r0;"],
["mulu", 0, False, -1, "Multiply (unsigned integer) (TOS <- NIS * TOS).", "opStack[opStackOfs] = ((unsigned) r1) * ((unsigned) r0);"],
["band", 0, False, -1, "Bitwise AND (TOS <- NIS & TOS).", "opStack[opStackOfs] = ((unsigned) r1) & ((unsigned) r0);"],
["bor", 0, False, -1, "Bitwise OR (TOS <- NIS | TOS).", "opStack[opStackOfs] = ((unsigned) r1) | ((unsigned) r0);"],
["bxor", 0, False, -1, "Bitwise XOR (TOS <- NIS ^ TOS).", "opStack[opStackOfs] = ((unsigned) r1) ^ ((unsigned) r0);"],
["bcom", 0, False, 0, "Bitwise complement (TOS <- ~TOS).", "opStack[opStackOfs] = ~((unsigned) r0);"],
["lsh", 0, False, -1, "Bitwise left-shift (TOS <- NIS << TOS).", "opStack[opStackOfs] = r1 << r0;"],
["rshi", 0, False, -1, "Algebraic (signed) right-shift (TOS <- NIS >> TOS).", "opStack[opStackOfs] = r1 >> r0;"],
["rshu", 0, False, -1, "Bitwise (unsigned) right-shift (TOS <- NIS >> TOS).", "opStack[opStackOfs] = ((unsigned) r1) >> r0;"],
["negf", 0, False, 0, "Negate float value (TOS <- -TOS).", "((float *) opStack)[opStackOfs] = -((float *) opStack)[opStackOfs];"],
["addf", 0, False, -1, "Add floats (TOS <- NIS + TOS).", "((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] + ((float *) opStack)[(uint8_t) (opStackOfs + 1)];"],
["subf", 0, False, -1, "Subtract floats (TOS <- NIS - TOS).", "((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] - ((float *) opStack)[(uint8_t) (opStackOfs + 1)];"],
["divf", 0, False, -1, "Divide floats (TOS <- NIS / TOS).", "((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] / ((float *) opStack)[(uint8_t) (opStackOfs + 1)];"],
["mulf", 0, False, -1, "Multiply floats (TOS <- NIS x TOS).", "((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] * ((float *) opStack)[(uint8_t) (opStackOfs + 1)];"],
["cvif", 0, False, 0, "Convert signed integer to float (TOS <- TOS).", "((float *) opStack)[opStackOfs] = (float) opStack[opStackOfs];"],
["cvfi", 0, False, 0, "Convert float to signed integer (TOS <- TOS).", "opStack[opStackOfs] = Q_ftol(((float *) opStack)[opStackOfs]);"]
]
(
OP_UNDEF,
OP_IGNORE,
OP_BREAK,
OP_ENTER,
OP_LEAVE,
OP_CALL,
OP_PUSH,
OP_POP,
OP_CONST,
OP_LOCAL,
OP_JUMP,
OP_EQ,
OP_NE,
OP_LTI,
OP_LEI,
OP_GTI,
OP_GEI,
OP_LTU,
OP_LEU,
OP_GTU,
OP_GEU,
OP_EQF,
OP_NEF,
OP_LTF,
OP_LEF,
OP_GTF,
OP_GEF,
OP_LOAD1,
OP_LOAD2,
OP_LOAD4,
OP_STORE1,
OP_STORE2,
OP_STORE4,
OP_ARG,
OP_BLOCK_COPY,
OP_SEX8,
OP_SEX16,
OP_NEGI,
OP_ADD,
OP_SUB,
OP_DIVI,
OP_DIVU,
OP_MODI,
OP_MODU,
OP_MULI,
OP_MULU,
OP_BAND,
OP_BOR,
OP_BXOR,
OP_BCOM,
OP_LSH,
OP_RSHI,
OP_RSHU,
OP_NEGF,
OP_ADDF,
OP_SUBF,
OP_DIVF,
OP_MULF,
OP_CVIF,
OP_CVFI ) = range(60)
# in qvms double and long types are still only 4 bytes
basicTypes = ("byte", "char", "uchar", "short", "ushort", "int", "uint", "float")
SYMBOL_RANGE = 0 # size specified directly
SYMBOL_TEMPLATE = 1
SYMBOL_POINTER_VOID = 2
SYMBOL_POINTER_BASIC = 3 # pointer to basic type
SYMBOL_POINTER_TEMPLATE = 4
# basic types
SYMBOL_BYTE = 5 # unsigned char
SYMBOL_CHAR = 6
SYMBOL_UCHAR = 7
SYMBOL_SHORT = 8
SYMBOL_USHORT = 9
SYMBOL_INT = 10
SYMBOL_UINT = 11
SYMBOL_FLOAT = 12
class ArraySize:
def __init__ (self, value, name=None):
self.value = value
self.name = name
class RangeException(Exception):
pass
class RangeElement:
def __init__ (self, size=0, symbolName="", symbolType=SYMBOL_RANGE, isPointer=False, pointerType="", pointerDepth=0, isArray=False, arrayLevels=[], arrayTemplate="", arrayElementSize=0):
self.size = size;
self.symbolName = symbolName
# templates should have been expanded by the time they are added as ranges
if symbolType == SYMBOL_TEMPLATE and not isArray:
raise RangeException("non-array range element created with template symbol")
self.symbolType = symbolType
self.isPointer = isPointer
# note this is the string name of the type, overriding that type will use the new setting even in previously defined templates
self.pointerType = pointerType
self.pointerDepth = pointerDepth
self.isArray = isArray
self.arrayLevels = arrayLevels # [size1:ArraySize, size2:ArraySize, ...]
self.arrayTemplate = arrayTemplate # '' if basic type or pointer
self.arrayElementSize = arrayElementSize
# turn arrays into ranges
if isArray:
self.symbolType = SYMBOL_RANGE
class TemplateMember:
def __init__ (self, offset=0, size=0, name="", symbolType=SYMBOL_RANGE, isPointer=False, pointerType="", pointerDepth=0, parentTemplatesInfo=[], isArray=False, arrayLevels=[], arrayTemplate="", arrayElementSize=0, aliasUsed=False, origName=""):
self.offset = offset
self.size = size
self.name = name
self.symbolType = symbolType
self.isPointer = isPointer
self.pointerType = pointerType
self.pointerDepth = pointerDepth
self.isArray = isArray
self.arrayLevels = arrayLevels # [size1:ArraySize, size2:ArraySize, ...]
self.arrayTemplate = arrayTemplate
self.arrayElementSize = arrayElementSize
# for debugging
self.aliasUsed = aliasUsed
self.origName = origName # without alias expanded
# info with respect to parent templates
self.parentTemplatesInfo = parentTemplatesInfo # [ [parentTemplate1:str, name1:str, offset1:int, isTemplateRange1:bool, ourTemplate1:str], [parentTemplate2:str, name2:str, offset2:int, isTemplateRange2:bool, ourTemplate2:str], ... ]
class AliasInfo:
def __init__ (self, name, declaration, expansion):
self.name = name
self.declaration = declaration
self.expansion = expansion
class ForwardDeclaration:
def __init__ (self, symbolName, lineCount, fname, line):
self.symbolName = symbolName
self.lineCount = lineCount
self.fname = fname
self.line = line
class Template:
def __init__ (self, size, paddingSize, paddingUsed, members=[]):
self.size = size
self.paddingSize = paddingSize
self.paddingUsed = paddingUsed
self.members = members # [ member1:TemplateMember, member2:TemplateMember, ... ]
class TemplateManager:
def __init__ (self):
self.symbolTemplates = {} # name:str -> template:Template
self.arrayConstants = {} # name:str -> value:int
self.templateAliases = {} # name:str -> sub:AliasInfo
self.forwardDeclarations = [] # [ declaration1:ForwardDeclaration ... ]
def pad_up (self, offset, paddingSize):
if paddingSize < 0:
error_exit("invalid padding size: %d" % paddingSize)
if paddingSize == 0:
return offset
if offset % paddingSize == 0:
return offset
return (offset + paddingSize) - (offset % paddingSize)
def check_for_template_alias (self, typeString):
s = typeString
pdEnd = 0
for c in s:
if c == '*':
pdEnd += 1
else:
break
if pdEnd > 0:
pointerDeclaration = s[:pdEnd]
s = s[pdEnd:]
else:
pointerDeclaration = ""
symEnd = 0
for c in s:
if c != '[':
symEnd += 1
else:
break
if symEnd > 0:
symbolDeclaration = s[:symEnd]
s = s[symEnd:]
else:
symbolDeclaration = ""
arrayDeclaration = s
if symbolDeclaration in self.templateAliases:
symbolDeclaration = self.templateAliases[symbolDeclaration].expansion
aliasUsed = True
else:
aliasUsed = False
s = pointerDeclaration + symbolDeclaration + arrayDeclaration
#print("xxxxxx %s -> %s" % (s, symbolDeclaration))
return (aliasUsed, s)
def check_for_array_declaration (self, typeString):
isArray = False
arrayLevels = []
isValid = True
name = typeString
# ex: 'matrix[3][6]' -> ['matrix', '3]', '6]']
match = typeString.split('[')
if len(match) == 1: # ex: ['float']
return (True, typeString, False, [])
isArray = True
for m in match[1:]:
# check for invalid or unsupported declarations
# ex: nested array 'hello[11[22]]' -> ['hello', '11', '22]]']
if m[-1] != ']':
isValid = False
break
m = m[:-1]
if ']' in m:
isValid = False
break
name = None
if m in self.arrayConstants:
name = m
size = self.arrayConstants[m]
else:
try:
size = parse_int(m)
except ValueError:
isValid = False
break
if size < 0:
isValid = False
break
arrayLevels.append(ArraySize(size, name=name))
return (isValid, match[0], isArray, arrayLevels)
def parse_symbol_or_size (self, words, lineCount, fname, line, currentParsingTemplate=None):
# currently only checks words[0] but could potentially allow spaces
# for pointer or array declarations
def ferror_exit (msg):
error_exit("%s in line %d of %s: %s" % (msg, lineCount + 1, fname, line))
size = 0
template = None
symbolType = SYMBOL_RANGE
isPointer = False
pointerType = ""
pointerDepth = 0
isArray = False
arrayLevels = [] # ex: [ArraySize(3), ArraySize(3)] for float[3][3]
arrayElementSize = 0
aliasUsed = False
word = words[0]
firstChar = word[0]
if firstChar.isdigit() or firstChar in ('+', '-'):
try:
size = parse_int(word)
except ValueError:
ferror_exit("couldn't parse size")
if size < 0:
ferror_exit("invalid size")
else: # template or basic type
# check for aliases
(aliasUsed, word) = self.check_for_template_alias(word)
# check for array
# Note: pointer to array isn't supported, if both pointer and
# array declarations are used it will be array of pointers
(isValid, word, isArray, arrayLevels) = self.check_for_array_declaration(word)
if not isValid:
ferror_exit("invalid array declaration")
# check for pointer and pointer depth
wlen = len(word)
for i in range(wlen):
if word[i] == '*':
isPointer = True
pointerDepth += 1
else:
break
if isPointer:
w = word[i:]
pointerType = w
symbolType = SYMBOL_POINTER_TEMPLATE
if pointerType == "void":
symbolType = SYMBOL_POINTER_VOID
elif pointerType in basicTypes:
symbolType = SYMBOL_POINTER_BASIC
else:
if not valid_symbol_name(pointerType):
ferror_exit("invalid pointer name")
# check that it exists or is the current template being parsed
if pointerType not in self.symbolTemplates and pointerType != currentParsingTemplate:
#ferror_exit("unknown pointer type")
# check later
self.forwardDeclarations.append(ForwardDeclaration(pointerType, lineCount, fname, line))
symbolType = SYMBOL_POINTER_TEMPLATE
size = 0x4
else: # template or basic type
w = word
if w == "byte":
symbolType = SYMBOL_BYTE
size = 0x1
elif w == "char":
symbolType = SYMBOL_CHAR
size = 0x1
elif w == "uchar":
symbolType = SYMBOL_UCHAR
size = 0x1
elif w == "short":
symbolType = SYMBOL_SHORT
size = 0x2
elif w == "ushort":
symbolType = SYMBOL_USHORT
size = 0x2
elif w == "int":
symbolType = SYMBOL_INT
size = 0x4
elif w == "uint":
symbolType = SYMBOL_UINT
size = 0x4
elif w == "float":
symbolType = SYMBOL_FLOAT
size = 0x4
else:
symbolType = SYMBOL_TEMPLATE
template = w
if not valid_symbol_name(template):
ferror_exit("invalid template name")
if template not in self.symbolTemplates:
ferror_exit("parsed unknown template")
size = self.symbolTemplates[template].size
if isArray:
arrayElementSize = size
for a in arrayLevels:
size *= a.value
return (size, symbolType, template, isPointer, pointerType, pointerDepth, isArray, arrayLevels, arrayElementSize, aliasUsed)
def load_symbol_templates_file (self, fname, allowOverride=False):
# ex:
# vmCvar_t 0x110
# {
# 0x0 0x4 handle
# 0x4 0x4 modificationCount
# ...
# }
def ferror_exit (msg):
error_exit("%s in line %d of %s: %s" % (msg, lineCount + 1, fname, line))
def fwarning_msg (msg):
warning_msg("%s in line %d of %s: %s" % (msg, lineCount + 1, fname, line))
f = open(fname)
lines = f.readlines()
f.close()
lineCount = 0
haveTemplateInfo = False
skipOpeningBrace = False
for line in lines:
# strip comments and trailing/ending whitespace
line = line.split(";")[0]
line = line.strip()
words = line.split()
# skip empty lines
if len(words) == 0:
lineCount += 1
continue
if haveTemplateInfo and skipOpeningBrace:
if len(words) != 1 or words[0] != "{":
ferror_exit("invalid opening brace")
skipOpeningBrace = False
lineCount += 1
continue
if not haveTemplateInfo:
if words[0] == "%alias":
if len(words) != 3:
ferror_exit("invalid alias declaration")
aliasString = words[1]
aliasName = words[2]
if not valid_symbol_name(aliasName):
ferror_exit("invalid alias name")
if aliasName in self.symbolTemplates:
ferror_exit("template exists with same name")
if not allowOverride and aliasName in self.templateAliases:
ferror_exit("alias already exists")
# expand other possible alias reference
(aliasUsed, aliasString) = self.check_for_template_alias(aliasString)
self.templateAliases[aliasName] = AliasInfo(name=aliasName, declaration=words[1], expansion=aliasString)
lineCount += 1
continue
if words[0] == "%arrayConstant":
if len(words) != 3:
ferror_exit("invalid array constant declaration")
cname = words[1]
c = cname[0]
if c.isdigit() or c == '+' or c == '-':
ferror_exit("invalid array constant name")
try:
cvalue = parse_int(words[2])
except ValueError:
ferror_exit("couldn't parse array constant value")
if not allowOverride and cname in self.arrayConstants:
ferror_exit("array constant already exists")
self.arrayConstants[cname] = cvalue
lineCount += 1
continue
# getting template info
# size and opening brace optional, ex: sx_t 0x100 {
haveTemplateSize = False
parseTemplateSize = False
if len(words) == 1:
# just name
pass
elif len(words) == 2:
# name plus size or opening brace
if words[1] != "{":
parseTemplateSize = True
elif len(words) == 3:
# name plus size plus opening brace
parseTemplateSize = True
else:
ferror_exit("invalid word count in template declaration")
templateName = words[0]
if not valid_symbol_name(templateName):
ferror_exit("invalid template name")
if templateName in self.templateAliases:
ferror_exit("alias exists with same name")
if not allowOverride and templateName in self.symbolTemplates:
ferror_exit("template already exists")
if parseTemplateSize:
try:
templateSize = parse_int(words[1])
except ValueError:
ferror_exit("couldn't parse template size")
if templateSize < 0:
ferror_exit("invalid template size")
haveTemplateSize = True
haveTemplateInfo = True
if words[-1] == "{":
skipOpeningBrace = False
else:
skipOpeningBrace = True
paddingSize = 0
currentOffset = 0
memberList = []
lineCount += 1
continue
# parsing template at this point
if words[0] == "}":
if len(words) != 1:
ferror_exit("invalid closing brace")
paddingUsed = 0
if not haveTemplateSize:
templateSize = 0
if len(memberList) > 0:
m = memberList[-1]
ts = m.offset + m.size
templateSize = self.pad_up(ts, paddingSize)
paddingUsed = templateSize - ts
self.symbolTemplates[templateName] = Template(size=templateSize, paddingSize=paddingSize, paddingUsed=paddingUsed, members=memberList)
lineCount += 1
haveTemplateInfo = False
continue
# parsing members (offset optional), ex: '0x0 0x4 handle' or 'int count'
if len(words) not in (2, 3):
ferror_exit("invalid word count in member declaration")
haveOffset = False
symbolIndex = 1
if len(words) == 3:
try:
memberOffset = parse_int(words[0])
except ValueError:
ferror_exit("couldn't get member offset")
if memberOffset < 0:
ferror_exit("invalid offset")
haveOffset = True
symbolIndex = 1
else: # len(words) == 2
haveOffset = False
symbolIndex = 0
(memberSize, memberSymbolType, memberTemplate, memberIsPointer, memberPointerType, memberPointerDepth, memberIsArray, memberArrayLevels, memberArrayElementSize, memberAliasUsed) = self.parse_symbol_or_size(words[symbolIndex:], lineCount, fname, line, currentParsingTemplate=templateName)
memberName = words[symbolIndex + 1]
if not valid_symbol_name(memberName):
ferror_exit("invalid member name")
# make sure name is unique
for m in memberList:
if m.name == memberName:
ferror_exit("duplicate member name")
if memberTemplate and not memberIsArray:
memberTemplateSize = self.symbolTemplates[memberTemplate].size
if self.symbolTemplates[memberTemplate].paddingSize > paddingSize:
paddingSize = self.symbolTemplates[memberTemplate].paddingSize
if not haveOffset:
memberOffset = self.pad_up(currentOffset, self.symbolTemplates[memberTemplate].paddingSize)
haveOffset = True
memberTemplateMembers = self.symbolTemplates[memberTemplate].members
# add member template itself
memberList.append(TemplateMember(offset=memberOffset, size=memberTemplateSize, name=memberName, parentTemplatesInfo=[[templateName, memberName, memberOffset, True, memberTemplate]], aliasUsed=memberAliasUsed, origName=words[1]))
# check if it overrides, only need to check previous member if
# there's also a check that members are added in order
if len(memberList) > 1:
prevMember = memberList[-2]
if memberOffset < prevMember.offset:
fwarning_msg("member template '%s' out of order" % memberName)
elif memberOffset < (prevMember.offset + prevMember.size):
fwarning_msg("member template '%s' overrides previous member" % memberName)
for m in memberTemplateMembers:
adjOffset = memberOffset + m.offset
ptinfo = m.parentTemplatesInfo[:]
# ptinfo[-1][3] : keep specifying that it's the range for entire template, also keep the template name
ptinfo.append([templateName, "%s.%s" % (memberName, m.name), m.offset, ptinfo[-1][3], ptinfo[-1][4]])
# don't need to check for override or order since this is a previously defined template
memberList.append(TemplateMember(offset=adjOffset, size=m.size, name="%s.%s" % (memberName, m.name), symbolType=m.symbolType, isPointer=m.isPointer, pointerType=m.pointerType, pointerDepth=m.pointerDepth, parentTemplatesInfo=ptinfo[:], isArray=m.isArray, arrayLevels=m.arrayLevels, arrayTemplate=m.arrayTemplate, arrayElementSize=m.arrayElementSize, aliasUsed=m.aliasUsed, origName=m.origName))
currentOffset += memberTemplateSize
else: # basic type, range, pointer, or array
# padding check
psize = 4
msymt = memberSymbolType
if msymt == SYMBOL_RANGE:
psize = 0
elif msymt in (SYMBOL_BYTE, SYMBOL_CHAR, SYMBOL_UCHAR):
psize = 1
elif msymt in (SYMBOL_SHORT, SYMBOL_USHORT):
psize = 2
elif msymt == SYMBOL_TEMPLATE: # it is array of templates, straight templates handled before
psize = self.symbolTemplates[memberTemplate].paddingSize
if psize > paddingSize:
paddingSize = psize
if not haveOffset:
memberOffset = self.pad_up(currentOffset, psize)
currentOffset = memberOffset
haveOffset = True
else:
currentOffset = memberOffset
memberList.append(TemplateMember(offset=memberOffset, size=memberSize, name=memberName, symbolType=memberSymbolType, isPointer=memberIsPointer, pointerType=memberPointerType, pointerDepth=memberPointerDepth, parentTemplatesInfo=[[templateName, memberName, memberOffset, False, ""]], isArray=memberIsArray, arrayLevels=memberArrayLevels, arrayTemplate=memberTemplate, arrayElementSize=memberArrayElementSize, aliasUsed=memberAliasUsed, origName=words[1]))
# check if it overrides, only need to check previous member if
# there's also a check that members are added in order
if len(memberList) > 1:
prevMember = memberList[-2]
if memberOffset < prevMember.offset:
fwarning_msg("member '%s' out of order" % memberName)
elif memberOffset < (prevMember.offset + prevMember.size):
fwarning_msg("member '%s' overrides previous member" % memberName)
currentOffset += memberSize
lineCount += 1
if haveTemplateInfo:
# never finished parsing last template
ferror_exit("last template not closed")
# check that forward declarations exist
for d in self.forwardDeclarations:
if d.symbolName not in self.symbolTemplates:
error_exit("undefined declaration %s in line %d of %s: %s" % (d.symbolName, d.lineCount + 1, d.fname, d.line))
def load_default_templates (self):
fname = TEMPLATES_DEFAULT_FILE
if os.path.exists(fname):
# override default one
self.load_symbol_templates_file(fname, allowOverride=False)
else:
fname = os.path.join(BASE_DIR, TEMPLATES_DEFAULT_FILE)
if os.path.exists(fname):
self.load_symbol_templates_file(fname, allowOverride=False)
fname = TEMPLATES_FILE
if os.path.exists(fname):
self.load_symbol_templates_file(fname, allowOverride=True)
class InvalidQvm(Exception):
pass
ReplaceDecompiled = False
class Qvm:
# qvmType:("cgame", "game", "ui", None)
def __init__ (self, qvmFileName, qvmType=None):
qvmFile = LEBinFile(qvmFileName)
self.magic = qvmFile.read_int()
if self.magic != QVM_MAGIC_VER1 and self.magic != QVM_MAGIC_VER2:
qvmFile.close()
raise InvalidQvm("not a valid qvm file, magic 0x%x != (0x%x | 0x%x)" % (self.magic, QVM_MAGIC_VER1, QVM_MAGIC_VER2))
# q3vm_specs.html wrong about header, it's offset and then length
self.instructionCount = qvmFile.read_int()
self.codeSegOffset = qvmFile.read_int()
self.codeSegLength = qvmFile.read_int()
self.dataSegOffset = qvmFile.read_int()
self.dataSegLength = qvmFile.read_int()
self.litSegOffset = self.dataSegOffset + self.dataSegLength
self.litSegLength = qvmFile.read_int()
self.bssSegOffset = self.dataSegOffset + self.dataSegLength + self.litSegLength
self.bssSegLength = qvmFile.read_int()
if self.magic != QVM_MAGIC_VER1:
self.jumpTableOffset = self.litSegOffset + self.litSegLength
self.jumpTableLength = qvmFile.read_int()
else:
self.jumpTableLength = 0
# validate header values
if self.instructionCount < 0:
qvmFile.close()
raise InvalidQvm("bad header: instructionCount %d" % self.instructionCount)
if self.codeSegOffset < 0:
qvmFile.close()
raise InvalidQvm("bad header: codeSegOffset %d" % self.codeSegOffset)
if self.codeSegLength < 0:
qvmFile.close()
raise InvalidQvm("bad header: codeSegLength %d" % self.codeSegLength)
if self.dataSegOffset < 0:
qvmFile.close()
raise InvalidQvm("bad header: dataSegOffset %d" % self.dataSegOffset)
if self.dataSegLength < 0:
qvmFile.close()
raise InvalidQvm("bad header: dataSegLength %d" % self.dataSegLength)
if self.litSegLength < 0:
qvmFile.close()
raise InvalidQvm("bad header: litSegLength %d" % self.litSegLength)
if self.bssSegLength < 0:
qvmFile.close()
raise InvalidQvm("bad header: bssSegLength %d" % self.bssSegLength)
if self.jumpTableLength < 0:
qvmFile.close()
raise InvalidQvm("bad header: jumpTableLength %d" % self.jumpTableLength)
qvmFile.seek(self.codeSegOffset)
self.codeData = qvmFile.read(self.codeSegLength)
self.codeData = self.codeData + b"\x00\x00\x00\x00\x00" # for look ahead
qvmFile.seek(self.dataSegOffset)
self.dataData = qvmFile.read(self.dataSegLength)
self.dataData = self.dataData + b"\x00\x00\x00\x00" # for look ahead
qvmFile.seek(self.litSegOffset)
self.litData = qvmFile.read(self.litSegLength)
self.litData = self.litData + b"\x00\x00\x00\x00" # for look ahead
if self.magic != QVM_MAGIC_VER1:
self.jumpTableData = qvmFile.read(self.jumpTableLength)
else:
self.jumpTableData = b""
qvmFile.close()
self.syscalls = {} # num:int -> name:str
self.functions = {} # addr:int -> name:str
# user labels
# ArgRangeLabels could just be part of LocalRangeLabels but local
# address isn't known when the function is defined
self.functionsArgRangeLabels = {} # addr:int -> { argX:str -> range:RangeElement }
self.functionsLocalLabels = {} # addr:int -> { localAddr:int -> sym:str }
self.functionsLocalRangeLabels = {} # addr:int -> { localAddr:int -> [ range1:RangeElement, range2:RangeElement, ... ] }
self.functionHashes = {} # addr:int -> hash:int
self.functionRevHashes = {} # hash:int -> [funcAddr1:int, funcAddr2:int, ...]
self.functionSizes = {} # addr:int -> instructionCount:int
self.functionMaxArgsCalled = {} # addr:int -> maxArgs:int
self.functionParmNum = {} # addr:int -> num:int
self.baseQ3FunctionRevHashes = {} # hash:int -> [ funcName1, funcName2, ... ]
self.symbols = {} # addr:int -> sym:str
self.symbolsRange = {} # addr:int -> [ range1:RangeElement, range2:RangeElement, ... ]
self.templateManager = TemplateManager()
self.constants = {} # codeAddr:int -> [ name:str, value:int ]
# code segment comments
self.commentsInline = {} # addr:int -> comment:str
self.commentsBefore = {} # addr:int -> [ line1:str, line2:str, ... ]
self.commentsBeforeSpacing = {} # addr:int -> [ spaceBefore:int, spaceAfter:int ]
self.commentsAfter = {} # addr:int -> [ line1:str, line2:str, ... ]
self.commentsAfterSpacing = {} # addr:int -> [ spaceBefore:int, spaceAfter: int ]
# data segment comments
self.dataCommentsInline = {} # addr:int -> comment:str
self.dataCommentsBefore = {} # addr:int -> [ line1:str, line2:str, ... ]
self.dataCommentsBeforeSpacing = {} # addr:int -> [ spaceBefore:int, spaceAfter:int ]
self.dataCommentsAfter = {} # addr:int -> [ line1:str, line2:str, ... ]
self.dataCommentsAfterSpacing = {} # addr:int -> [ spaceBefore:int, spaceAfter: int ]
self.jumpPoints = {} # targetAddr:int -> [ jumpPointAddr1:int, jumpPointAddr2:int, ... ]
self.switchStartStatements = [] # [ addr1:int, addr2:int, ... ]
self.switchJumpStatements = {} # addr:int -> [ minValue:int, maxValue:int, switchJumpTableAddress:int ]
self.switchJumpPoints = {} # targetAddr:int -> [ [ jumpPointAddr1:int, caseValue:int ], [ jumpPointAddr2:int, caseValue:int ], ... ]
self.switchDataTable = {} # addr:int -> [ switchCodeAddr1:int, switchCodeAddr2:int, ... ]
self.callPoints = {} # targetAddr:int -> [ callerAddr1:int, callerAddr2:int, ... ]
self.jumpTableTargets = [] # [ targetAddr1:int, targetAddr2:int, targetAddr3:int, ... ]
self.pointerDereference = {} # addr:int -> [ local:bool, pointerAddr:int, offset:int ]
self.set_qvm_type(qvmType)
self.load_address_info()
self.parse_jump_table()
self.compute_function_info()
def set_qvm_type (self, qvmType):
def ferror_exit (msg):
error_exit("%s in line %d of %s: %s" % (msg, lineCount + 1, fname, line))
self.qvmType = qvmType
if qvmType not in ("cgame", "game", "ui"):