Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/dwarffi/instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -1157,6 +1157,36 @@ def __gt__(self, other: Any) -> bool:
def __ge__(self, other: Any) -> bool:
return self.address >= (other.address if isinstance(other, Ptr) else other)

def __and__(self, other: int) -> int:
if not isinstance(other, int):
return NotImplemented
return self.address & other

def __rand__(self, other: int) -> int:
if not isinstance(other, int):
return NotImplemented
return other & self.address

def __or__(self, other: int) -> int:
if not isinstance(other, int):
return NotImplemented
return self.address | other

def __ror__(self, other: int) -> int:
if not isinstance(other, int):
return NotImplemented
return other | self.address

def __xor__(self, other: int) -> int:
if not isinstance(other, int):
return NotImplemented
return self.address ^ other

def __rxor__(self, other: int) -> int:
if not isinstance(other, int):
return NotImplemented
return other ^ self.address


class EnumInstance:
"""
Expand Down
30 changes: 30 additions & 0 deletions tests/test_magic_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,33 @@ def test_primitive_math(ffi_env: DFFI):
assert val > 50
assert val <= 100
assert val == 100

def test_ptr_tagged_and_page_alignment(ffi_env: DFFI):
"""
Simulate AArch64 tagged pointers and OS page alignment masking.
Verifies that complex bitwise logic chains evaluate correctly.
"""
d = ffi_env
# 64-bit pointer with a metadata tag in the top 8 bits
# Tag: 0xA5, True Address: 0x00007FFF80001234
tagged_addr = 0xA5007FFF80001234
ptr = d.t.int.ptr(tagged_addr)

# 1. Extract the tag (shift right 56 bits)
tag = (ptr & 0xFF00000000000000) >> 56
assert tag == 0xA5

# 2. Clear the tag to get the routable address
actual_addr = ptr & 0x00FFFFFFFFFFFFFF
assert actual_addr == 0x00007FFF80001234

# 3. Calculate 4KB Page alignment (Clear the bottom 12 bits)
# Python bitwise NOT on standard ints can be tricky with signs,
# so we explicitly mask the bits we want.
PAGE_MASK = 0xFFFFFFFFFFFFF000
page_base = actual_addr & PAGE_MASK
assert page_base == 0x00007FFF80001000

# 4. Isolate the offset within the page
page_offset = actual_addr & 0xFFF
assert page_offset == 0x234
Loading