Skip to content

Commit dc156bb

Browse files
committed
Refactor string method
1 parent ba12100 commit dc156bb

File tree

1 file changed

+30
-15
lines changed

1 file changed

+30
-15
lines changed

qiling/os/memory.py

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,22 +46,37 @@ def __init__(self, ql: Qiling):
4646
self.max_addr = max_addr
4747
self.max_mem_addr = max_addr
4848

49+
def __read_string(self, addr: int) -> str:
50+
ret = bytearray()
51+
c = self.read(addr, 1)
4952

50-
def string(self, addr, value=None ,encoding='utf-8'):
51-
if value == None:
52-
ret = ""
53-
c = self.read(addr, 1)[0]
54-
read_bytes = 1
55-
56-
while c != 0x0:
57-
ret += chr(c)
58-
c = self.read(addr + read_bytes, 1)[0]
59-
read_bytes += 1
60-
return ret
61-
else:
62-
string_bytes = bytes(value, encoding) + b'\x00'
63-
self.write(addr, string_bytes)
64-
return None
53+
while c[0]:
54+
ret += c
55+
addr += 1
56+
c = self.read(addr, 1)
57+
58+
return ret.decode()
59+
60+
def __write_string(self, addr: int, s: str, encoding: str):
61+
self.write(addr, bytes(s, encoding) + b'\x00')
62+
63+
# TODO: this is an obsolete utility method that should not be used anymore
64+
# and here for backward compatibility. use QlOsUtils.read_cstring instead
65+
def string(self, addr: int, value=None, encoding='utf-8') -> Optional[str]:
66+
"""Read or write string to memory.
67+
68+
Args:
69+
addr: source / destination address
70+
value: string to write, or None if reading one from memory
71+
encoding: string encoding
72+
73+
Returns: null-terminated string read from memory, or None if wrote one
74+
"""
75+
76+
if value is None:
77+
return self.__read_string(addr)
78+
79+
self.__write_string(addr, value, encoding)
6580

6681
def add_mapinfo(self, mem_s: int, mem_e: int, mem_p: int, mem_info: str):
6782
tmp_map_info = []

0 commit comments

Comments
 (0)