Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support memory slicing #1151

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Changes from 3 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
25 changes: 24 additions & 1 deletion qiling/os/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
#

import os, re
from typing import Any, Callable, List, MutableSequence, Optional, Sequence, Tuple
from typing import Any, Callable, List, MutableSequence, Optional, Sequence, Tuple, Union

from unicorn import UC_PROT_NONE, UC_PROT_READ, UC_PROT_WRITE, UC_PROT_EXEC, UC_PROT_ALL

Expand Down Expand Up @@ -63,6 +63,29 @@ def __read_string(self, addr: int) -> str:
def __write_string(self, addr: int, s: str, encoding: str):
self.write(addr, bytes(s, encoding) + b'\x00')

def __getitem__(self, key: Union[slice, int]) -> bytearray:
if isinstance(key, slice):
start = key.start
stop = key.stop
step = key.step

if step is not None and step != 1:
# step != 1 means we have to do copy, don't allow it.
raise IndexError("Only support slicing continous memory")

return self.ql.mem.read(start, stop - start)
wtdcode marked this conversation as resolved.
Show resolved Hide resolved
elif isinstance(key, int):
return self.ql.mem.read(key, 1)
wtdcode marked this conversation as resolved.
Show resolved Hide resolved
else:
raise KeyError("Wrong type of key")

def __setitem__(self, key: Union[slice, int], value: Union[bytes, bytearray]):
wtdcode marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(key, int):
wtdcode marked this conversation as resolved.
Show resolved Hide resolved
self.ql.mem.write(key, value)
else:
# Slicing doesn't make sense in writing.
elicn marked this conversation as resolved.
Show resolved Hide resolved
raise KeyError("Wrong type of key")

# TODO: this is an obsolete utility method that should not be used anymore
# and here for backward compatibility. use QlOsUtils.read_cstring instead
def string(self, addr: int, value=None, encoding='utf-8') -> Optional[str]:
Expand Down