-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
189 lines (150 loc) · 5.24 KB
/
main.py
File metadata and controls
189 lines (150 loc) · 5.24 KB
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
#!/usr/bin/env python3
"""
Main entry point for LLM-Bisect.
This module provides the primary interface for running the bug-inducing
commit identification pipeline on Linux kernel vulnerabilities.
Usage:
python -m llm_bisect.main <commit> [--model MODEL]
Example:
python -m llm_bisect.main 6ca575374dd9a507cdd16dfa0e78c2e9e20bd05f --model o1
"""
import sys
import logging
import argparse
from typing import Optional, Dict, Any
from .config import Config, set_config, get_config
from .bisect import bisect_vulnerability, Bisector, BisectResult
from .analysis import extract_critical_lines
from .utils.file_utils import save_json, load_json, ensure_dir
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def get_case_all_results(commit: str, model: str = "o1") -> Dict[str, Any]:
"""
Run the complete bisect analysis for a given patch commit.
This is the main entry point that replicates the functionality of
the original evaluate.get_case_all_results().
Args:
commit: The patch/fix commit hash
model: LLM model to use
Returns:
Dictionary containing all analysis results
"""
config = get_config()
config.llm.model = model
set_config(config)
logger.info(f"Processing commit: {commit}")
logger.info(f"Using model: {model}")
results = {
"patch_commit": commit,
"model": model,
"inducing_commit": None,
"candidates": {},
"success": False,
}
try:
# Extract critical lines
logger.info("Step 1: Extracting critical lines from patch...")
critical_lines = extract_critical_lines(commit, use_llm=True)
results["critical_lines_count"] = len(critical_lines)
logger.info(f" Found {len(critical_lines)} critical lines")
# Run bisection
logger.info("Step 2: Running bisection to find bug-inducing commit...")
bisector = Bisector()
bisect_result = bisector.bisect(commit)
results["inducing_commit"] = bisect_result.inducing_commit
results["candidates"] = bisect_result.all_candidates
results["candidates_filtered"] = bisect_result.candidates_filtered
results["success"] = bisect_result.success
results["error"] = bisect_result.error
if bisect_result.success:
logger.info(f" Bug-inducing commit: {bisect_result.inducing_commit}")
else:
logger.warning(f" Bisect failed: {bisect_result.error}")
# Save results
output_dir = config.paths.results_dir
ensure_dir(output_dir)
output_file = f"{output_dir}/{commit[:12]}_{model}_results.json"
save_json(results, output_file)
logger.info(f"Results saved to: {output_file}")
except Exception as e:
logger.exception(f"Error processing commit {commit}: {e}")
results["error"] = str(e)
return results
def run_batch(
commits: list,
model: str = "o1",
output_file: Optional[str] = None,
) -> Dict[str, Dict[str, Any]]:
"""
Process multiple commits in batch.
Args:
commits: List of patch commit hashes
model: LLM model to use
output_file: Optional output file path
Returns:
Dictionary mapping commit to results
"""
all_results = {}
for i, commit in enumerate(commits, 1):
logger.info(f"Processing {i}/{len(commits)}: {commit}")
results = get_case_all_results(commit, model)
all_results[commit] = results
if output_file:
save_json(all_results, output_file)
logger.info(f"Batch results saved to: {output_file}")
return all_results
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="LLM-Bisect: Find bug-inducing commits"
)
parser.add_argument(
"commit",
nargs="?",
help="Patch commit to analyze",
)
parser.add_argument(
"--model",
default="o1",
help="LLM model to use (default: o1)",
)
parser.add_argument(
"--input",
help="JSON file with list of commits",
)
parser.add_argument(
"--output",
help="Output file for results",
)
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="Enable verbose logging",
)
args = parser.parse_args()
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
if args.input:
# Batch mode
commits = load_json(args.input, [])
if isinstance(commits, dict):
commits = list(commits.keys())
run_batch(commits, args.model, args.output)
elif args.commit:
# Single commit mode
results = get_case_all_results(args.commit, args.model)
if results["success"]:
print(f"\nBug-inducing commit: {results['inducing_commit']}")
return 0
else:
print(f"\nFailed: {results.get('error', 'Unknown error')}")
return 1
else:
parser.print_help()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())