Skip to content

Commit 50fc1b2

Browse files
committed
Generalize heap _find method
1 parent 0313312 commit 50fc1b2

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

qiling/os/memory.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -585,10 +585,10 @@ def size(self, addr: int) -> int:
585585
Returns: chunk size (in bytes), or 0 if no chunk starts at that address
586586
"""
587587

588-
for chunk in self.chunks:
589-
if addr == chunk.address and chunk.inuse:
590-
return chunk.size
591-
return 0
588+
# find used chunk starting at specified address
589+
chunk = self._find(addr, inuse=True)
590+
591+
return chunk.size if chunk else 0
592592

593593
def free(self, addr: int) -> bool:
594594
"""Free up memory at a specific address.
@@ -599,11 +599,15 @@ def free(self, addr: int) -> bool:
599599
Returns: True iff memory was freed successfully, False otherwise
600600
"""
601601

602-
for chunk in self.chunks:
603-
if addr == chunk.address and chunk.inuse:
604-
chunk.inuse = False
605-
return True
606-
return False
602+
# find used chunk starting at specified address
603+
chunk = self._find(addr, inuse=True)
604+
605+
if not chunk:
606+
return False
607+
608+
# clear in-use indication
609+
chunk.inuse = False
610+
return True
607611

608612
# clear all memory regions alloc
609613
def clear(self):
@@ -629,7 +633,7 @@ def _find(self, addr: int, inuse: bool = None) -> Optional[Chunk]:
629633
as required (if required), None if no such chunk was found
630634
"""
631635

632-
for chunk in self.chunks:
633-
if addr == chunk.address:
634-
return chunk
635-
return None
636+
# nullify the in-use check in case the caller doesn't care about it
637+
dontcare = True if inuse is None else False
638+
639+
return next((chunk for chunk in self.chunks if addr == chunk.address and (dontcare or chunk.inuse == inuse)), None)

0 commit comments

Comments
 (0)