ยปCore Development>Code coverage>Tools/freeze/makefreeze.py

Python code coverage for Tools/freeze/makefreeze.py

#countcontent
1n/aimport marshal
2n/aimport bkfile
3n/a
4n/a
5n/a# Write a file containing frozen code for the modules in the dictionary.
6n/a
7n/aheader = """
8n/a#include "Python.h"
9n/a
10n/astatic struct _frozen _PyImport_FrozenModules[] = {
11n/a"""
12n/atrailer = """\
13n/a {0, 0, 0} /* sentinel */
14n/a};
15n/a"""
16n/a
17n/a# if __debug__ == 0 (i.e. -O option given), set Py_OptimizeFlag in frozen app.
18n/adefault_entry_point = """
19n/aint
20n/amain(int argc, char **argv)
21n/a{
22n/a extern int Py_FrozenMain(int, char **);
23n/a""" + ((not __debug__ and """
24n/a Py_OptimizeFlag++;
25n/a""") or "") + """
26n/a PyImport_FrozenModules = _PyImport_FrozenModules;
27n/a return Py_FrozenMain(argc, argv);
28n/a}
29n/a
30n/a"""
31n/a
32n/adef makefreeze(base, dict, debug=0, entry_point=None, fail_import=()):
33n/a if entry_point is None: entry_point = default_entry_point
34n/a done = []
35n/a files = []
36n/a mods = sorted(dict.keys())
37n/a for mod in mods:
38n/a m = dict[mod]
39n/a mangled = "__".join(mod.split("."))
40n/a if m.__code__:
41n/a file = 'M_' + mangled + '.c'
42n/a with bkfile.open(base + file, 'w') as outfp:
43n/a files.append(file)
44n/a if debug:
45n/a print("freezing", mod, "...")
46n/a str = marshal.dumps(m.__code__)
47n/a size = len(str)
48n/a if m.__path__:
49n/a # Indicate package by negative size
50n/a size = -size
51n/a done.append((mod, mangled, size))
52n/a writecode(outfp, mangled, str)
53n/a if debug:
54n/a print("generating table of frozen modules")
55n/a with bkfile.open(base + 'frozen.c', 'w') as outfp:
56n/a for mod, mangled, size in done:
57n/a outfp.write('extern unsigned char M_%s[];\n' % mangled)
58n/a outfp.write(header)
59n/a for mod, mangled, size in done:
60n/a outfp.write('\t{"%s", M_%s, %d},\n' % (mod, mangled, size))
61n/a outfp.write('\n')
62n/a # The following modules have a NULL code pointer, indicating
63n/a # that the frozen program should not search for them on the host
64n/a # system. Importing them will *always* raise an ImportError.
65n/a # The zero value size is never used.
66n/a for mod in fail_import:
67n/a outfp.write('\t{"%s", NULL, 0},\n' % (mod,))
68n/a outfp.write(trailer)
69n/a outfp.write(entry_point)
70n/a return files
71n/a
72n/a
73n/a
74n/a# Write a C initializer for a module containing the frozen python code.
75n/a# The array is called M_<mod>.
76n/a
77n/adef writecode(outfp, mod, str):
78n/a outfp.write('unsigned char M_%s[] = {' % mod)
79n/a for i in range(0, len(str), 16):
80n/a outfp.write('\n\t')
81n/a for c in bytes(str[i:i+16]):
82n/a outfp.write('%d,' % c)
83n/a outfp.write('\n};\n')
84n/a
85n/a## def writecode(outfp, mod, str):
86n/a## outfp.write('unsigned char M_%s[%d] = "%s";\n' % (mod, len(str),
87n/a## '\\"'.join(map(lambda s: repr(s)[1:-1], str.split('"')))))