diff options
author | Neil Schemenauer <nas-github@arctrix.com> | 2021-02-19 00:49:12 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-02-19 00:49:12 (GMT) |
commit | ffa55d21b4a86ad8b4a43a9f597151e526541130 (patch) | |
tree | 788adcfdf91d11c30cf92ae15e112b864819a734 /Tools/freeze | |
parent | 743932d50815edbe4ffd530ae091c53ae47dd34b (diff) | |
download | cpython-ffa55d21b4a86ad8b4a43a9f597151e526541130.zip cpython-ffa55d21b4a86ad8b4a43a9f597151e526541130.tar.gz cpython-ffa55d21b4a86ad8b4a43a9f597151e526541130.tar.bz2 |
bpo-39448: Add regen-frozen makefile target. (GH-18174)
Add the "regen-frozen" makefile target that regenerates the code for the
frozen __hello__ module.
Diffstat (limited to 'Tools/freeze')
-rw-r--r-- | Tools/freeze/regen_frozen.py | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/Tools/freeze/regen_frozen.py b/Tools/freeze/regen_frozen.py new file mode 100644 index 0000000..391182a --- /dev/null +++ b/Tools/freeze/regen_frozen.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +import sys +import os +import marshal + + +DIR = os.path.dirname(sys.argv[0]) +# source code for module to freeze +FILE = os.path.join(DIR, 'flag.py') +# C symbol to use for array holding frozen bytes +SYMBOL = 'M___hello__' + + +def get_module_code(filename): + """Compile 'filename' and return the module code as a marshalled byte + string. + """ + with open(filename, 'r') as fp: + src = fp.read() + co = compile(src, 'none', 'exec') + co_bytes = marshal.dumps(co) + return co_bytes + + +def gen_c_code(fp, co_bytes): + """Generate C code for the module code in 'co_bytes', write it to 'fp'. + """ + def write(*args, **kwargs): + print(*args, **kwargs, file=fp) + write('/* Generated with Tools/freeze/regen_frozen.py */') + write('static unsigned char %s[] = {' % SYMBOL, end='') + bytes_per_row = 13 + for i, opcode in enumerate(co_bytes): + if (i % bytes_per_row) == 0: + # start a new row + write() + write(' ', end='') + write('%d,' % opcode, end='') + write() + write('};') + + +def main(): + out_filename = sys.argv[1] + co_bytes = get_module_code(FILE) + with open(out_filename, 'w') as fp: + gen_c_code(fp, co_bytes) + + +if __name__ == '__main__': + main() |