-
Notifications
You must be signed in to change notification settings - Fork 49
/
types.py
1583 lines (1373 loc) · 60.1 KB
/
types.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
import copy
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set, Tuple, Union
import pycparser.c_ast as ca
from .c_types import (
CType,
Enum,
Struct,
StructUnion as CStructUnion,
TypeMap,
UndefinedStructError,
is_unk_type,
parse_constant_int,
parse_function,
parse_struct,
primitive_size,
resolve_typedefs,
set_decl_name,
to_c,
)
from .demangle_codewarrior import CxxName, CxxSymbol, CxxTerm, CxxType
from .error import DecompFailure, static_assert_unreachable
from .options import Formatter
# AccessPath represents a struct/array path, with ints for array access, and
# strs for struct fields. Ex: `["foo", 3, "bar"]` represents `.foo[3].bar`
AccessPath = List[Union[str, int]]
@dataclass
class TypePool:
"""
Mutable shared state for Types, maintaining the set of available struct types.
"""
unknown_field_prefix: str
unk_inference: bool
structs: Set["StructDeclaration"] = field(default_factory=set)
structs_by_tag_name: Dict[str, "StructDeclaration"] = field(default_factory=dict)
structs_by_ctype: Dict[CStructUnion, "StructDeclaration"] = field(
default_factory=dict
)
unknown_decls: Dict[str, "Type"] = field(default_factory=dict)
warnings: List[str] = field(default_factory=list)
def get_struct_for_ctype(
self,
ctype: CStructUnion,
) -> Optional["StructDeclaration"]:
"""Return the StructDeclaration for a given ctype struct, if known"""
struct = self.structs_by_ctype.get(ctype)
if struct is not None:
return struct
if ctype.name is not None:
return self.structs_by_tag_name.get(ctype.name)
return None
def get_or_create_struct_by_tag_name(
self,
tag_name: str,
typemap: Optional[TypeMap],
*,
size: Optional[int] = None,
with_typedef: bool = False,
) -> "StructDeclaration":
struct = self.get_struct_by_tag_name(tag_name, typemap)
if struct is not None:
return struct
struct = StructDeclaration.unknown(self, size, tag_name, align=4)
if with_typedef:
struct.typedef_name = tag_name
return struct
def get_struct_by_tag_name(
self,
tag_name: str,
typemap: Optional[TypeMap],
) -> Optional["StructDeclaration"]:
"""
Return the StructDeclaration with the given tag name, if available.
If the struct is not already known and typemap is provided, try to find it there.
"""
struct = self.structs_by_tag_name.get(tag_name)
if struct is not None:
return struct
if typemap is not None:
cstruct = typemap.structs.get(tag_name)
if cstruct is not None:
type = Type.ctype(cstruct.type, typemap, self)
return type.get_struct_declaration()
return None
def add_struct(
self,
struct: "StructDeclaration",
ctype_or_tag_name: Union[CStructUnion, str],
) -> None:
"""Add the struct declaration to the set of known structs for later access"""
self.structs.add(struct)
tag_name: Optional[str]
if isinstance(ctype_or_tag_name, str):
tag_name = ctype_or_tag_name
else:
ctype = ctype_or_tag_name
tag_name = ctype.name
self.structs_by_ctype[ctype] = struct
if tag_name is not None:
assert (
tag_name not in self.structs_by_tag_name
), f"Duplicate tag: {tag_name}"
self.structs_by_tag_name[tag_name] = struct
def format_type_declarations(self, fmt: Formatter, stack_structs: bool) -> str:
decls = []
for struct in sorted(
self.structs, key=lambda s: s.tag_name or s.typedef_name or ""
):
# Only output stack structs if `stack_structs` is enabled
if not stack_structs and struct.is_stack:
continue
# Include any struct with added fields, plus any stack structs
if any(not f.known for f in struct.fields) or struct.is_stack:
decls.append(struct.format(fmt) + "\n")
return "\n".join(decls)
def prune_structs(self) -> None:
"""Remove overlapping fields from all known structs"""
for struct in self.structs:
struct.prune_overlapping_fields()
struct.rename_inferred_vtables()
@dataclass(eq=False)
class TypeData:
K_INT = 1 << 0
K_PTR = 1 << 1
K_FLOAT = 1 << 2
K_FN = 1 << 3
K_VOID = 1 << 4
K_ARRAY = 1 << 5
K_STRUCT = 1 << 6
K_INTPTR = K_INT | K_PTR
K_ANYREG = K_INT | K_PTR | K_FLOAT
K_ANY = K_INT | K_PTR | K_FLOAT | K_FN | K_VOID | K_ARRAY | K_STRUCT
SIGNED = 1
UNSIGNED = 2
ANY_SIGN = 3
kind: int = K_ANY
likely_kind: int = K_ANY # subset of kind
size_bits: Optional[int] = None
uf_parent: Optional["TypeData"] = None
sign: int = ANY_SIGN # K_INT
ptr_to: Optional["Type"] = None # K_PTR | K_ARRAY
fn_sig: Optional["FunctionSignature"] = None # K_FN
array_dim: Optional[int] = None # K_ARRAY
struct: Optional["StructDeclaration"] = None # K_STRUCT
enum: Optional[Enum] = None # K_INT
new_field_within: Set["StructDeclaration"] = field(default_factory=set)
def __post_init__(self) -> None:
assert self.kind
self.likely_kind &= self.kind
def get_representative(self) -> "TypeData":
# Follow `uf_parent` links until we hit the "root" TypeData
equivalent_typedatas = set()
root = self
while root.uf_parent is not None:
assert root not in equivalent_typedatas, "TypeData cycle detected"
equivalent_typedatas.add(root)
root = root.uf_parent
# Set the `uf_parent` pointer on all visited TypeDatas
for td in equivalent_typedatas:
td.uf_parent = root
return root
@dataclass(eq=False, repr=False)
class Type:
"""
Type information for an expression, which may improve over time. The least
specific type is any (initially the case for e.g. arguments); this might
get refined into intish if the value gets used for e.g. an integer add
operation, or into u32 if it participates in a logical right shift.
Types cannot change except for improvements of this kind -- thus concrete
types like u32 can never change into anything else, and e.g. ints can't
become floats.
"""
_data: TypeData
def unify(self, other: "Type", *, seen: Optional[Set["TypeData"]] = None) -> bool:
"""
Try to set this type equal to another. Returns true on success.
Once set equal, the types will always be equal (we use a union-find
structure to ensure this).
The seen argument is used during recursion, to track which TypeData
objects have been encountered so far.
"""
x = self.data()
y = other.data()
if x is y:
return True
# If we hit a type that we have already seen, fail.
# TODO: Is there a looser check that would allow more types to unify?
if seen is None:
seen = {x, y}
elif x in seen or y in seen:
return False
else:
seen = seen | {x, y}
if (
x.size_bits is not None
and y.size_bits is not None
and x.size_bits != y.size_bits
):
return False
kind = x.kind & y.kind
likely_kind = x.likely_kind & y.likely_kind
size_bits = x.size_bits if x.size_bits is not None else y.size_bits
ptr_to = x.ptr_to if x.ptr_to is not None else y.ptr_to
fn_sig = x.fn_sig if x.fn_sig is not None else y.fn_sig
array_dim = x.array_dim if x.array_dim is not None else y.array_dim
struct = x.struct if x.struct is not None else y.struct
enum = x.enum if x.enum is not None else y.enum
sign = x.sign & y.sign
if size_bits not in (None, 32, 64):
kind &= ~TypeData.K_FLOAT
if size_bits not in (None, 32):
kind &= ~TypeData.K_PTR
if size_bits not in (None,):
kind &= ~TypeData.K_FN
if size_bits not in (None, 0):
kind &= ~TypeData.K_VOID
likely_kind &= kind
if kind == 0 or sign == 0:
return False
if kind == TypeData.K_PTR:
size_bits = 32
if sign != TypeData.ANY_SIGN:
assert kind & TypeData.K_INTPTR
if enum is not None:
assert kind == TypeData.K_INT
if x.ptr_to is not None and y.ptr_to is not None:
if not x.ptr_to.unify(y.ptr_to, seen=seen):
return False
if x.fn_sig is not None and y.fn_sig is not None:
if not x.fn_sig.unify(y.fn_sig, seen=seen):
return False
if x.array_dim is not None and y.array_dim is not None:
if x.array_dim != y.array_dim:
return False
if x.struct is not None and y.struct is not None:
if not x.struct.unify(y.struct, seen=seen):
return False
if x.enum is not None and y.enum is not None:
if x.enum != y.enum:
return False
if y.struct in x.new_field_within or x.struct in y.new_field_within:
# Disallow recursive structs: if y is a struct that has a newly added
# field of (yet unknown) type x, don't allow unifying x and y.
return False
x.kind = kind
x.likely_kind = likely_kind
x.size_bits = size_bits
x.sign = sign
x.ptr_to = ptr_to
x.fn_sig = fn_sig
x.array_dim = array_dim
x.struct = struct
x.enum = enum
x.new_field_within |= y.new_field_within
y.uf_parent = x
return True
def data(self) -> "TypeData":
if self._data.uf_parent is None:
return self._data
self._data = self._data.get_representative()
return self._data
def is_float(self) -> bool:
return self.data().kind == TypeData.K_FLOAT
def is_likely_float(self) -> bool:
data = self.data()
return data.kind == TypeData.K_FLOAT or data.likely_kind == TypeData.K_FLOAT
def is_pointer(self) -> bool:
return self.data().kind == TypeData.K_PTR
def is_pointer_or_array(self) -> bool:
return self.data().kind in (TypeData.K_PTR, TypeData.K_ARRAY)
def is_int(self) -> bool:
return self.data().kind == TypeData.K_INT
def is_reg(self) -> bool:
return (self.data().kind & ~TypeData.K_ANYREG) == 0
def is_function(self) -> bool:
return self.data().kind == TypeData.K_FN
def is_void(self) -> bool:
return self.data().kind == TypeData.K_VOID
def is_array(self) -> bool:
return self.data().kind == TypeData.K_ARRAY
def is_struct(self) -> bool:
return self.data().kind == TypeData.K_STRUCT
def is_signed(self) -> bool:
return self.data().sign == TypeData.SIGNED
def is_unsigned(self) -> bool:
return self.data().sign == TypeData.UNSIGNED
def get_enum_name(self, value: int) -> Optional[str]:
data = self.data()
if data.enum is None:
return None
return data.enum.names.get(value)
def get_size_bits(self) -> Optional[int]:
return self.data().size_bits
def get_size_bytes(self) -> Optional[int]:
size_bits = self.get_size_bits()
return None if size_bits is None else size_bits // 8
def get_parameter_size_align_bytes(self) -> Tuple[int, int]:
"""Return the size & alignment of self when used as a function argument"""
data = self.data()
if self.is_struct():
assert data.struct is not None
if data.struct.size is None:
raise DecompFailure(f"Cannot use incomplete type {self} as parameter")
return data.struct.size, data.struct.align
size = (self.get_size_bits() or 32) // 8
return size, size
def get_pointer_target(self) -> Optional["Type"]:
"""If self is a pointer-to-a-Type, return the Type"""
data = self.data()
if self.is_pointer() and data.ptr_to is not None:
return data.ptr_to
return None
def reference(self) -> "Type":
"""Return a pointer to self. If self is an array, decay the type to a pointer"""
if self.is_array():
data = self.data()
assert data.ptr_to is not None
return Type.ptr(data.ptr_to)
return Type.ptr(self)
def decay(self) -> "Type":
"""If self is an array, return a pointer to the element type. Otherwise, return self."""
if self.is_array():
data = self.data()
assert data.ptr_to is not None
return Type.ptr(data.ptr_to)
return self
def weaken_void_ptr(self) -> "Type":
"""If self is an explicit `void *`, return `Type.ptr()` without an target type."""
target = self.get_pointer_target()
if target is not None and target.is_void():
return Type.ptr()
return self
def get_array(self) -> Tuple[Optional["Type"], Optional[int]]:
"""If self is an array, return a tuple of the inner Type & the array dimension"""
if not self.is_array():
return None, None
data = self.data()
assert data.ptr_to is not None
return (data.ptr_to, data.array_dim)
def get_function_pointer_signature(self) -> Optional["FunctionSignature"]:
"""If self is a function pointer, return the FunctionSignature"""
data = self.data()
if self.is_pointer() and data.ptr_to is not None:
ptr_to = data.ptr_to.data()
if ptr_to.kind == TypeData.K_FN:
return ptr_to.fn_sig
return None
def get_struct_declaration(self) -> Optional["StructDeclaration"]:
"""If self is a struct, return the StructDeclaration"""
if self.is_struct():
data = self.data()
assert data.struct is not None
return data.struct
return None
GetFieldResult = Tuple[Optional[AccessPath], "Type", int]
def get_field(
self, offset: int, *, target_size: Optional[int], exact: bool = True
) -> GetFieldResult:
"""
Locate the field in self at the appropriate offset, and optionally
with an exact target size (both values in bytes).
The target size can be used to disambiguate different fields in a union, or
different levels inside nested structs.
The return value is a tuple of `(field_path, field_type, remaining_offset)`.
If `exact` is True, then `remaining_offset` is always 0. If no field is
found, the result is `(None, Type.any(), 0)`.
If `exact` is False, then `remaining_offset` may be nonzero. This means there
was *not* a field at the exact offset provided; the returned field is at
`(offset - remaining_offset)`.
"""
NO_MATCHING_FIELD: Type.GetFieldResult = (None, Type.any(), 0)
if offset < 0:
return NO_MATCHING_FIELD
if self.is_array():
# Array types always have elements with known size
data = self.data()
assert data.ptr_to is not None
size = data.ptr_to.get_size_bytes()
assert size is not None
index, remaining_offset = divmod(offset, size)
if data.array_dim is not None and index >= data.array_dim:
return NO_MATCHING_FIELD
assert index >= 0 and remaining_offset >= 0
# Assume this is an array access at the computed `index`.
# Check if there is a field at the `remaining_offset` offset
subpath, subtype, sub_remaining_offset = data.ptr_to.get_field(
remaining_offset,
target_size=target_size,
exact=exact,
)
if subpath is not None:
# Success: prepend `index` and return
subpath.insert(0, index)
return subpath, subtype, sub_remaining_offset
return NO_MATCHING_FIELD
if self.is_struct():
data = self.data()
assert data.struct is not None
if data.struct.size is not None and offset >= data.struct.size:
return NO_MATCHING_FIELD
# Get a list of fields which contain the byte at offset. There may be more
# than one if the StructDeclaration is for a union.
possible_fields = data.struct.fields_containing_offset(offset)
# We don't support bitfield access. If there isn't a field at the given offset,
# it's better to bail early. We're likely recursively resolving a field, and
# it's better for the caller to check for other fields (like in a union) than
# to get a reference to a struct with bitfields.
if not possible_fields and data.struct.has_bitfields:
return NO_MATCHING_FIELD
# One option is to return the whole struct itself. Do not do this if the struct
# is marked as a stack struct, or if `target_size` is specified and does not match.
possible_results: List[Type.GetFieldResult] = []
can_return_self = False
if not data.struct.is_stack and (
target_size is None or target_size == self.get_size_bytes()
):
possible_results.append(([], self, offset))
can_return_self = True
# Recursively check each of the `possible_fields` to find the best matches
# for fields at the given offset.
for field in possible_fields:
inner_offset_bits = offset - field.offset
subpath, subtype, sub_remaining_offset = field.type.get_field(
inner_offset_bits,
target_size=target_size,
exact=exact,
)
if subpath is None:
continue
subpath.insert(0, field.name)
possible_results.append((subpath, subtype, sub_remaining_offset))
# Check if this subfield is an exact match. If it is, return it.
if (
target_size is not None
and target_size == subtype.get_size_bytes()
and sub_remaining_offset == 0
):
return possible_results[-1]
zero_offset_results = [r for r in possible_results if r[2] == 0]
if zero_offset_results:
# Try returning the first field which was at the correct offset,
# but has the wrong size
return zero_offset_results[0]
elif exact:
# Try to insert a new field into the struct at the given offset
field_type = Type.any_field(new_within=data.struct)
field_name = f"{data.struct.new_field_prefix}{offset:X}"
new_field = data.struct.try_add_field(
field_type, offset, field_name, size=target_size
)
if new_field is not None:
return [field_name], field_type, 0
elif possible_results:
return possible_results[0]
if (target_size is None or target_size == self.get_size_bytes()) and (
offset == 0
):
# The whole type itself is a match
return [], self, offset
return NO_MATCHING_FIELD
def get_deref_field(
self,
offset: int,
*,
target_size: Optional[int],
exact: bool = True,
) -> GetFieldResult:
"""
Similar to `.get_field()`, but treat self as a pointer and find the field in the
pointer's target. The return value has the same semantics as `.get_field()`.
If successful, the first item in the resulting `field_path` will be `0`.
This mirrors how `foo[0].bar` and `foo->bar` are equivalent in C.
"""
NO_MATCHING_FIELD: Type.GetFieldResult = (None, Type.any(), 0)
target = self.get_pointer_target()
if target is None:
return NO_MATCHING_FIELD
# Assume the pointer is to a single object, and not an array.
field_path, field_type, remaining_offset = target.get_field(
offset, target_size=target_size, exact=exact
)
if field_path is not None:
field_path.insert(0, 0)
return field_path, field_type, remaining_offset
def get_initializer_fields(
self,
) -> Optional[List[Union[int, "Type"]]]:
"""
If self is a struct or array (i.e. initialized with `{...}` syntax), then
return a list of fields suitable for creating an initializer.
Return None if an initializer cannot be made (e.g. a struct with bitfields)
Padding is represented by an int in the list, otherwise the list fields
denote the field's Type.
"""
data = self.data()
if self.is_array():
assert data.ptr_to is not None
if data.array_dim is None:
return None
return [data.ptr_to] * data.array_dim
if self.is_struct():
assert data.struct is not None
if data.struct.has_bitfields:
# TODO: Support bitfields
return None
output: List[Union[int, Type]] = []
position = 0
def add_padding(upto: int) -> None:
nonlocal position
nonlocal output
assert upto >= position
if upto > position:
output.append(upto - position)
for field in data.struct.fields:
# Overlapping fields aren't supported
if field.offset < position:
return None
add_padding(field.offset)
field_size = field.type.get_size_bytes()
# If any field has unknown size, we can't make an initializer
if field_size is None:
return None
output.append(field.type)
position = field.offset + field_size
# Unions only have an initializer for the first field
if data.struct.is_union:
break
if data.struct.size is not None and position > data.struct.size:
# This struct has a field that goes outside of the bounds of the struct
return None
add_padding(data.struct.min_size())
return output
return None
def to_decl(self, name: str, fmt: Formatter) -> str:
decl = ca.Decl(
name=name,
type=self._to_ctype(set(), fmt),
quals=[],
align=[],
storage=[],
funcspec=[],
init=None,
bitsize=None,
)
set_decl_name(decl)
ret = to_c(decl)
if fmt.coding_style.pointer_style_left:
# Keep going until the result is unmodified
while True:
replaced = (
ret.replace(" *", "* ").replace("* )", "*)").replace("* ,", "*,")
)
if replaced == ret:
break
ret = replaced
return ret
def _to_ctype(self, seen: Set["TypeData"], fmt: Formatter) -> CType:
def simple_ctype(typename: str) -> ca.TypeDecl:
return ca.TypeDecl(
type=ca.IdentifierType(names=[typename]),
declname=None,
quals=[],
align=[],
)
unk_symbol = "M2C_UNK" if fmt.valid_syntax else "?"
data = self.data()
if data in seen:
return simple_ctype(unk_symbol)
seen.add(data)
size_bits = data.size_bits or 32
sign = "s" if data.sign & TypeData.SIGNED else "u"
if data.enum is not None and data.enum.tag is not None:
assert data.kind == TypeData.K_INT
return ca.TypeDecl(
type=ca.Enum(name=data.enum.tag, values=None),
declname=None,
quals=[],
align=[],
)
if (data.kind & TypeData.K_ANYREG) == TypeData.K_ANYREG and (
data.likely_kind & (TypeData.K_INT | TypeData.K_FLOAT)
) not in (TypeData.K_INT, TypeData.K_FLOAT):
if data.size_bits is not None:
return simple_ctype(f"{unk_symbol}{size_bits}")
return simple_ctype(unk_symbol)
if (
data.kind == TypeData.K_FLOAT
or (data.likely_kind & (TypeData.K_FLOAT | TypeData.K_INT))
== TypeData.K_FLOAT
):
return simple_ctype(f"f{size_bits}")
if data.kind == TypeData.K_PTR:
target_ctype: CType
if data.ptr_to is None:
target_ctype = simple_ctype("void")
else:
target_ctype = data.ptr_to._to_ctype(seen.copy(), fmt)
# Strip parameter names from function pointers
if isinstance(target_ctype, ca.FuncDecl) and target_ctype.args:
for arg in target_ctype.args.params:
if isinstance(arg, ca.Decl):
arg.name = None
set_decl_name(arg)
return ca.PtrDecl(type=target_ctype, quals=[])
if data.kind == TypeData.K_FN:
assert data.fn_sig is not None
return_ctype = data.fn_sig.return_type._to_ctype(seen.copy(), fmt)
params: List[Union[ca.Decl, ca.ID, ca.Typename, ca.EllipsisParam]] = []
for param in data.fn_sig.params:
decl = ca.Decl(
name=param.name,
type=param.type._to_ctype(seen.copy(), fmt),
quals=[],
align=[],
storage=[],
funcspec=[],
init=None,
bitsize=None,
)
set_decl_name(decl)
params.append(decl)
if data.fn_sig.is_variadic:
params.append(ca.EllipsisParam())
return ca.FuncDecl(
type=return_ctype,
args=ca.ParamList(params),
)
if data.kind == TypeData.K_VOID:
return simple_ctype("void")
if data.kind == TypeData.K_ARRAY:
assert data.ptr_to is not None
dim: Optional[ca.Constant] = None
if data.array_dim is not None:
dim = ca.Constant(value=fmt.format_int(data.array_dim), type="")
return ca.ArrayDecl(
type=data.ptr_to._to_ctype(seen.copy(), fmt),
dim=dim,
dim_quals=[],
)
if data.kind == TypeData.K_STRUCT:
assert data.struct is not None
if data.struct.typedef_name:
return simple_ctype(data.struct.typedef_name)
# If there's no typedef or tag name, then label it as `_anonymous`
name = data.struct.tag_name or "_anonymous"
Class = ca.Union if data.struct.is_union else ca.Struct
return ca.TypeDecl(
declname=name,
type=ca.Struct(name=name, decls=None),
quals=[],
align=[],
)
return simple_ctype(f"{sign}{size_bits}")
def format(self, fmt: Formatter) -> str:
return self.to_decl("", fmt)
def __str__(self) -> str:
return self.format(Formatter(debug=True))
def __repr__(self) -> str:
data = self.data()
signstr = ("+" if data.sign & TypeData.SIGNED else "") + (
"-" if data.sign & TypeData.UNSIGNED else ""
)
kindstr = (
("I" if data.kind & TypeData.K_INT else "")
+ ("P" if data.kind & TypeData.K_PTR else "")
+ ("F" if data.kind & TypeData.K_FLOAT else "")
+ ("N" if data.kind & TypeData.K_FN else "")
+ ("V" if data.kind & TypeData.K_VOID else "")
+ ("A" if data.kind & TypeData.K_ARRAY else "")
+ ("S" if data.kind & TypeData.K_STRUCT else "")
)
sizestr = str(data.size_bits) if data.size_bits is not None else "?"
return f"Type({signstr + kindstr + sizestr})"
@staticmethod
def any() -> "Type":
return Type(TypeData())
@staticmethod
def any_reg() -> "Type":
return Type(TypeData(kind=TypeData.K_ANYREG))
@staticmethod
def any_field(*, new_within: "Optional[StructDeclaration]" = None) -> "Type":
return Type(
TypeData(
kind=TypeData.K_ANY & ~TypeData.K_VOID,
new_field_within={new_within} if new_within else set(),
)
)
@staticmethod
def intish() -> "Type":
return Type(TypeData(kind=TypeData.K_INT))
@staticmethod
def uintish() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, sign=TypeData.UNSIGNED))
@staticmethod
def sintish() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, sign=TypeData.SIGNED))
@staticmethod
def intptr() -> "Type":
return Type(TypeData(kind=TypeData.K_INTPTR))
@staticmethod
def uintptr() -> "Type":
return Type(TypeData(kind=TypeData.K_INTPTR, sign=TypeData.UNSIGNED))
@staticmethod
def sintptr() -> "Type":
return Type(TypeData(kind=TypeData.K_INTPTR, sign=TypeData.SIGNED))
@staticmethod
def ptr(type: Optional["Type"] = None) -> "Type":
return Type(TypeData(kind=TypeData.K_PTR, size_bits=32, ptr_to=type))
@staticmethod
def function(fn_sig: Optional["FunctionSignature"] = None) -> "Type":
if fn_sig is None:
fn_sig = FunctionSignature()
return Type(TypeData(kind=TypeData.K_FN, fn_sig=fn_sig))
@staticmethod
def f32() -> "Type":
return Type(TypeData(kind=TypeData.K_FLOAT, size_bits=32))
@staticmethod
def floatish() -> "Type":
return Type(TypeData(kind=TypeData.K_FLOAT))
@staticmethod
def f64() -> "Type":
return Type(TypeData(kind=TypeData.K_FLOAT, size_bits=64))
@staticmethod
def f128() -> "Type":
return Type(TypeData(kind=TypeData.K_FLOAT, size_bits=128))
@staticmethod
def s8() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=8, sign=TypeData.SIGNED))
@staticmethod
def u8() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=8, sign=TypeData.UNSIGNED))
@staticmethod
def s16() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=16, sign=TypeData.SIGNED))
@staticmethod
def u16() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=16, sign=TypeData.UNSIGNED))
@staticmethod
def s32() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=32, sign=TypeData.SIGNED))
@staticmethod
def u32() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=32, sign=TypeData.UNSIGNED))
@staticmethod
def s64() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=64, sign=TypeData.SIGNED))
@staticmethod
def u64() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=64, sign=TypeData.UNSIGNED))
@staticmethod
def int64() -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=64))
@staticmethod
def int_of_size(size_bits: int) -> "Type":
return Type(TypeData(kind=TypeData.K_INT, size_bits=size_bits))
@staticmethod
def reg32(*, likely_float: bool) -> "Type":
likely = TypeData.K_FLOAT if likely_float else TypeData.K_INTPTR
return Type(TypeData(kind=TypeData.K_ANYREG, likely_kind=likely, size_bits=32))
@staticmethod
def reg64(*, likely_float: bool) -> "Type":
kind = TypeData.K_FLOAT | TypeData.K_INT
likely = TypeData.K_FLOAT if likely_float else TypeData.K_INT
return Type(TypeData(kind=kind, likely_kind=likely, size_bits=64))
@staticmethod
def bool() -> "Type":
return Type.intish()
@staticmethod
def void() -> "Type":
return Type(TypeData(kind=TypeData.K_VOID, size_bits=0))
@staticmethod
def array(type: "Type", dim: Optional[int]) -> "Type":
# Array elements must have a known size
el_size = type.get_size_bits()
assert el_size is not None
size_bits = None if dim is None else (el_size * dim)
return Type(
TypeData(
kind=TypeData.K_ARRAY, size_bits=size_bits, ptr_to=type, array_dim=dim
)
)
@staticmethod
def struct(st: "StructDeclaration") -> "Type":
size_bits = st.size * 8 if st.size is not None else None
return Type(TypeData(kind=TypeData.K_STRUCT, size_bits=size_bits, struct=st))
@staticmethod
def ctype(ctype: CType, typemap: TypeMap, typepool: TypePool) -> "Type":
real_ctype = resolve_typedefs(ctype, typemap)
if typepool.unk_inference and is_unk_type(ctype, typemap):
type = Type.any()
if isinstance(real_ctype, ca.TypeDecl) and isinstance(
real_ctype.type, ca.IdentifierType
):
size_bits = primitive_size(real_ctype.type) * 8
if size_bits < 32:
# This preserves the size of UNK_TYPE1, UNK_TYPE2
type = Type.int_of_size(size_bits)
if isinstance(ctype, ca.TypeDecl) and ctype.declname:
if ctype.declname in typepool.unknown_decls:
return typepool.unknown_decls[ctype.declname]
typepool.unknown_decls[ctype.declname] = type
return type
if isinstance(real_ctype, ca.ArrayDecl):
dim = None
try:
if real_ctype.dim is not None:
dim = parse_constant_int(real_ctype.dim, typemap)
except DecompFailure:
pass
inner_type = Type.ctype(real_ctype.type, typemap, typepool)
return Type.array(inner_type, dim)
if isinstance(real_ctype, ca.PtrDecl):
return Type.ptr(Type.ctype(real_ctype.type, typemap, typepool))
if isinstance(real_ctype, ca.FuncDecl):
fn = parse_function(real_ctype)
assert fn is not None
fn_sig = FunctionSignature(
return_type=Type.void(),
is_variadic=fn.is_variadic,
)
if fn.ret_type is not None:
fn_sig.return_type = Type.ctype(fn.ret_type, typemap, typepool)
if fn.params is not None:
fn_sig.params = [
FunctionParam(
name=param.name or "",
type=Type.ctype(param.type, typemap, typepool),
)
for param in fn.params
]
fn_sig.params_known = True
return Type.function(fn_sig)
if isinstance(real_ctype, ca.TypeDecl):
if isinstance(real_ctype.type, (ca.Struct, ca.Union)):
return Type.struct(
StructDeclaration.from_ctype(real_ctype.type, typemap, typepool)
)
if isinstance(real_ctype.type, ca.Enum):
enum = None
if real_ctype.type.name is not None:
enum = typemap.enums.get(real_ctype.type.name)
if enum is None:
enum = typemap.enums.get(real_ctype.type)
return Type(
TypeData(
kind=TypeData.K_INT,
size_bits=32,
sign=TypeData.SIGNED,
enum=enum,
)