Hi I have been attempting to use python library functions to invoke terminal gdb in terminal on a file and input in another file and then read output(segfault or exit code) for automated debugging. I have attempted using subprocess and pexpect libraries but both do not pick up on it segmentation faulting. pexpect library code:
if len(sys.argv) < 3:
print("Not enough arguments, program terminated.")
exit(1)
filename = sys.argv[1]
inputfile = sys.argv[2]
child = pexpect.spawn(f'gdb {sys.argv[1]}')
child.expect("(gdb) ")
child.sendline(f"run {sys.argv[2]}")
child.expect(["exited normally", "exited with code", pexpect.EOF])
if "exited normally" in child.before.decode('utf-8'):
print("Program exited normally.")
else:
print("Segmentation fault")
child.expect("0x[0-9a-fA-F]+")
address = child.after.decode('utf-8')
print(f"Segfaulted at address: {address}")
child.close() subprocess library code:
def run_gdb(filename, input_file):
gdb_script = f"""
run < {input_file}
info registers
quit
"""
full_script = gdb_script.format(input_file)
process = subprocess.Popen(['gdb', filename],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate(input=full_script)
# Check if there was a segmentation fault
if 'Segmentation fault' in stderr:
# Extract the address from the register information
match = re.search(r'rip\s*([0-9a-fA-F]+)', stderr)
if match:
faulting_address = match.group(1)
print(f"Segmentation fault at address: {faulting_address}")
print(f"Input string that caused the fault: {input_file}")
else:
print("Failed to extract address from register information.")
else:
print("Program exited normally.")
if __name__ == "__main__":
filename = "your_binary_file"
input_file = "your_input_file"
run_gdb(filename, input_file)
Any help is welcome. Thank you in advance.