Debian Codegraph @

bindings/const_generator.py

raw symbols SCIP
1 # Capstone Disassembler Engine
2 # By Dang Hoang Vu, 2013
3 from __future__ import print_function
4 import sys, re
5
6 INCL_DIR = '../include/capstone/'
7
8 include = [ 'arm.h', 'arm64.h', 'm68k.h', 'mips.h', 'x86.h', 'ppc.h', 'sparc.h', 'systemz.h', 'xcore.h', 'tms320c64x.h', 'm680x.h', 'evm.h', 'mos65xx.h', 'wasm.h', 'bpf.h' ,'riscv.h', 'sh.h', 'tricore.h' ]
9
10 template = {
11 'java': {
12 'header': "// For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT\npackage capstone;\n\npublic class %s_const {\n",
13 'footer': "}",
14 'line_format': '\tpublic static final int %s = %s;\n',
15 'out_file': './java/capstone/%s_const.java',
16 # prefixes for constant filenames of all archs - case sensitive
17 'arm.h': 'Arm',
18 'arm64.h': 'Arm64',
19 'm68k.h': 'M68k',
20 'mips.h': 'Mips',
21 'x86.h': 'X86',
22 'ppc.h': 'Ppc',
23 'sparc.h': 'Sparc',
24 'systemz.h': 'Sysz',
25 'xcore.h': 'Xcore',
26 'tms320c64x.h': 'TMS320C64x',
27 'm680x.h': 'M680x',
28 'evm.h': 'Evm',
29 'wasm.h': 'Wasm',
30 'comment_open': '\t//',
31 'comment_close': '',
32 },
33 'python': {
34 'header': "from . import CS_OP_INVALID, CS_OP_REG, CS_OP_IMM, CS_OP_MEM\n"
35 "# For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT [%s_const.py]\n",
36 'footer': "",
37 'line_format': '%s = %s\n',
38 'out_file': './python/capstone/%s_const.py',
39 # prefixes for constant filenames of all archs - case sensitive
40 'arm.h': 'arm',
41 'arm64.h': 'arm64',
42 'm68k.h': 'm68k',
43 'mips.h': 'mips',
44 'x86.h': 'x86',
45 'ppc.h': 'ppc',
46 'sparc.h': 'sparc',
47 'systemz.h': 'sysz',
48 'xcore.h': 'xcore',
49 'tms320c64x.h': 'tms320c64x',
50 'm680x.h': 'm680x',
51 'evm.h': 'evm',
52 'wasm.h': 'wasm',
53 'mos65xx.h': 'mos65xx',
54 'bpf.h': 'bpf',
55 'riscv.h': 'riscv',
56 'sh.h': 'sh',
57 'tricore.h': ['TRICORE', 'TriCore'],
58 'comment_open': '#',
59 'comment_close': '',
60 },
61 'ocaml': {
62 'header': "(* For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT [%s_const.ml] *)\n",
63 'footer': "",
64 'line_format': 'let _%s = %s;;\n',
65 'out_file': './ocaml/%s_const.ml',
66 # prefixes for constant filenames of all archs - case sensitive
67 'arm.h': 'arm',
68 'arm64.h': 'arm64',
69 'mips.h': 'mips',
70 'm68k.h': 'm68k',
71 'x86.h': 'x86',
72 'ppc.h': 'ppc',
73 'sparc.h': 'sparc',
74 'systemz.h': 'sysz',
75 'xcore.h': 'xcore',
76 'tms320c64x.h': 'tms320c64x',
77 'm680x.h': 'm680x',
78 'evm.h': 'evm',
79 'wasm.h': 'wasm',
80 'comment_open': '(*',
81 'comment_close': ' *)',
82 },
83 # 'swift': {
84 # 'header': "// For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT (%s)\n\n",
85 # 'footer': "",
86 # 'enum_doc': '/// %s\n',
87 # 'enum_header': 'public enum %s: %s {\n',
88 # 'enum_default_type': 'UInt32',
89 # 'enum_types': {
90 # 'UInt16': r'^\w+Reg$',
91 # 'UInt8': r'^\w+Grp$'
92 # },
93 # 'option_set_header': 'public struct %s: OptionSet {\n public typealias RawValue = %s\n public let rawValue: RawValue\n public init(rawValue: RawValue) { self.rawValue = rawValue }\n',
94 # 'option_sets': {
95 # 'X86Eflags': 'UInt64',
96 # 'X86FpuFlags': 'UInt64',
97 # 'SparcHint': 'UInt32',
98 # 'M680xIdx': 'UInt8',
99 # 'M680xOpFlags': 'UInt8',
100 # },
101 # 'rename': {
102 # r'^M680X_(\w+_OP_IN_MNEM)$': r'M680X_OP_FLAGS_\1',
103 # },
104 # 'option_format': ' public static let {option} = {type}(rawValue: {value})\n',
105 # 'enum_extra_options': {
106 # # swift enum != OptionSet, so options must be specified
107 # 'ArmSysreg': {
108 # 'spsrCx': 'spsrC + spsrX',
109 # 'spsrCs': 'spsrC + spsrS',
110 # 'spsrXs': 'spsrX + spsrS',
111 # 'spsrCxs': 'spsrC + spsrX + spsrS',
112 # 'spsrCf': 'spsrC + spsrF',
113 # 'spsrXf': 'spsrX + spsrF',
114 # 'spsrCxf': 'spsrC + spsrX + spsrF',
115 # 'spsrSf': 'spsrS + spsrF',
116 # 'spsrCsf': 'spsrC + spsrS + spsrF',
117 # 'spsrXsf': 'spsrX + spsrS + spsrF',
118 # 'spsrCxsf': 'spsrC + spsrX + spsrS + spsrF',
119 # 'cpsrCx': 'cpsrC + cpsrX',
120 # 'cpsrCs': 'cpsrC + cpsrS',
121 # 'cpsrXs': 'cpsrX + cpsrS',
122 # 'cpsrCxs': 'cpsrC + cpsrX + cpsrS',
123 # 'cpsrCf': 'cpsrC + cpsrF',
124 # 'cpsrXf': 'cpsrX + cpsrF',
125 # 'cpsrCxf': 'cpsrC + cpsrX + cpsrF',
126 # 'cpsrSf': 'cpsrS + cpsrF',
127 # 'cpsrCsf': 'cpsrC + cpsrS + cpsrF',
128 # 'cpsrXsf': 'cpsrX + cpsrS + cpsrF',
129 # 'cpsrCxsf': 'cpsrC + cpsrX + cpsrS + cpsrF',
130 # }
131 # },
132 # 'enum_footer': '}\n\n',
133 # 'doc_line_format': ' /// %s\n',
134 # 'line_format': ' case %s = %s\n',
135 # 'dup_line_format': ' public static let %s = %s\n',
136 # 'out_file': './swift/Sources/Capstone/%sEnums.swift',
137 # 'reserved_words': [
138 # 'break', 'class', 'for', 'false', 'in', 'init', 'return', 'true'
139 # ],
140 # 'reserved_word_format': '`%s`',
141 # # prefixes for constant filenames of all archs - case sensitive
142 # 'arm.h': 'Arm',
143 # 'arm64.h': 'Arm64',
144 # 'm68k.h': 'M68k',
145 # 'mips.h': 'Mips',
146 # 'x86.h': 'X86',
147 # 'ppc.h': 'Ppc',
148 # 'sparc.h': 'Sparc',
149 # 'systemz.h': 'Sysz',
150 # 'xcore.h': 'Xcore',
151 # 'tms320c64x.h': 'TMS320C64x',
152 # 'm680x.h': 'M680x',
153 # 'evm.h': 'Evm',
154 # 'mos65xx.h': 'Mos65xx',
155 # 'comment_open': '\t//',
156 # 'comment_close': '',
157 # },
158 }
159
160 # markup for comments to be added to autogen files
161 MARKUP = '//>'
162
163 def camelize(name):
164 parts = name.split('_')
165 return parts[0].lower() + ''.join(map(str.capitalize, parts[1:]))
166
167 def pascalize(name):
168 parts = name.split('_')
169 return ''.join(map(str.capitalize, parts))
170
171 def pascalize_const(name):
172 parts = name.split('_',2)
173 match = re.match('^(CC|DISP|MOD|DIR|BCAST|RM|FLAGS|SIZE|BR_DISP_SIZE)_', parts[2])
174 if match:
175 parts = name.split('_', 2 + match.group(0).count('_'))
176 item = camelize(parts[-1])
177 if item[0].isdigit():
178 item = parts[-2].lower() + item
179 return (pascalize('_'.join(parts[0:-1])), item)
180
181 def enum_type(name, templ):
182 for enum_type, pattern in templ['enum_types'].items():
183 if re.match(pattern, name):
184 return enum_type
185 return templ['enum_default_type']
186
187 def write_enum_extra_options(outfile, templ, enum, enum_values):
188 if 'enum_extra_options' in templ and enum in templ['enum_extra_options']:
189 for name, value in templ['enum_extra_options'][enum].items():
190 if type(value) is str:
191 # evaluate within existing enum
192 value = eval(value, None, enum_values)
193 outfile.write((templ['line_format'] %(name, value)).encode("utf-8"))
194
195 def gen(lang):
196 global include, INCL_DIR
197 print('Generating bindings for', lang)
198 templ = template[lang]
199 print('Generating bindings for', lang)
200 for target in include:
201 if target not in templ:
202 print("Warning: No binding found for %s" % target)
203 continue
204 prefix = templ[target]
205 prefixs = []
206 if isinstance(prefix, list):
207 prefixs = prefix
208 prefix = prefix[0].lower()
209
210 outfile = open(templ['out_file'] %(prefix), 'wb') # open as binary prevents windows newlines
211 outfile.write((templ['header'] % (prefix)).encode("utf-8"))
212
213 lines = open(INCL_DIR + target).readlines()
214 enums = {}
215 values = {}
216 doc_lines = []
217
218 count = 0
219 for line in lines:
220 line = line.strip()
221
222 if line.startswith(MARKUP): # markup for comments
223 outfile.write(("\n%s%s%s\n" %(templ['comment_open'], \
224 line.replace(MARKUP, ''), \
225 templ['comment_close']) ).encode("utf-8"))
226 continue
227
228 if line.startswith('/// ') and 'enum_doc' in templ:
229 doc_lines.append(line[4: ])
230 continue
231 elif line.startswith('}') or line.startswith('#'):
232 doc_lines = []
233 pass
234
235 if line == '' or line.startswith('//'):
236 continue
237
238 if line.startswith('#define '):
239 line = line[8:] #cut off define
240 xline = re.split(r'\s+', line, 1) #split to at most 2 express
241 if len(xline) != 2:
242 continue
243 if '(' in xline[0] or ')' in xline[0]: #does it look like a function
244 continue
245 xline.insert(1, '=') # insert an = so the expression below can parse it
246 line = ' '.join(xline)
247
248 def is_with_prefix(x):
249 if prefixs:
250 return any(x.startswith(pre) for pre in prefixs)
251 else:
252 return x.startswith(prefix.upper())
253
254 if not is_with_prefix(line):
255 continue
256
257 tmp = line.strip().split(',')
258 for t in tmp:
259 t = t.strip()
260 if not t or t.startswith('//'): continue
261 # hacky: remove type cast (uint64_t)
262 t = t.replace('(uint64_t)', '')
263 t = re.sub(r'\((\d+)ULL << (\d+)\)', r'\1 << \2', t) # (1ULL<<1) to 1 << 1
264 f = re.split(r'\s+', t)
265
266 if not is_with_prefix(f[0]):
267 continue
268
269 if len(f) > 1 and f[1] not in ('//', '///<', '='):
270 print("Error: Unable to convert %s" % f)
271 continue
272 elif len(f) > 1 and f[1] == '=':
273 rhs = ''.join(f[2:])
274 else:
275 rhs = str(count)
276 count += 1
277
278 try:
279 count = int(rhs) + 1
280 if (count == 1):
281 outfile.write(("\n").encode("utf-8"))
282 except ValueError:
283 if lang == 'ocaml':
284 # ocaml uses lsl for '<<', lor for '|'
285 rhs = rhs.replace('<<', ' lsl ')
286 rhs = rhs.replace('|', ' lor ')
287 # ocaml variable has _ as prefix
288 if rhs[0].isalpha():
289 rhs = '_' + rhs
290
291 if lang == 'swift':
292 value = eval(rhs, None, values)
293 exec('%s = %d' %(f[0].strip(), value), None, values)
294 else:
295 value = rhs
296
297 name = f[0].strip()
298
299 if 'rename' in templ:
300 # constant renaming
301 for pattern, replacement in templ['rename'].items():
302 if re.match(pattern, name):
303 name = re.sub(pattern, replacement, name)
304 break
305
306
307 if 'enum_header' in templ:
308 # separate constants by enums based on name
309 enum, name = pascalize_const(name)
310 if enum not in enums:
311 if len(enums) > 0:
312 write_enum_extra_options(outfile, templ, last_enum, enums[last_enum])
313 outfile.write((templ['enum_footer']).encode("utf-8"))
314 last_enum = enum
315
316 if 'enum_doc' in templ:
317 for doc_line in doc_lines:
318 outfile.write((templ['enum_doc'] %(doc_line)).encode("utf-8"))
319 doc_lines = []
320
321 if 'option_sets' in templ and enum in templ['option_sets']:
322 outfile.write((templ['option_set_header'] %(enum, templ['option_sets'][enum])).encode("utf-8"))
323 else:
324 outfile.write((templ['enum_header'] %(enum, enum_type(enum, templ))).encode("utf-8"))
325 enums[enum] = {}
326
327 if 'option_sets' in templ and enum in templ['option_sets']:
328 # option set format
329 line_format = templ['option_format'].format(option='%s',type=enum,value='%s')
330 if value == 0:
331 continue # skip empty option
332 # option set values need not be literals
333 value = rhs
334 elif 'dup_line_format' in templ and value in enums[enum].values():
335 # different format for duplicate values?
336 line_format = templ['dup_line_format']
337 else:
338 line_format = templ['line_format']
339 enums[enum][name] = value
340
341 # escape reserved words
342 if 'reserved_words' in templ and name in templ['reserved_words']:
343 name = templ['reserved_word_format'] %(name)
344
345 # print documentation?
346 if 'doc_line_format' in templ and '///<' in line:
347 doc = line.split('///<')[1].strip()
348 outfile.write((templ['doc_line_format'] %(doc)).encode("utf-8"))
349 else:
350 line_format = templ['line_format']
351
352 outfile.write((line_format %(name, value)).encode("utf-8"))
353
354 if 'enum_footer' in templ:
355 write_enum_extra_options(outfile, templ, enum, enums[enum])
356 outfile.write((templ['enum_footer']).encode("utf-8"))
357 outfile.write((templ['footer']).encode("utf-8"))
358 outfile.close()
359
360 def main():
361 try:
362 if sys.argv[1] == 'all':
363 for key in template.keys():
364 gen(key)
365 else:
366 gen(sys.argv[1])
367 except:
368 raise RuntimeError("Unsupported binding %s" % sys.argv[1])
369
370 if __name__ == "__main__":
371 if len(sys.argv) < 2:
372 print("Usage:", sys.argv[0], " <bindings: java|python|ocaml|all>")
373 sys.exit(1)
374 main()