Skip to content

Commit

Permalink
Server logging behind flag
Browse files Browse the repository at this point in the history
  • Loading branch information
nbbeeken committed Oct 2, 2018
1 parent b7bb93c commit a059892
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 11 deletions.
10 changes: 8 additions & 2 deletions dashmips/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def main_compile(args):

def main_debug(args):
"""Start debug server for mips."""
debug_mips(host=args.host, port=args.port)
debug_mips(host=args.host, port=args.port, log=args.log)


def main():
Expand All @@ -34,7 +34,9 @@ def main():

parser.add_argument('-v', '--version', action='version', version='0.0.1')

sbp = parser.add_subparsers(title='commands', dest='command', required=True)
sbp = parser.add_subparsers(
title='commands', dest='command', required=True
)
compileparse = sbp.add_parser('compile', aliases=['c'])
debugparse = sbp.add_parser('debug', aliases=['d'])

Expand All @@ -60,6 +62,10 @@ def main():
debugparse.add_argument(
'-i', '--host', default='0.0.0.0', help='run debugger on host'
)
debugparse.add_argument(
'-l', '--log', dest='log',
action='store_true', help='Log all network traffic'
)
debugparse.set_defaults(func=main_debug)

prog_args = parser.parse_args()
Expand Down
20 changes: 14 additions & 6 deletions dashmips/debugserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ class DebugMessage:
error: bool = False

def __post_init__(self):
"""Ensure unique breakpoints."""
# set to remove duplicates and sort
self.breakpoints = sorted(set(self.breakpoints))

def __iter__(self):
"""Make DebugMessage castable to dict."""
return iter(asdict(self).items())

@staticmethod
Expand Down Expand Up @@ -54,15 +56,17 @@ def respond(self, msg: DebugMessage):
msg_to_send = json.dumps(dict(msg)).encode('utf8')
self.wfile.write(msg_to_send + b'\r\n\r\n')
self.wfile.flush()
print(f"{self.client_address}: Respond {msg}")
if self.server.log:
print(f"{self.client_address}: Respond {msg}")

def receive(self) -> Optional[DebugMessage]:
"""Receive Client Command."""
try:
msg = DebugMessage.from_dict(
json.loads(self.rfile.readline().strip())
)
print(f"{self.client_address}: Receive {msg}")
if self.server.log:
print(f"{self.client_address}: Receive {msg}")
return msg
except json.JSONDecodeError:
return None
Expand All @@ -71,7 +75,8 @@ def handle(self):
"""Handle Client Req."""
from dashmips.debugger import Commands
try:
print(f"{self.client_address}: Connected")
if self.server.log:
print(f"{self.client_address}: Connected")
msg = self.receive()
if msg is None:
self.respond(DebugMessage(**{
Expand Down Expand Up @@ -111,26 +116,29 @@ class MipsDebugServer(TCPServer):

def __init__(self,
server_address=('0.0.0.0', 9999),
log=False,
RequestHandlerClass=MipsDebugRequestHandler,
bind_and_activate=True) -> None:
"""Create Mips Debug Server."""
self.allow_reuse_address = True
self.log = log
super().__init__(
server_address,
RequestHandlerClass,
bind_and_activate
)
print(f"Server is listening on {self.socket.getsockname()}")
if self.log:
print(f"Server is listening on {self.socket.getsockname()}")

def server_bind(self):
"""Set reusable address opt."""
self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.socket.bind(self.server_address)


def debug_mips(host='localhost', port=9999):
def debug_mips(host='localhost', port=9999, log=False):
"""Create a debugging instance of mips."""
with MipsDebugServer(server_address=(host, port)) as server:
with MipsDebugServer(server_address=(host, port), log=log) as server:
try:
server.allow_reuse_address = True
server.serve_forever()
Expand Down
3 changes: 3 additions & 0 deletions dashmips/instructions/special_instructions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@


def parse(arg):
"""Instructions that take no arguments."""
return tuple()


@mips_instruction('', parse)
def nop(program):
"""Do nothing."""
return True


@mips_instruction('', parse)
def syscall(program):
"""Call syscall specified in $v0."""
return Syscalls[program.registers['$v0']](program)
3 changes: 2 additions & 1 deletion dashmips/mips.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@


class MipsException(Exception):
"""Mips related errors"""
"""Mips related errors."""

def __init__(self, message):
"""Create MipsException."""
super().__init__(message)
self.message = message

Expand Down
3 changes: 2 additions & 1 deletion dashmips/preprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ def preprocess(file: TextIO) -> MipsProgram:
processed_code = code_labels(labels, unprocessed_code)

source = [
SourceLine(file.name, lineno=ol[0], line=ol[1]) for ol in processed_code
SourceLine(file.name, lineno=ol[0], line=ol[1])
for ol in processed_code
]

assert 'main' in labels
Expand Down
1 change: 1 addition & 0 deletions dashmips/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ def run(program: MipsProgram, runnable=lambda _: True):


def next_instruction(program):
"""Execute One Instruction."""
current_pc = program.registers['pc']
if len(program.source) < current_pc:
# We jumped or executed beyond available text
Expand Down
1 change: 0 additions & 1 deletion dashmips/syscalls/print_syscalls.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def _exit(program):
sys.exit(program.registers['$a0'])



@mips_syscall(45)
def dump_program(program):
"""Print json format of program."""
Expand Down

0 comments on commit a059892

Please sign in to comment.