From 4b9c5eb4b98a2898b746bfcee8febb02580d7b43 Mon Sep 17 00:00:00 2001 From: dusoleil Date: Mon, 13 Mar 2023 08:35:27 -0400 Subject: arch: Add explicit int conversions Signed-off-by: dusoleil Reviewed-by: Malfurious --- sploit/arch.py | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/sploit/arch.py b/sploit/arch.py index ac8ac14..36f48a4 100644 --- a/sploit/arch.py +++ b/sploit/arch.py @@ -21,12 +21,6 @@ predefined architectures: from dataclasses import dataclass -def btoi(b, signed=False): - return int.from_bytes(b, arch.endianness, signed=signed) - -def itob(i, signed=False): - return i.to_bytes(arch.wordsize, arch.endianness, signed=signed) - @dataclass(frozen=True) class Arch: """ @@ -54,3 +48,60 @@ ARM = Arch( 4, 'little', 8, b'\xe1\xa0\x00\x00') THUMB = Arch( 4, 'little', 8, b'\x46\xc0') arch = Arch(**x86_64.__dict__) + +def __int(i, signed=False, width=None): + # type conversion from int to int of given sign and width + width = width or arch.wordsize + bits = 8 * width + if signed: + sign_bit = 1 << (bits - 1) + return (i & (sign_bit - 1)) - (i & sign_bit) + else: + mask = (1 << bits) - 1 + return i & mask + +def sint(i): + """Convert given int to signed int of arch.wordsize width.""" + return __int(i, True) + +def uint(i): + """Convert given int to unsigned int of arch.wordsize width.""" + return __int(i, False) + +def int8(i): + """Convert given int to signed 8 bit int.""" + return __int(i, True, 1) + +def int16(i): + """Convert given int to signed 16 bit int.""" + return __int(i, True, 2) + +def int32(i): + """Convert given int to signed 32 bit int.""" + return __int(i, True, 4) + +def int64(i): + """Convert given int to signed 64 bit int.""" + return __int(i, True, 8) + +def uint8(i): + """Convert given int to unsigned 8 bit int.""" + return __int(i, False, 1) + +def uint16(i): + """Convert given int to unsigned 16 bit int.""" + return __int(i, False, 2) + +def uint32(i): + """Convert given int to unsigned 32 bit int.""" + return __int(i, False, 4) + +def uint64(i): + """Convert given int to unsigned 64 bit int.""" + return __int(i, False, 8) + +def btoi(b, signed=False): + return int.from_bytes(b, arch.endianness, signed=signed) + +def itob(i, signed=False): + return i.to_bytes(arch.wordsize, arch.endianness, signed=signed) -- cgit v1.2.3