I have a C program as such:
//Testing for program hang
//If pass in EOF, this will cause an infinite loop
void vuln() {
char c = getchar();
while(c != ' '){
putchar(c);
c = getchar();
}
}
int main(int argc, char **argv) { vuln(); }
Which will have an infinite loop if send in a file that has no spaces.
In a python file, I am attempting to open this process and send a string to it. The problem I am having is when attempting to get the strace output for this process. Its printing a bunch of question mark characters, even when I do not specify an input to the process. Below is my python code:
from subprocess import Popen, PIPE
import signal
import time
import os
def time_out_handler(signum, frame):
print("Infinite loop detected. Exiting program.")
exit()
binary = './Test/hang'
testInput = 'Test/hang.txt'
proc = Popen([binary], shell=True, stdin=PIPE)
print('Running program, pid: ', proc.pid)
# TIMEOUT APPROACH
signal.signal(signal.SIGALRM, time_out_handler)
signal.alarm(10)
with open(testInput) as f:
text = f.read()
if not isinstance(text, bytearray):
text = bytes(text, 'utf-8')
# COVERAGE BASED
# Send input, check for strace output
# First we fork, in the child process we send the input
newpid = os.fork()
if newpid == 0:
print('sending input')
proc.communicate(text)
exit()
# In parent process we create tracing process
else:
time.sleep(1)
print('in parent')
while(1):
# Attach to the proc process
trace = Popen(['strace -p ' + str(proc.pid)], shell=True, stdout = PIPE, stderr = PIPE)
print('Tracing program, trace_pid: ', trace.pid, '. program_pid: ', proc.pid)
for line in iter(trace.stderr.readline, b''):
print(str(line))
trace.kill()
print('killed')
time.sleep(1)
The terminal output when running this program is as below:
Running program, pid: 4570
sending input
in parent
Tracing program, trace_pid: 4573 . program_pid: 4570
b'strace: Process 4570 attached\n'
Then after 10 seconds, the program exits, after running the time_out_handler function. Which means it is not running any more trace processes. Additionally, if I press any button in the terminal after the proram exits, the terminal gets filled with question mark characters, and i am unable to interrupt or stop this in anyway, the only option is to ctrl-D and close the terminal window.
I am not sure if my method to do this is correct, but can anyone tell me why this behaviour is occuring?