From 93ff8d7186c8cde32fc08fdbd64f26408aa04376 Mon Sep 17 00:00:00 2001 From: Anton Lydike Date: Sat, 17 Apr 2021 20:28:34 +0200 Subject: [PATCH] added unsigned option for int_{from,to}_bytes --- riscemu/Exceptions.py | 22 +++++++++++++++++++++- riscemu/helpers.py | 11 ++++++++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/riscemu/Exceptions.py b/riscemu/Exceptions.py index 7182d6d..c57b376 100644 --- a/riscemu/Exceptions.py +++ b/riscemu/Exceptions.py @@ -7,6 +7,8 @@ class RiscemuBaseException(BaseException): pass +# Parsing exceptions: + class ParseException(RiscemuBaseException): def __init__(self, msg, data=None): super().__init__() @@ -42,6 +44,8 @@ def ASSERT_IN(a1, a2): raise ParseException("ASSERTION_FAILED: Expected {} to not be in {}".format(a1, a2), (a1, a2)) +# MMU Exceptions + class MemoryAccessException(RiscemuBaseException): def __init__(self, msg, addr, size, op): super(MemoryAccessException, self).__init__() @@ -71,6 +75,8 @@ class OutOfMemoryEsception(RiscemuBaseException): ) +# CPU Exceptions + class UnimplementedInstruction(RiscemuBaseException): def __init__(self, ins: 'LoadedInstruction'): self.ins = ins @@ -81,6 +87,7 @@ class UnimplementedInstruction(RiscemuBaseException): repr(self.ins) ) + class InvalidRegisterException(RiscemuBaseException): def __init__(self, reg): self.reg = reg @@ -91,5 +98,18 @@ class InvalidRegisterException(RiscemuBaseException): self.reg ) + def INS_NOT_IMPLEMENTED(ins): - raise UnimplementedInstruction(ins) \ No newline at end of file + raise UnimplementedInstruction(ins) + + +class NumberFormatException(RiscemuBaseException): + def __init__(self, msg): + super().__init__() + self.msg = msg + + def message(self): + return "{}({})".format( + self.__class__.__name__, + self.msg + ) \ No newline at end of file diff --git a/riscemu/helpers.py b/riscemu/helpers.py index ac8b31c..caf2561 100644 --- a/riscemu/helpers.py +++ b/riscemu/helpers.py @@ -1,3 +1,5 @@ +from .Exceptions import NumberFormatException + def align_addr(addr: int, to_bytes: int = 8): """ align an address to `to_bytes` (meaning addr & to_bytes = 0) @@ -14,16 +16,18 @@ def parse_numeric_argument(arg: str): return int(arg) -def int_to_bytes(val, bytes=4): +def int_to_bytes(val, bytes=4, unsigned=False): """ int -> byte (two's complement) """ + if unsigned and val < 0: + raise NumberFormatException("unsigned negative number!") return bytearray([ (val >> ((bytes-i-1) * 8)) & 0xFF for i in range(bytes) ]) -def int_from_bytes(bytes): +def int_from_bytes(bytes, unsigned=False): """ byte -> int (two's complement) """ @@ -32,10 +36,11 @@ def int_from_bytes(bytes): num = num << 8 num += b sign = num >> (len(bytes) * 8 - 1) - if sign: + if sign and not unsigned: return num - 2 ** (8 * len(bytes)) return num + FMT_ORANGE = '\033[33m' FMT_GRAY = '\033[37m' FMT_BOLD = '\033[1m'