Add a default encoding parameter to struct for decoding strings.

This commit is contained in:
Jennifer Taylor
2021-08-28 17:08:07 +00:00
parent c6bd3b4c72
commit 866ef4db52

View File

@@ -19,8 +19,9 @@ class LineNumber:
class StructPrinter:
def __init__(self, data: bytes) -> None:
def __init__(self, data: bytes, default_encoding: str="ascii") -> None:
self.data = data
self.default_encoding = default_encoding
self.pe = PEFile(data)
def parse_format_spec(self, fmt: str) -> Tuple[str, List[Any]]:
@@ -172,7 +173,10 @@ class StructPrinter:
# Hex makes no sense here
if dohex:
raise Exception("Cannot display string as hex!")
line.append(bs.decode('ascii'))
# TODO: We should have an optional encoding specifier that can be added to "z"
# so that individual entries in strings can be overridden from the default.
line.append(bs.decode(self.default_encoding))
else:
size = struct.calcsize(prefix + spec)
chunk = self.data[offset:(offset + size)]
@@ -259,6 +263,12 @@ Ih&h = Decodes an array of structures containing an unsigned integer and two sho
type=str,
default=None,
)
parser.add_argument(
"--encoding",
help="Encoding to use for strings, such as 'ascii', 'utf-8' or 'shift-jis'.",
default='ascii',
type=str,
)
parser.add_argument(
"--format",
help=(
@@ -301,7 +311,7 @@ Ih&h = Decodes an array of structures containing an unsigned integer and two sho
else:
return repr(obj)
printer = StructPrinter(data)
printer = StructPrinter(data, default_encoding=args.encoding)
lines = printer.parse_struct(args.start, args.end, args.count, args.format)
for i, line in enumerate(lines):
print(", ".join(__str(entry, i) for entry in line))