-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdboost.py
166 lines (137 loc) · 4.99 KB
/
gdboost.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
import gdb
import json
from openai import OpenAI
def loadConfig():
try:
with open("config.json", "r") as config_file:
config = json.load(config_file)
clarity_response = config.get("clarityResponse", 0)
llm_model = config.get("llmModel", "openai/gpt-3.5-turbo")
if clarity_response not in (0, 1):
clarity_response = 0
return clarity_response, llm_model
except Exception as e:
print(f"Error reading config.json: {e}")
return 0, "openai/gpt-3.5-turbo"
def frameContext():
try:
frame = gdb.selected_frame()
if not frame:
return {
"error": "No frame is currently selected. Ensure the program is paused in a valid function."
}
block = frame.block()
if not block:
return {
"frame_name": frame.name() or "No frame",
"pc": hex(frame.pc()) if frame.pc() else "Unknown",
"locals": {},
"error": "Cannot locate block for frame. Frame context may be incomplete."
}
locals_context = {
symbol.name: str(symbol.value(frame))
for symbol in block if symbol.is_variable
}
return {
"frame_name": frame.name() or "No frame",
"pc": hex(frame.pc()) if frame.pc() else "Unknown",
"locals": locals_context,
}
except Exception as e:
return {
"error": f"Error extracting frame context: {e}"
}
def registerContext():
registers = ["eax", "ecx", "edx", "ebx", "esp", "esi", "edi", "eip",
"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rsp", "rbp", "rip"]
register_context = {}
for reg in registers:
try:
value = gdb.parse_and_eval(f"${reg}")
if value is not None:
register_context[reg] = str(value)
except Exception:
pass
return register_context
def breakpointContext():
try:
return [
{"location": bp.location, "enabled": bp.enabled}
for bp in (gdb.breakpoints() or [])
]
except Exception as e:
print(f"Error extracting breakpoint context: {e}")
return []
def disassemblyContext():
try:
return gdb.execute("disassemble", to_string=True)
except gdb.error as e:
print(f"Error extracting disassembly context: {e}")
return "None"
def gdbContext():
frame_context = frameContext() or {}
return {
"frame_name": frame_context.get("frame_name", "No frame"),
"pc": frame_context.get("pc", "Unknown"),
"locals": frame_context.get("locals", {}),
"registers": registerContext(),
"breakpoints": breakpointContext(),
"disassembly": disassemblyContext(),
}
class LLMCommand(gdb.Command):
def __init__(self):
super(LLMCommand, self).__init__("llm", gdb.COMMAND_USER)
try:
with open(".key", "r") as file:
api_key = file.read().strip()
self.client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key,
)
except Exception as e:
print(f"Error initializing OpenAI client: {e}")
self.client = None
def invoke(self, arg, from_tty):
user_query = arg.strip()
if not user_query:
print("Error: No query provided. Usage: llm <your-query>")
return
if not self.client:
print("Error: LLM client not initialized.")
return
clarityResponse, llm_model = loadConfig()
context = gdbContext()
base_prompt = """
You are debugging an x86_64 binary. Here is the current state:
- Current function: {frame_name}
- Program counter (PC): {pc}
- Local variables: {locals}
- Registers: {registers}
- Disassembly:
{disassembly}
- Breakpoints: {breakpoints}
User query: {query}
"""
if clarityResponse == 0:
prompt = "Provide a concise answer.\n\n" + base_prompt
else:
prompt = "Provide a detailed answer.\n\n" + base_prompt
try:
full_prompt = prompt.format(
frame_name=context["frame_name"],
pc=context["pc"],
locals=json.dumps(context["locals"], indent=2),
registers=json.dumps(context["registers"], indent=2),
disassembly=context["disassembly"],
breakpoints=json.dumps(context["breakpoints"], indent=2),
query=user_query,
)
completion = self.client.chat.completions.create(
model=llm_model,
messages=[{"role": "user", "content": full_prompt}],
)
response = completion.choices[0].message.content
print(f"{response}")
except Exception as e:
print(f"Error querying LLM: {e}")
LLMCommand()