GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Multi-Hunk-APR/vul4j.py at master · iSEngLab/Multi-Hunk-APR

Expand file tree

/

vul4j.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
421 lines (347 loc) · 14.5 KB
/

vul4j.py

Copy path

File metadata and controls

421 lines (347 loc) · 14.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import json
import logging
import os.path
import subprocess
from common_config import get_vul_repo_root, get_vul_context_save_dir
from bug import BuggyHunk
from utils import apply_modifications
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def vul_checkout(vul_id):
if not os.path.exists(get_vul_repo_root()):
os.makedirs(get_vul_repo_root())
path = f'{get_vul_repo_root()}/{vul_id}'
if os.path.exists(path):
subprocess.run(['rm', '-rf', path])
# $ vul4j checkout --id VUL4J-1 -d /root/autodl-tmp/vul4j/repos/VUL4J-1
result = subprocess.run([
'vul4j', 'checkout', '--id', vul_id, '-d', path
], capture_output=True,
text=True,
timeout=3000)
if result.returncode == 0:
logging.info(f'Checkout vul {vul_id} to {path} success')
else:
logging.error(f'Checkout vul {vul_id} to {path} fail, error msg: {result.stderr}')
import os
from difflib import unified_diff
def get_vul_location(vul_id):
DATA_ROOT = f"{get_vul_repo_root()}/{vul_id}/VUL4J"
before_dir = DATA_ROOT + "/vulnerable"
after_dir = DATA_ROOT + "/human_patch"
hunks = []
file_list = json.load(open(before_dir + '/paths.json', 'r')).values()
file_names = json.load(open(before_dir + '/paths.json', 'r')).keys()
if vul_id == 'VUL4J-23':
file_list = [x for x in file_list if not x.startswith('testing')]
file_names = [x for x in file_names if not x.startswith('testing')]
before_file_list = [before_dir + '/' + x for x in file_names]
after_file_list = [after_dir + '/' + x for x in file_names]
for file_in_repo, before_file, after_file in zip(file_list, before_file_list, after_file_list):
abs_path = get_vul_repo_root() + '/' + vul_id + '/' + file_in_repo
java_funcs = get_java_funcs_for_vul(vul_id, abs_path)
try:
with open(before_file, 'r', encoding='utf-8') as f:
before_lines = f.read().splitlines()
with open(after_file, 'r', encoding='utf-8') as f:
after_lines = f.read().splitlines()
except Exception as e:
print(f"Error reading files {before_file} or {after_file}: {e}")
continue
diff_lines = list(unified_diff(
before_lines, after_lines,
fromfile=str(before_file),
tofile=str(after_file),
lineterm='',
n=0
))
print('\n'.join(diff_lines))
i = 0
while i < len(diff_lines):
line = diff_lines[i]
if line.startswith('@@'):
# hunk header: @@ -old_start,old_len +new_start,new_len @@
hunk_header = line
import re
match = re.match(r'@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@', hunk_header)
if not match:
i += 1
continue
old_start = int(match.group(1))
old_len = int(match.group(2)) if match.group(2) else 1
new_start = int(match.group(3))
new_len = int(match.group(4)) if match.group(4) else 1
hunk_content = []
j = i + 1
while j < len(diff_lines) and diff_lines[j].startswith((' ', '+', '-')):
hunk_content.append(diff_lines[j])
j += 1
lines_deleted = [ln[1:] for ln in hunk_content if ln.startswith('-') and not ln.startswith('--')]
lines_added = [ln[1:] for ln in hunk_content if ln.startswith('+') and not ln.startswith('++')]
belonging_func = None
for func in java_funcs:
start_line = func['startLine']
end_line = func['endLine']
if start_line <= old_start and end_line >= old_start + old_len - 1:
belonging_func = func
break
if belonging_func is not None:
func_name = belonging_func['name']
func_signature = belonging_func['signature']
func_start_line = belonging_func['startLine']
func_end_line = belonging_func['endLine']
func_lines = before_lines[func_start_line - 1:func_end_line]
else:
func_name = ''
func_signature = ''
func_start_line = -1
func_end_line = -1
func_lines = []
buggy_hunk = BuggyHunk(
file_path=abs_path,
file_lines=before_lines,
func_name=func_name,
func_signature=func_signature,
func_lines=func_lines,
func_start_line=func_start_line,
func_end_line=func_end_line,
hunk_start_line=old_start,
hunk_end_line=old_start + old_len - 1,
hunk_lines=hunk_content,
lines_deleted=lines_deleted,
lines_added=lines_added
)
hunks.append(buggy_hunk)
i = j
else:
i += 1
return hunks
import csv
from dataclasses import dataclass, fields
from typing import Optional, List
from common_config import get_VUL4J_root
@dataclass
class Vulnerability:
no: int # Serial number or ID
vul_id: str # Custom ID for the vulnerability
cve_id: Optional[str] # CVE ID, may be empty
cwe_id: Optional[str] # CWE ID, e.g., "CWE-78"
cwe_name: Optional[str] # CWE name, e.g., "OS Command Injection"
owasp_id: Optional[str] # OWASP related ID or category, e.g., "A1:2017-Injection"
repo_slug: str # Repository name or path, e.g., "spring-petclinic"
human_patch: str # Manual patch content (could be diff or file path)
build_system: str # Build system, e.g., "maven", "gradle"
compliance_level: Optional[str] # Compliance level, e.g., "high", "medium"
failing_tests: List[str] # List of failing test cases
compile_cmd: str # Compilation command
test_all_cmd: str # Command to run all tests
test_cmd: str # Command to run the target test
cmd_options: Optional[str] # Command line options (optional)
failing_module: str # Name of the failing module
src: str # Source code directory path
test: str # Test code directory path
src_classes: str # Compiled source classes path (e.g., target/classes)
test_classes: str # Compiled test classes path (e.g., target/test-classes)
warning: str # Warning information or static analysis alert content
def read_vulnerabilities_from_csv(csv_file_path: str) -> List[Vulnerability]:
if csv_file_path is None or csv_file_path == '':
csv_file_path = f'{get_VUL4J_root()}/dataset/vul4j_dataset.csv'
vulnerabilities = []
field_names = [field.name for field in fields(Vulnerability)]
with open(csv_file_path, mode='r', encoding='utf-8') as f:
reader = csv.DictReader(f)
if reader.fieldnames is None:
raise ValueError("CSV is empty or lack head")
header = [name.strip() for name in reader.fieldnames]
if header != field_names:
raise ValueError(f"CSV head not match. expect: {field_names},actual: {header}")
for row_num, row in enumerate(reader, start=2):
try:
instance = Vulnerability(
no=int(row['no']),
vul_id=row['vul_id'],
cve_id=row['cve_id'] or None,
cwe_id=row['cwe_id'] or None,
cwe_name=row['cwe_name'] or None,
owasp_id=row['owasp_id'] or None,
repo_slug=row['repo_slug'],
human_patch=row['human_patch'],
build_system=row['build_system'],
compliance_level=row['compliance_level'] or None,
failing_tests=[t.strip() for t in row['failing_tests'].split(';')] if row['failing_tests'] else [],
compile_cmd=row['compile_cmd'],
test_all_cmd=row['test_all_cmd'],
test_cmd=row['test_cmd'],
cmd_options=row['cmd_options'] or None,
failing_module=row['failing_module'],
src=row['src'],
test=row['test'],
src_classes=row['src_classes'],
test_classes=row['test_classes'],
warning=row['warning']
)
if instance.cve_id is not None:
vulnerabilities.append(instance)
except Exception as e:
raise ValueError(f"parse CSV row {row_num} error: {e}")
return vulnerabilities
all_vuls = read_vulnerabilities_from_csv('')
skip_list = ['VUL4J-4', 'VUL4J-19', 'VUL4J-27', 'VUL4J-37']
def get_all_vuls():
return [x for x in all_vuls if x.vul_id not in skip_list]
def get_vul_by_vul_id(vul_id):
for x in all_vuls:
if x.vul_id == vul_id:
return x
return None
def get_vul_module(vul_id):
return get_vul_by_vul_id(vul_id).failing_module
def get_vul_source_code_root(vul_id):
vul = get_vul_by_vul_id(vul_id)
path = vul.src
module = get_vul_module(vul_id)
if module == 'xwork-core':
module = 'core'
if module != 'root':
path = module + '/' + path
if vul_id == 'VUL4J-66':
path = 'resteasy-core/src/main/java'
path += '/' + vul.failing_tests[0].split('.')[0]
return path
def get_vul_test_root(vul_id):
vul = get_vul_by_vul_id(vul_id)
path = vul.test
module = get_vul_module(vul_id)
if module != 'root':
path = module + '/' + path
path += '/' + vul.failing_tests[0].split('.')[0]
return path
def get_java_funcs_for_vul(vul_id, file_path):
path = get_vul_context_save_dir() + os.path.sep + f'{vul_id}' + os.path.sep + file_path.replace(
get_vul_repo_root() + '/', '').replace('/',
"_").replace(
'.java', '.json')
with open(path, 'r') as f:
java_file_info = json.load(f)
func_list = []
for method_info in java_file_info['methodList']:
func_list.append({
'name': method_info['name'],
'signature': method_info['signature'],
'startLine': method_info['startLine'],
'endLine': method_info['endLine']
})
return func_list
def compile_vul_and_run_test(vul_id):
work_dir = f'{get_vul_repo_root()}/{vul_id}'
vul = get_vul_by_vul_id(vul_id)
# compile
logging.info(f'Compile vul {vul_id}')
# vul4j compile -d /tmp/vul4j/VUL4J-10
compile_result = subprocess.run([
'vul4j', 'compile', '-d', work_dir
],
capture_output=True,
text=True,
timeout=3000
)
logging.info(f'Compile result: {compile_result}')
if compile_result.returncode != 0:
return compile_result.stderr, False
# vul4j test -d /tmp/vul4j/VUL4J-10
test_result = subprocess.run(
['vul4j', 'test', '-d', work_dir],
capture_output=True,
text=True,
timeout=3000
)
logging.info(f'Test result: {test_result}')
return test_result, True
def get_failing_test_report_for_vul(vul_id):
test_report_path = f'{get_vul_repo_root()}/{vul_id}/VUL4J/testing_results.json'
if not os.path.exists(test_report_path):
return None
with open(test_report_path, 'r') as f:
failures = json.load(f)['tests']['failures']
f.close()
lines = []
for failure in failures:
test_class = failure["test_class"]
test_method = failure["test_method"]
failure_name = failure["failure_name"]
detail = failure["detail"].strip() if 'detail' in failure else ''
is_error = failure["is_error"]
lines.append(f"Class: {test_class}")
lines.append("-" * 40)
status = "ERROR" if is_error else "FAILURE"
lines.append(f" Method: {test_method}")
lines.append(f" Status: {status}")
lines.append(f" Type: {failure_name}")
lines.append(f" Detail: {detail}")
lines.append("")
return "\n".join(lines)
def get_test_class_and_method_for_vul(vul_id):
test_report_path = f'{get_vul_repo_root()}/{vul_id}/VUL4J/testing_results.json'
if not os.path.exists(test_report_path):
return {}
result = {}
with open(test_report_path, 'r') as f:
failures = json.load(f)['tests']['failures']
f.close()
for failure in failures:
if failure['test_class'] not in result:
result[failure['test_class']] = [failure['test_method']]
else:
result[failure['test_class']].append(failure['test_method'])
return result
def get_patch_diff_and_test_for_vul(vul_id, modifications, tmp_branch='tmp', clean_branch=True):
work_dir = f'{get_vul_repo_root()}/{vul_id}'
detach_head = subprocess.run([
'git', 'describe', '--always', 'HEAD'
],
capture_output=True,
text=True,
timeout=300,
cwd=work_dir
).stdout.strip()
subprocess.run([
'git', 'switch', '-c', tmp_branch
],
capture_output=True,
text=True,
timeout=300,
cwd=work_dir
)
apply_modifications(modifications)
subprocess.run([
'git', 'add'
] + [x.replace(work_dir + '/', '') for x in modifications.keys()], cwd=work_dir)
subprocess.run([
'git', 'commit', '-m', 'submit patch'
], cwd=work_dir)
patch = ''
try:
result = subprocess.run(
['git', 'diff', '--no-color', 'HEAD~1..HEAD', '--', ' '.join(modifications.keys())],
capture_output=True,
text=True,
check=False,
cwd=work_dir
)
patch = result.stdout.strip()
if not patch:
print(f"No changes detected by git diff")
except Exception as e:
print("Error running git diff:", str(e))
finally:
test_result, is_compile_success = compile_vul_and_run_test(vul_id)
test_report = get_failing_test_report_for_vul(vul_id)
if not is_compile_success:
test_report = f'Compile Fail: {test_result}'
if clean_branch:
subprocess.run([
'git', 'checkout', detach_head
], cwd=work_dir)
subprocess.run([
'git', 'branch', '-D', tmp_branch
], cwd=work_dir)
return patch, test_report, test_result
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.