opdb/c/server-c.py

150 lines
4.7 KiB
Python

import json
import log
import time
import subprocess
from flask import Flask
from flask import request
from mygdbcontroller import MyGdbController
from pygdbmi.gdbcontroller import NoGdbProcessError
gdbmi = None
app = Flask(__name__)
expression_list = []
def request_interceptor(request):
# Super bad practice.
request.args = request.args.to_dict()
command = request.args.get("command")
request.args["original_command"] = command
if command.startswith("add-expression"):
expression = command.split(" ", 1)[1]
expression = expression.strip()
expression_list.append(expression)
return get_expressions(command)
elif command.startswith("remove-expression"):
expression = command.split(" ", 1)[1]
expression = expression.strip()
if expression in expression_list:
expression_list.remove(expression)
return get_expressions(command)
elif "get-expressions" in command:
expression_dict = {}
for expression in expression_list:
try:
command = '-data-evaluate-expression "{}"'.format(expression)
response = gdbmi.write(command, timeout_sec=3)
value = ""
for line in response:
if (
line["type"] != "result"
or line["stream"] != "stdout"
or "payload" not in line
):
continue
if "value" in line["payload"]:
value = line["payload"]["value"]
break
elif "msg" in line["payload"]:
value = line["payload"]["msg"]
break
except Exception as e:
value = "Unable to retrieve expression's value."
log.error(e)
expression_dict[expression] = value
return expression_dict
def response_interceptor(request, response):
return response
def get_expressions(command):
expression_dict = {}
for expression in expression_list:
try:
command = '-data-evaluate-expression "{}"'.format(expression)
response = gdbmi.write(command, timeout_sec=3)
value = ""
for line in response:
if (
line["type"] != "result"
or line["stream"] != "stdout"
or "payload" not in line
):
continue
if "value" in line["payload"]:
value = line["payload"]["value"]
break
elif "msg" in line["payload"]:
value = line["payload"]["msg"]
break
except Exception as e:
value = "Unable to retrieve expression's value."
log.error(e)
expression_dict[expression] = value
return expression_dict
@app.route("/compile")
def compile():
language = request.args.get("language")
command = request.args.get("command")
command_list = command.split(",")
if language is None or language == "c":
compile_command = ["gcc", "-g", "-o", "myProgram.out"] + command_list
else:
compile_command = ["g++", "-g", "-std=c++11", "-lstdc++", "-o", "myProgram.out"] + command_list
try:
result = subprocess.run(compile_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, check=True)
output = result.stdout + result.stderr
return output
except subprocess.CalledProcessError as e:
return "Compilation Error:\n" + e.stderr
@app.route("/run_command")
def run_command():
response = request_interceptor(request)
if response is not None:
log.info("Response given through custom interceptor.")
return json.dumps(response)
command = request.args.get("command")
gdbmi.write(command, read_response=False)
time.sleep(1)
return get_responses()
@app.route("/get_responses")
def get_responses():
try:
response = gdbmi.get_gdb_response(
timeout_sec=0, raise_error_on_timeout=False
)
except NoGdbProcessError as e:
response = {
"message": "stopped",
"payload": {
"reason": "exception",
"msg": str(e),
},
}
return {'response': response}
def main():
global gdbmi
input_file = open('input.txt', 'r')
output_file = open('output.txt', 'w')
gdbmi = MyGdbController(gdb_args=["--quiet", "--interpreter=mi2"], input_file=input_file, output_file=output_file)
app.run(host="0.0.0.0", port=80)
if __name__ == "__main__":
main()