Skip to content

tools/mpy-tool.py: Allow dumping MPY segments into their own files. #17306

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
49 changes: 49 additions & 0 deletions tools/mpy-tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -1765,6 +1765,44 @@ def copy_section(file, offset, offset2):
f.write(merged_mpy)


def extract_segments(compiled_modules, basename, kinds_arg):
import re

kind_str = ("META", "QSTR", "OBJ", "CODE")
kinds = set()
if kinds_arg is not None:
for kind in kinds_arg.upper().split(","):
if kind in kind_str:
kinds.add(kind)
else:
raise Exception('unknown segment kind "%s"' % (kind,))
segments = []
for module in compiled_modules:
for segment in module.mpy_segments:
if not kinds or kind_str[segment.kind] in kinds:
segments.append((module.mpy_source_file, module.source_file.str, segment))
count_len = len(str(len(segments)))
sanitiser = re.compile("[^a-zA-Z0-9_.-]")
for counter, entry in enumerate(segments):
file_name, source_file, segment = entry
output_name = (
basename
+ "_"
+ str(counter).rjust(count_len, "0")
+ "_"
+ sanitiser.sub("_", source_file)
+ "_"
+ kind_str[segment.kind]
+ "_"
+ sanitiser.sub("_", str(segment.name))
+ ".bin"
)
with open(file_name, "rb") as source:
with open(output_name, "wb") as output:
source.seek(segment.start)
output.write(source.read(segment.end - segment.start))


def main(args=None):
global global_qstrs

Expand All @@ -1781,6 +1819,14 @@ def main(args=None):
cmd_parser.add_argument(
"--merge", action="store_true", help="merge multiple .mpy files into one"
)
cmd_parser.add_argument(
"-e", "--extract", metavar="BASE", type=str, help="write segments into separate files"
)
cmd_parser.add_argument(
"--extract-only",
metavar="KIND[,...]",
help="extract only segments of the given type (meta, qstr, obj, code)",
)
cmd_parser.add_argument("-q", "--qstr-header", help="qstr header file to freeze against")
cmd_parser.add_argument(
"-mlongint-impl",
Expand Down Expand Up @@ -1848,6 +1894,9 @@ def main(args=None):
if args.merge:
merge_mpy(compiled_modules, args.output)

if args.extract:
extract_segments(compiled_modules, args.extract, args.extract_only)


if __name__ == "__main__":
main()
Loading