-
Notifications
You must be signed in to change notification settings - Fork 4
/
gen.py
executable file
·257 lines (201 loc) · 7.2 KB
/
gen.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
#!/usr/bin/env python
import os
import sys
from clang.cindex import CursorKind, Index
# This is here needed for windows to be able to find "libclang.dll"
if sys.platform == "win32":
for path in os.environ['PATH'].split(';'):
if os.path.exists(path):
os.add_dll_directory(path)
def underscoreify(s):
"""Turns a string like "FooBarBaz" into "foo_bar_baz"."""
res = ""
# Avoid turning CPU into c_p_u
last_was_upper = False
for i, c in enumerate(s):
if i != 0 and c.isupper() and not last_was_upper:
res += "_"
res += c.lower()
last_was_upper = c.isupper()
return res
class Rust:
reserved_keywords = ()
bitflags = ["ZydisOperandAction_"]
def file_header(self):
print("""// AUTO-GENERATED USING zydis-bindgen!
#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};
""")
def start_enum(self, name, full_name, brief_comment):
self.closed = False
if name == "FormatterProperty":
print(
f"""/// We wrap this in a nicer rust enum `FormatterProperty` already,
/// use that instead.
#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(C)]
pub enum {full_name[:-1]} {{"""
)
self.enum_name = full_name[:-1]
else:
print(
f"/// {brief_comment}\n"
f'#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]\n'
f"#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]\n"
f"#[repr(C)]\n"
f"pub enum {name} {{"
)
self.enum_name = name
def enum_member(self, name, full_name, val, brief_comment, last):
if name == "REQUIRED_BITS":
return
elif name == "MAX_VALUE":
# Work around that we can't use negative values in unsigned constants.
if self.enum_name == "Padding":
return
self.closed = True
print(f"}}\n\npub const {full_name[6:]}: usize = {val};\n")
return
if brief_comment is not None:
print(f" /// {brief_comment}\n {name} = {val},")
else:
print(f" {name} = {val},")
def end_enum(self):
if not self.closed:
print("}\n")
class Py:
reserved_keywords = ("IF",)
bitflags = []
def file_header(self):
print(
"# THIS FILE IS AUTO-GENERATED USING zydis-bindgen!\n"
"# distutils: include_dirs=ZYDIS_INCLUDES\n\n"
"from enum import IntEnum\n"
)
def start_enum(self, name, full_name, brief_comment):
print(f'class {name}(IntEnum):\n """{brief_comment}"""')
def enum_member(self, name, full_name, val, brief_comment, last):
if name == "REQUIRED_BITS":
return
if brief_comment:
print(f" # {brief_comment}")
print(f" {name} = {val}")
def end_enum(self):
print("\n")
class Pxd:
reserved_keywords = ()
bitflags = []
def file_header(self):
print(
"# THIS FILE IS AUTO-GENERATED USING zydis-bindgen!\n\n"
'cdef extern from "Zydis/Zydis.h":'
)
def start_enum(self, name, full_name, brief_comment):
print(f" ctypedef enum {full_name[:-1]}:")
def enum_member(self, name, full_name, val, brief_comment, last):
if name == "REQUIRED_BITS":
return
print(f" {full_name}")
def end_enum(self):
print()
class CSharp:
reserved_keywords = ()
bitflags = []
def file_header(self):
print("// THIS FILE IS AUTO-GENERATED USING zydis-bindgen!\n")
def start_enum(self, name, full_name, brief_comment):
print(f'/// <summary>{brief_comment}</summary>')
print(f'public enum {name}\n{{')
def enum_member(self, name, full_name, val, brief_comment, last):
if name == "REQUIRED_BITS":
return
if brief_comment:
print(f" /// <summary>{brief_comment}</summary>")
print(f" {name} = {val},")
def end_enum(self):
print("}\n")
class Ocaml:
reserved_keywords = ()
bitflags = ["ZydisOperandAction_"]
def __init__(self):
self.current_name = None
def file_header(self):
print("(* THIS FILE IS AUTO-GENERATED USING zydis-bindgen! *)\n")
def start_enum(self, name, full_name, brief_comment):
self.current_name = name
self.i = 0
print(f"type {underscoreify(name)} =")
def enum_member(self, name, full_name, val, brief_comment, last):
if self.i == 0 and name == "NONE":
self.i += 1
return
if name == "REQUIRED_BITS" or name == "MAX_VALUE":
return
if name[0] == "_":
name = self.current_name + name[1:]
print(f" | {name}")
self.i += 1
def end_enum(self):
print()
class Pascal:
reserved_keywords = ()
bitflags = []
def file_header(self):
print("// THIS FILE IS AUTO-GENERATED USING zydis-bindgen!\n")
print("type\n")
def start_enum(self, name, full_name, brief_comment):
print(f'// {brief_comment}')
if full_name.endswith('_'):
full_name = full_name[:-1]
print(f'T{full_name} = (')
def enum_member(self, name, full_name, val, brief_comment, last):
if brief_comment:
print(f" // {brief_comment}")
if last:
print(f" {full_name} = {val}")
else:
print(f" {full_name} = {val},")
def end_enum(self):
print(");\n")
MODES = {
"rust": Rust(),
"py": Py(),
"pxd": Pxd(),
"csharp": CSharp(),
"ocaml": Ocaml(),
"pascal": Pascal(),
}
if __name__ == "__main__":
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} <zydis path> <{'|'.join(MODES)}>", file=sys.stderr)
exit(1)
zydis_path = sys.argv[1]
mode = MODES[sys.argv[2]]
tu = Index.create().parse(
f"{zydis_path}/include/Zydis/Zydis.h",
args=[
"-DZYAN_NO_LIBC=1",
"-I./include",
f"-I{zydis_path}/include/",
f"-I{zydis_path}",
f"-I{zydis_path}/dependencies/zycore/include",
],
)
for error in tu.diagnostics:
print(f"Err: {error!s}", file=sys.stderr)
mode.file_header()
for c in tu.cursor.get_children():
if c.kind == CursorKind.ENUM_DECL and c.displayname[:5] == "Zydis" and c.displayname not in mode.bitflags:
mode.start_enum(c.displayname[5:-1], c.displayname, c.brief_comment)
*children, = [x.displayname for x in c.get_children()]
skip_prefix = len(os.path.commonprefix(children))
max = sum(1 for _ in c.get_children())
enum_members = list(c.get_children())
max = len(enum_members)
for index, x in enumerate(enum_members):
name = x.displayname[skip_prefix:]
if name[0].isdigit() or name in mode.reserved_keywords:
name = "_" + name
mode.enum_member(name, x.displayname, x.enum_value, x.brief_comment, index == max - 1)
mode.end_enum()