elsagranger commited on
Commit
077a99a
·
1 Parent(s): 827e9ed

Add force execution and introduction

Browse files
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ playground.py
README.md CHANGED
@@ -1,6 +1,14 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
4
 
5
  ## Usage
6
 
 
1
+ # Virtual Compiler Is All You Need For Assembly Code Search
2
+
3
+ ## Introduction
4
+
5
+ This repo contains the models and the corresponding evaluation datasets of ACL 2024 paper "Virtual Compiler Is All You Need For Assembly Code Search".
6
+
7
+ A virtual compiler is a LLM that is capable of compiling any programming language into underlying assembly code. The virtual compiler model is available at [elsagranger/VirtualCompiler](https://huggingface.co/elsagranger/VirtualCompiler), based on 34B CodeLlama.
8
+
9
+ We evaluate the similiarity of the virtual assembly code generated by the virtual compiler and the real assembly code using force execution by script [force-exec.py](./force_exec.py), the corresponding evaluation dataset is avaiable at [virtual_assembly_and_ground_truth](./virtual_assembly_and_ground_truth).
10
+
11
+ We evaluate the effective of the virtual compiler throught downstream task -- assembly code search, the evaluation dataset is avaiable at [elsagranger/AssemblyCodeSearch](https://huggingface.co/datasets/elsagranger/AssemblyCodeSearch).
12
 
13
  ## Usage
14
 
force_exec.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ from capstone import *
3
+ import json
4
+ from tqdm import tqdm
5
+ import random
6
+ from multiprocessing import Process, Queue
7
+ from unicorn.x86_const import *
8
+ from unicorn import *
9
+ from datasets import concatenate_datasets
10
+ from keystone import *
11
+ import re
12
+ from datasets import load_from_disk
13
+
14
+
15
+ def test_single(code):
16
+ ks = Ks(KS_ARCH_X86, KS_MODE_64)
17
+ try:
18
+ count = ks.asm(code)
19
+ except:
20
+ count = 0
21
+ return count
22
+
23
+
24
+ def convert_hex_format(assembly):
25
+ hex_pattern = re.compile(r'\b([0-9A-Fa-f]+)h')
26
+ converted_assembly = hex_pattern.sub(r'0x\1', assembly)
27
+ return converted_assembly
28
+
29
+
30
+ def get_name_value(name):
31
+
32
+ # match "VAR_num" label
33
+ if name.startswith("var_"):
34
+ match = re.match(r"var_(\d+)", name)
35
+ if match:
36
+ # get number
37
+ return int(match.group(1))
38
+ # else case
39
+ return None
40
+
41
+
42
+ class KeypatchAsm:
43
+ def __init__(self, arch=KS_ARCH_X86, mode=KS_MODE_64):
44
+ self.arch = arch
45
+ self.mode = mode
46
+ self.ks = Ks(self.arch, self.mode)
47
+
48
+ def fix_cmp_instruction_size(self, assembly):
49
+ lines = assembly.split('\n')
50
+ updated_lines = []
51
+ for line in lines:
52
+ if 'cmp' in line and '[' in line and ']' in line:
53
+ # add default size indicator 'dword ptr'
54
+ if ' ptr ' not in line:
55
+ line = line.replace('cmp', 'cmp dword ptr', 1)
56
+ elif 'cmp' in line and ':' in line:
57
+ line = 'nop'
58
+ updated_lines.append(line)
59
+ return '\n'.join(updated_lines)
60
+
61
+ def replace_calls_and_leas(self, assembly):
62
+ lines = assembly.split('\n')
63
+ update_lines = []
64
+ for line in lines:
65
+ if ('call' in line) and not any(x in line for x in ['0x', '0X']):
66
+ update_lines.append('nop')
67
+ elif ('lea' in line):
68
+ update_lines.append('nop')
69
+ else:
70
+ update_lines.append(line)
71
+ # print(line)
72
+ return '\n'.join(update_lines)
73
+
74
+ def remove_comments(self, assembly):
75
+ # remove ';'
76
+ lines = assembly.split('\n')
77
+ cleaned_lines = [line.split(';', 1)[0] for line in lines]
78
+ return '\n'.join(cleaned_lines).strip()
79
+
80
+ def replace_segment_register_references(self, assembly):
81
+ lines = assembly.split('\n')
82
+ updated_lines = []
83
+ for line in lines:
84
+ if 'cs:' in line:
85
+ updated_lines.append('nop')
86
+ else:
87
+ if test_single(line) == 0 and "INSTR" not in line:
88
+ updated_lines.append('nop')
89
+ else:
90
+ updated_lines.append(line)
91
+ return '\n'.join(updated_lines)
92
+
93
+ def ida_resolve(self, assembly, address):
94
+ def _resolve(_op, ignore_kw=True):
95
+ names = re.findall(r"[\$a-z0-9_:\.]+", _op, re.I)
96
+
97
+ for name in names:
98
+ # ingnore known key words
99
+ if ignore_kw and name in ('byte', 'near', 'short', 'word', 'dword', 'ptr', 'offset'):
100
+ continue
101
+
102
+ # use get_name_value fucntion
103
+ value = get_name_value(name)
104
+ if value is not None:
105
+ _op = _op.replace(name, '0x'+str(value))
106
+
107
+ return _op
108
+
109
+ # split the part and anylaize each oprand
110
+ _asm = assembly.partition(' ')
111
+ mnem = _asm[0]
112
+ opers = _asm[2].split(',')
113
+
114
+ for idx, op in enumerate(opers):
115
+ _op = list(op.partition('['))
116
+ ignore_kw = True
117
+ if _op[1] == '':
118
+ _op[2] = _op[0]
119
+ _op[0] = ''
120
+ else:
121
+ _op[0] = _resolve(_op[0], ignore_kw=True)
122
+ ignore_kw = False
123
+
124
+ _op[2] = _resolve(_op[2], ignore_kw=ignore_kw)
125
+ opers[idx] = ''.join(_op)
126
+
127
+ asm = "{0} {1}".format(mnem, ','.join(opers))
128
+ return asm
129
+
130
+ def assemble(self, assembly, address=0, syntax=KS_OPT_SYNTAX_INTEL):
131
+ assembly = assembly.replace("endbr64\n", "")
132
+ assembly = self.remove_comments(assembly)
133
+ assembly = self.ida_resolve(assembly, address)
134
+ assembly = self.replace_calls_and_leas(assembly)
135
+ assembly = self.fix_cmp_instruction_size(assembly)
136
+ assembly = self.replace_segment_register_references(assembly)
137
+
138
+ def fix_ida_syntax(assembly):
139
+ assembly = convert_hex_format(assembly)
140
+ assembly = assembly.upper()
141
+
142
+ assembly = assembly.replace("0X", " 0x")
143
+
144
+ if self.arch == KS_ARCH_X86:
145
+ if 'RETN' in assembly:
146
+ return assembly.replace('RETN', 'RET', 1)
147
+ if 'OFFSET ' in assembly:
148
+ return assembly.replace('OFFSET ', ' ')
149
+ return assembly
150
+
151
+ if syntax is None:
152
+ syntax = KS_OPT_SYNTAX_INTEL
153
+
154
+ # print(fix_ida_syntax(assembly))
155
+ try:
156
+ self.ks.syntax = syntax
157
+ encoding, count = self.ks.asm(fix_ida_syntax(assembly), address)
158
+ except KsError as e:
159
+ print(f"Error:{e}")
160
+ print(f"Assembly:\n{fix_ida_syntax(assembly)}")
161
+ print("-"*50)
162
+ print("")
163
+ encoding, count = None, 0
164
+
165
+ return (encoding, count)
166
+
167
+
168
+ UC_X86_REG_MAPPING = {
169
+ UC_X86_REG_RAX: "RAX", UC_X86_REG_RBX: "RBX", UC_X86_REG_RCX: "RCX",
170
+ UC_X86_REG_RDX: "RDX", UC_X86_REG_RSI: "RSI", UC_X86_REG_RDI: "RDI",
171
+ UC_X86_REG_RBP: "RBP", UC_X86_REG_RSP: "RSP", UC_X86_REG_R8: "R8",
172
+ UC_X86_REG_R9: "R9", UC_X86_REG_R10: "R10", UC_X86_REG_R11: "R11",
173
+ UC_X86_REG_R12: "R12", UC_X86_REG_R13: "R13", UC_X86_REG_R14: "R14",
174
+ UC_X86_REG_R15: "R15", UC_X86_REG_RIP: "RIP",
175
+ # FPU register, vector register and flag register
176
+ UC_X86_REG_XMM0: "XMM0", UC_X86_REG_XMM1: "XMM1", UC_X86_REG_XMM2: "XMM2",
177
+ UC_X86_REG_XMM3: "XMM3", UC_X86_REG_XMM4: "XMM4", UC_X86_REG_XMM5: "XMM5",
178
+ UC_X86_REG_XMM6: "XMM6", UC_X86_REG_XMM7: "XMM7", UC_X86_REG_XMM8: "XMM8",
179
+ UC_X86_REG_XMM9: "XMM9", UC_X86_REG_XMM10: "XMM10", UC_X86_REG_XMM11: "XMM11",
180
+ UC_X86_REG_XMM12: "XMM12", UC_X86_REG_XMM13: "XMM13", UC_X86_REG_XMM14: "XMM14",
181
+ UC_X86_REG_XMM15: "XMM15",
182
+ # YMM register
183
+ UC_X86_REG_YMM0: "YMM0", UC_X86_REG_YMM1: "YMM1", UC_X86_REG_YMM2: "YMM2",
184
+ UC_X86_REG_YMM3: "YMM3", UC_X86_REG_YMM4: "YMM4", UC_X86_REG_YMM5: "YMM5",
185
+ UC_X86_REG_YMM6: "YMM6", UC_X86_REG_YMM7: "YMM7", UC_X86_REG_YMM8: "YMM8",
186
+ UC_X86_REG_YMM9: "YMM9", UC_X86_REG_YMM10: "YMM10", UC_X86_REG_YMM11: "YMM11",
187
+ UC_X86_REG_YMM12: "YMM12", UC_X86_REG_YMM13: "YMM13", UC_X86_REG_YMM14: "YMM14",
188
+ UC_X86_REG_YMM15: "YMM15",
189
+ # EFLAGS register segment register
190
+ UC_X86_REG_EFLAGS: "EFLAGS",
191
+ UC_X86_REG_CS: "CS",
192
+ UC_X86_REG_DS: "DS",
193
+ UC_X86_REG_ES: "ES",
194
+ UC_X86_REG_FS: "FS",
195
+ UC_X86_REG_GS: "GS",
196
+ UC_X86_REG_SS: "SS"
197
+ }
198
+
199
+
200
+ class MemoryAccessLogger:
201
+ def __init__(self):
202
+ self.read_accesses = []
203
+ self.write_accesses = []
204
+
205
+ def hook_mem_read(self, uc, access, address, size, value, user_data):
206
+ self.read_accesses.append((address, size, value))
207
+
208
+ def hook_mem_write(self, uc, access, address, size, value, user_data):
209
+ self.write_accesses.append((address, size, value))
210
+
211
+
212
+ def hook_mem_invalid(uc, access, address, size, value, user_data):
213
+ if access == UC_MEM_WRITE_UNMAPPED or access == UC_MEM_READ_UNMAPPED or access == UC_MEM_FETCH_UNMAPPED:
214
+ print(">>> Missing memory is being WRITE at 0x%x, data size = %u, data value = 0x%x"
215
+ % (address, size, value))
216
+ start_map_addr = address & 0xfffffffffffff000
217
+
218
+ uc.mem_map(start_map_addr, start_map_addr+0x1000)
219
+ return True
220
+ return True
221
+
222
+
223
+ def instruction_hook(uc, address, size, user_data):
224
+ # get the current instruction
225
+ code = uc.mem_read(address, size)
226
+
227
+ rbp = uc.reg_read(UC_X86_REG_RBP)
228
+ rsp = uc.reg_read(UC_X86_REG_RSP)
229
+ # print(f"RBP: 0x{rbp:016x}, RSP: 0x{rsp:016x}")
230
+ # for i in md.disasm(code, address):
231
+ # print("0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))
232
+
233
+
234
+ def assemble_wrapper(asm_code, code_address, result_queue):
235
+ """
236
+ execute the function in new process and catch any exception to avoid crash the main process
237
+ """
238
+ try:
239
+ keypatch_asm = KeypatchAsm()
240
+ encoding, count = keypatch_asm.assemble(asm_code, code_address)
241
+ result_queue.put((encoding, count))
242
+ except Exception as e:
243
+ result_queue.put((None, 0))
244
+ print("Error during assembly:", str(e))
245
+
246
+
247
+ def safe_assemble(asm_code, code_address, timeout=3):
248
+ result_queue = Queue()
249
+ p = Process(target=assemble_wrapper, args=(
250
+ asm_code, code_address, result_queue))
251
+ p.start()
252
+ p.join(timeout)
253
+
254
+ if p.is_alive():
255
+ p.terminate()
256
+ print("Terminated the process due to timeout.")
257
+ return None, 0
258
+
259
+ try:
260
+ result = result_queue.get_nowait()
261
+ return result
262
+ except Exception:
263
+ return None, 0
264
+
265
+
266
+ md = Cs(CS_ARCH_X86, CS_MODE_64)
267
+
268
+
269
+ def compile_run(asm_code, code_address, seed=0):
270
+ try:
271
+ random.seed(seed)
272
+ encoding, count = safe_assemble(asm_code, code_address)
273
+ if encoding is None or count == 0:
274
+ return "ERROR", [], []
275
+ CODE_SIZE = (count+0x1000) // 0x1000 * 0x1000
276
+ CODE_ADDRESS = code_address
277
+ STACK_ADDRESS = 0x7fff0000
278
+ STACK_SIZE = 0x2000
279
+ mu = Uc(UC_ARCH_X86, UC_MODE_64)
280
+ mu.mem_map(CODE_ADDRESS, CODE_ADDRESS+CODE_SIZE)
281
+ mu.mem_map(STACK_ADDRESS, STACK_ADDRESS+STACK_SIZE)
282
+ mu.mem_write(CODE_ADDRESS, bytes(encoding))
283
+
284
+ mu.reg_write(UC_X86_REG_RAX, random.randint(0, 0x2000))
285
+ mu.reg_write(UC_X86_REG_RBX, random.randint(0, 0x2000))
286
+ mu.reg_write(UC_X86_REG_RCX, random.randint(0, 0x2000))
287
+ mu.reg_write(UC_X86_REG_RDX, random.randint(0, 0x2000))
288
+ mu.reg_write(UC_X86_REG_RSI, random.randint(0, 0x2000))
289
+ mu.reg_write(UC_X86_REG_RDI, random.randint(0, 0x2000))
290
+ mu.reg_write(UC_X86_REG_R8, random.randint(0, 0x2000))
291
+ mu.reg_write(UC_X86_REG_R9, random.randint(0, 0x2000))
292
+ mu.reg_write(UC_X86_REG_R10, random.randint(0, 0x2000))
293
+ mu.reg_write(UC_X86_REG_R11, random.randint(0, 0x2000))
294
+ mu.reg_write(UC_X86_REG_R12, random.randint(0, 0x2000))
295
+
296
+ mu.reg_write(UC_X86_REG_RSP, STACK_ADDRESS + STACK_SIZE)
297
+ mu.reg_write(UC_X86_REG_RBP, STACK_ADDRESS + STACK_SIZE)
298
+
299
+ mu.hook_add(UC_HOOK_MEM_INVALID |
300
+ UC_HOOK_MEM_UNMAPPED, hook_mem_invalid)
301
+ memory_logger = MemoryAccessLogger()
302
+ mu.hook_add(UC_HOOK_MEM_READ, memory_logger.hook_mem_read)
303
+ mu.hook_add(UC_HOOK_MEM_WRITE, memory_logger.hook_mem_write)
304
+
305
+ mu.emu_start(CODE_ADDRESS, CODE_ADDRESS +
306
+ len(bytes(encoding)), timeout=0, count=1000)
307
+ registers = {}
308
+ for reg_id, reg_name in UC_X86_REG_MAPPING.items():
309
+ registers[reg_name] = mu.reg_read(reg_id)
310
+ return registers, memory_logger.read_accesses, memory_logger.write_accesses
311
+ except Exception as e:
312
+ return "ERROR", [], []
313
+
314
+ # %%
315
+
316
+
317
+ ds = load_from_disk("./virtual_assembly_and_ground_truth")
318
+
319
+ # %%
320
+
321
+ all_results = {
322
+ 'ground_truth': [],
323
+ 'generated': []
324
+ }
325
+ test_index = []
326
+ cnt = 0
327
+ for idx, code in tqdm(enumerate(ds['asm'])):
328
+ print(idx, cnt)
329
+ regs, read_mem, write_mem = compile_run(code, 0x1000, cnt)
330
+ if regs == "ERROR":
331
+ pass
332
+ else:
333
+ test_index.append(idx)
334
+ all_results['ground_truth'].append(
335
+ {
336
+ 'regs': regs,
337
+ 'read_mem': read_mem,
338
+ 'write_mem': write_mem
339
+ }
340
+ )
341
+ cnt += 1
342
+
343
+ for seed, index in tqdm(enumerate(test_index)):
344
+ code = ds[index]['generated_asm']
345
+ regs, read_mem, write_mem = compile_run(code, 0x1000, seed)
346
+ if regs != "ERROR":
347
+ all_results['generated'].append(
348
+ {
349
+ 'regs': regs,
350
+ 'read_mem': read_mem,
351
+ 'write_mem': write_mem
352
+ }
353
+ )
354
+ else:
355
+ all_results['generated'].append(None)
356
+
357
+
358
+ evaluation_results = {
359
+ 'regs': [],
360
+ 'read_mem': [],
361
+ 'write_mem': [],
362
+ }
363
+
364
+ for overall_index in tqdm(range(len(test_index))):
365
+ ground_truth = all_results['ground_truth'][overall_index]
366
+ compare = all_results['generated'][overall_index]
367
+
368
+ if compare is None:
369
+ continue
370
+
371
+ # compare regs
372
+ if len(compare['regs']) == 0:
373
+ continue
374
+
375
+ reg_name_list = [
376
+ 'RAX', 'RSP', 'RBP'
377
+ ]
378
+ count = 0
379
+ for reg_name in reg_name_list:
380
+ if ground_truth['regs'][reg_name] == compare['regs'][reg_name]:
381
+ count += 1
382
+ evaluation_results['regs'].append(
383
+ float(count) / len(reg_name_list))
384
+
385
+ # compare read_mem
386
+ if len(ground_truth['read_mem']) != 0:
387
+ if len(compare['read_mem']) == 0:
388
+ evaluation_results['read_mem'].append(0)
389
+ # calculate the matching score of read_mem
390
+ else:
391
+ matching_score = 0
392
+ for address, size, value in compare['read_mem']:
393
+ if (address, size, value) in ground_truth['read_mem']:
394
+ matching_score += 1
395
+ evaluation_results['read_mem'].append(
396
+ float(matching_score) / len(ground_truth['read_mem']))
397
+
398
+ # compare write_mem
399
+ if len(ground_truth['write_mem']) != 0:
400
+ if len(compare['write_mem']) == 0:
401
+ evaluation_results['write_mem'].append(0)
402
+ # calculate the matching score of write_mem
403
+ else:
404
+ matching_score = 0
405
+ for address, size, value in compare['write_mem']:
406
+ if (address, size, value) in ground_truth['write_mem']:
407
+ matching_score += 1
408
+ evaluation_results['write_mem'].append(
409
+ matching_score / len(ground_truth['write_mem']))
410
+
411
+ # %%
412
+
413
+ reg_score = sum(evaluation_results['regs']) / len(evaluation_results['regs'])
414
+ read_score = sum(evaluation_results['read_mem']) / len(
415
+ evaluation_results['read_mem'])
416
+ write_score = sum(evaluation_results['write_mem']) / len(
417
+ evaluation_results['write_mem'])
418
+
419
+ print(f"mean_score: {(reg_score + read_score + write_score) / 3}")
virtual_assembly_and_ground_truth/data-00000-of-00001.arrow ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20b3bcb992adca822e7cee98a6baf64a708bdb1e7dcbfa33c1cc754f45f841cf
3
+ size 13165488
virtual_assembly_and_ground_truth/dataset_info.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "citation": "",
3
+ "description": "",
4
+ "features": {
5
+ "query": {
6
+ "dtype": "string",
7
+ "_type": "Value"
8
+ },
9
+ "source_code": {
10
+ "dtype": "string",
11
+ "_type": "Value"
12
+ },
13
+ "asm": {
14
+ "dtype": "string",
15
+ "_type": "Value"
16
+ },
17
+ "generated_asm": {
18
+ "dtype": "string",
19
+ "_type": "Value"
20
+ }
21
+ },
22
+ "homepage": "",
23
+ "license": ""
24
+ }
virtual_assembly_and_ground_truth/state.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_data_files": [
3
+ {
4
+ "filename": "data-00000-of-00001.arrow"
5
+ }
6
+ ],
7
+ "_fingerprint": "1908221406de049c",
8
+ "_format_columns": [
9
+ "asm",
10
+ "generated_asm",
11
+ "query",
12
+ "source_code"
13
+ ],
14
+ "_format_kwargs": {},
15
+ "_format_type": null,
16
+ "_output_all_columns": false,
17
+ "_split": null
18
+ }