Skip to content

SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]

[WIP] Implement GDB interactive session

Meet Udeshic2737756956e
diff --git a/config/commands/debug.sh b/config/commands/debug.sh
new file mode 100644
index 00000000..653f7ee3
--- /dev/null
+++ b/config/commands/debug.sh
@@ -0,0 +1,102 @@
+_debug_command() {
+ echo "<<INTERACTIVE_GDB||$@||INTERACTIVE_GDB>>"
+}
+
+# @yaml
+# signature: debug_start <binary> [<args>]
+# docstring: Starts a debug session with the given binary.
+# arguments:
+# binary:
+# type: string
+# description: the path to the binary to debug
+# required: true
+# args:
+# type: string
+# description: optional command-line arguments for the binary
+# required: false
+debug_start() {
+ if [ -z "$1" ]
+ then
+ echo "Usage: debug_start <binary>"
+ return
+ fi
+ if [ ! -x "$1" ]
+ then
+ echo "Error: File $1 does not exist, or is not executable"
+ return
+ fi
+ fp=$(realpath $1)
+ _debug_command "START"
+ _debug_command "file $fp"
+ _debug_command "starti"
+}
+
+# @yaml
+# signature: debug_add_breakpoint <breakpoint>
+# docstring: Adds a breakpoint in the debug session
+# arguments:
+# breakpoint:
+# type: string
+# description: The breakpoint location, which may be a function name, address, or filename and line number.
+# required: true
+debug_add_breakpoint() {
+ if [ -z "$1" ]
+ then
+ echo "Usage: debug_add_breakpoint <breakpoint>"
+ return
+ fi
+ _debug_command 'break '$1
+}
+
+# @yaml
+# signature: debug_continue
+# docstring: Continues the program execution in the debug session.
+debug_continue() {
+ _debug_command 'continue'
+}
+
+# @yaml
+# signature: debug_step [number]
+# docstring: Steps number of instructions in the debug session.
+# arguments:
+# number:
+# type: integer
+# description: number of instructions to step (default is 1)
+# required: false
+debug_step() {
+ if [ -z "$1" ]
+ then
+ _debug_command 'stepi'
+ elif [[ (("$1" -eq "$1") && ("$1" -gt "0")) ]] # Check if integer and positive
+ then
+ _debug_command 'stepi '$1
+ else
+ echo "Please provide a positive integer for number of instructions."
+ echo "Usage: debug_step [number]"
+ fi
+}
+
+# @yaml
+# signature: debug_exec <command>
+# docstring: Executes arbitrary gdb command in debug session.
+# arguments:
+# command:
+# type: string
+# description: command to execute
+# required: true
+debug_exec() {
+ if [ -z "$1" ]
+ then
+ echo "Usage: debug_exec <command>"
+ return
+ fi
+ _debug_command "$1"
+}
+
+# @yaml
+# signature: debug_stop
+# docstring: Stops the current debug session.
+debug_stop() {
+ _debug_command "quit"
+ _debug_command "STOP"
+}
diff --git a/config/default_ctf.yaml b/config/default_ctf.yaml
index 7718572f..bda29e0a 100644
--- a/config/default_ctf.yaml
+++ b/config/default_ctf.yaml
@@ -107,5 +107,6 @@ command_files:
- config/commands/submit_ctf.sh
- config/commands/decompile.py
- config/commands/disassemble.py
+- config/commands/debug.sh
parse_command: ParseCommandDetailed
history_processor: Last5Observations
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 9d65d3ff..5cd33aac 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -37,6 +37,7 @@ from sweagent.environment.utils import (
copy_file_to_container,
format_trajectory_markdown,
get_container,
+ get_interactive_gdb_session,
get_docker_compose,
get_gh_issue_data,
get_instances,
@@ -44,6 +45,7 @@ from sweagent.environment.utils import (
parse_gh_issue_url,
read_with_timeout,
read_with_timeout_experimental,
+ read_session_with_timeout,
terminate_docker_compose,
)
from sweagent.types import AgentInfo
@@ -54,6 +56,7 @@ LONG_TIMEOUT = float(keys_config.get("SWE_AGENT_ENV_LONG_TIMEOUT", 500))
AGENT_ACTION_TIMEOUT = float(keys_config.get("SWE_AGENT_ACTION_TIMEOUT", 25))
PATH_TO_REQS = "/root/requirements.txt"
PATH_TO_ENV_YML = "/root/environment.yml"
+GDB_TERMINAL_PATTERN = "(gdb) "
@dataclass(frozen=True)
@@ -191,6 +194,8 @@ class SWEEnv(gym.Env):
self.challenge: dict[str, Any] | None = None
self._reset_container()
+ self.interactive_session: subprocess.Popen | None = None
+
self.idx = 0
self.clean_multi_line_functions = lambda x: x
self.hooks: list[EnvHook] = []
@@ -551,6 +556,30 @@ class SWEEnv(gym.Env):
self.logger.warning(f"Wrong submission found: {submission}")
observation = "Wrong flag!"
return observation, 0, False, info
+
+ session_name, interactive_commands = self.get_interactive_commands(observation)
+ if session_name is not None:
+ observation = ""
+ self.logger.debug(f"Interactive session: {session_name}\nCommands: {', '.join(interactive_commands)}")
+ for command in interactive_commands:
+ if command == "START":
+ # Start the session
+ self.interactive_session = get_interactive_gdb_session(self.container_name)
+ elif command == "STOP":
+ if self.interactive_session.poll() is not None:
+ self.logger.warning("gdb did not quit successfully")
+ observation = "Could not quit"
+ else:
+ observation = "Debug session stopped successfully"
+ self.interactive_session = None
+ else:
+ if self.interactive_session is None:
+ self.logger.warning("Tried to run gdb commands without starting session")
+ observation = "Debug session is not running! please start it first using `debug_start`"
+ else:
+ observation += self.communicate_session(command, GDB_TERMINAL_PATTERN)
+ observation += "\n"
+
return observation, 0, False, info
def close(self) -> None:
@@ -888,6 +917,44 @@ class SWEEnv(gym.Env):
raise RuntimeError(msg)
return logs
+ def communicate_session(self, input: str, terminal_pattern: str, timeout_duration: int | float = 25) -> str:
+ """
+ Sends input to interactive_session and returns output
+
+ Args:
+ input: input to send to session
+ terminal_pattern: pattern indicating the session's output termination (e.g., "(gdb) " in gdb)
+ timeout_duration: duration to wait for output
+
+ Returns:
+ output: output from session
+ """
+ assert self.interactive_session is not None
+ self.logger.log(logging.TRACE, "Input:\n%s", input) # type: ignore
+
+ try:
+ cmd = input if input.endswith("\n") else input + "\n"
+ os.write(self.interactive_session.stdin.fileno(), cmd.encode())
+ time.sleep(0.03)
+ self.interactive_session.stdin.flush()
+ except BrokenPipeError:
+ traceback.print_exc()
+ self.logger.error("Failed to communicate with session. Check docker logs for more information.")
+ msg = "Failed to communicate with session"
+ raise RuntimeError(msg)
+
+ if input.strip() != "quit":
+ try:
+ buffer = read_session_with_timeout(self.interactive_session, terminal_pattern, timeout_duration)
+ except Exception:
+ msg = f"Read with timeout failed on input:\n---\n{input}\n---"
+ self.logger.error(msg)
+ raise
+ self.logger.log(logging.TRACE, "Output:\n%s", buffer) # type: ignore
+ return buffer
+ else:
+ return ""
+
def get_available_actions(self) -> list[str]:
"""
Returns list of available actions in current environment state
@@ -928,6 +995,30 @@ class SWEEnv(gym.Env):
return submission.strip() == self.challenge["flag"]
return True
+ def get_interactive_commands(self, output: str):
+ """
+ Function for extracting interactive session commands.
+
+ Args:
+ output: observation
+
+ Returns:
+ session: session name for the commands or None if no commands found.
+ commands: list of commands extracted from observation.
+ """
+ # TODO: dont hardcode GDB
+ pattern = r"\<\<INTERACTIVE_GDB\|\|(.*)\|\|INTERACTIVE_GDB\>\>"
+ commands = []
+ for line in output.split("\n"):
+ match = re.search(pattern, line, re.DOTALL)
+ if match is None:
+ continue
+ commands.append(match.group(1))
+ if len(commands) > 0:
+ return "GDB", commands
+ else:
+ return None, []
+
def get_submission(self, output: str) -> str | None:
"""
Function for extracting diff patch submission at the end of an episode.
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 244e3588..61914c2d 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -273,6 +273,54 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_duration
exit_code = _results.group(1)
return body, exit_code
+def read_session_with_timeout(session: subprocess.Popen, terminal_pattern: str, timeout_duration: int | float) -> str:
+ """
+ Read data from a subprocess with a timeout.
+ This function uses a file descriptor to read data from the subprocess in a non-blocking way.
+
+ Args:
+ session: The session subprocess.
+ terminal_pattern: the terminal pattern to indicate end of output.
+ timeout_duration: The timeout duration in seconds.
+
+ Returns:
+ Output
+
+ Raises:
+ TimeoutError: If the timeout duration is reached while reading from the subprocess.
+ """
+ buffer = b""
+ fd = session.stdout.fileno()
+ end_time = time.time() + timeout_duration
+
+ # Select is not available on windows
+ import select
+ def ready_to_read(fd) -> bool:
+ return bool(select.select([fd], [], [], 0.01)[0])
+
+ while time.time() < end_time:
+ if ready_to_read(fd):
+ try:
+ data = os.read(fd, 4096)
+ except BlockingIOError:
+ logger.error("BlockingIOError while reading from subprocess.", exc_info=True)
+ break
+ if data:
+ buffer += data
+ if terminal_pattern in buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n"):
+ break
+ time.sleep(0.01) # Prevents CPU hogging
+
+ if session.poll() is not None:
+ msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}"
+ raise RuntimeError(msg)
+ if time.time() >= end_time:
+ msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}"
+ raise TimeoutError(msg)
+
+ decoded = buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n")
+ body = "\n".join(line for line in decoded.splitlines() if not line.startswith(terminal_pattern))
+ return body
def get_background_pids(container_obj: Container):
pids = container_obj.exec_run("ps -eo pid,comm --no-headers").output.decode().split("\n")
@@ -352,6 +400,15 @@ def get_docker_compose(docker_compose_path: Path) -> Path:
logger.error(f"Unexpected compose setup error: {error}")
return docker_compose_path
+def get_interactive_gdb_session(ctr_name: str) -> subprocess.Popen:
+ startup_cmd = ["docker", "exec", "-i", ctr_name, "gdb"]
+ logger.debug("Starting interactive gdb session with command: %s", shlex.join(startup_cmd))
+ session = subprocess.Popen(startup_cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, text=True, bufsize=1)
+ time.sleep(DOCKER_START_UP_DELAY)
+ output = read_with_timeout(session, lambda: list(), timeout_duration=1)
+ logger.debug(f"gdb session initial output: {output}")
+
+ return session
def _get_non_persistent_container(ctr_name: str, image_name: str) -> tuple[subprocess.Popen, set[str]]:
startup_cmd = [