From ac7f4a52d61dca66d0ebc791c758430f291fed3a Mon Sep 17 00:00:00 2001 From: dusoleil Date: Sat, 4 Mar 2023 13:59:20 -0500 Subject: arch: Use dataclass instead of namedtuple Python's dataclass annotation gives us a nice way to cleanly and concisely define our list of supported architectures similar to namedtuple. Unlike namedtuple, though, dataclass gives us an actual class that is significantly more feature rich and even allows us to add functionality. In general, these are meant to be like const records of info about an architecture, so we use frozen=True to enforce some const correctness. There were some issues when involving other classes for the ActiveArch feature (subclassing and composition both had their respective issues), so I'm removing __ActiveArch__ and putting a set() method directly on Arch. This method will copy a given Arch into the self object. This technically breaks const correctness as this does modify the object, but it is intended to only be used on a single sentinel Arch that represents the active arch. This arch is initialized with x86_64 by default. Signed-off-by: dusoleil Reviewed-by: Malfurious --- sploit/arch.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/sploit/arch.py b/sploit/arch.py index e5de2ce..5575b05 100644 --- a/sploit/arch.py +++ b/sploit/arch.py @@ -1,4 +1,4 @@ -from collections import namedtuple as nt +from dataclasses import dataclass def btoi(b, signed=False): return int.from_bytes(b, arch.endianness, signed=signed) @@ -6,16 +6,18 @@ def btoi(b, signed=False): def itob(i, signed=False): return i.to_bytes(arch.wordsize, arch.endianness, signed=signed) -Arch = nt("Arch", "wordsize endianness alignment nopcode") -x86 = Arch( 4, 'little', 16, b'\x90') -x86_64 = Arch( 8, 'little', 16, b'\x90') -ARM = Arch( 4, 'little', 8, b'\xe1\xa0\x00\x00') -THUMB = Arch( 4, 'little', 8, b'\x46\xc0') +@dataclass(frozen=True) +class Arch: + wordsize: int + endianness: str + alignment: int + nopcode: bytes + def set(self,k): + self.__dict__.update(k.__dict__) -class __ActiveArch__: - __arch = x86_64 - def __getattr__(self,k): - return getattr(self.__arch,k) - def set(self,a): - self.__arch = a -arch = __ActiveArch__() +x86 = Arch( 4, 'little', 16, b'\x90') +x86_64 = Arch( 8, 'little', 16, b'\x90') +ARM = Arch( 4, 'little', 8, b'\xe1\xa0\x00\x00') +THUMB = Arch( 4, 'little', 8, b'\x46\xc0') + +arch = Arch(**x86_64.__dict__) -- cgit v1.2.3