Debian Codegraph @

Tools/build/deepfreeze.py

raw
1 """Deep freeze
2
3 The script may be executed by _bootstrap_python interpreter.
4 Shared library extension modules are not available in that case.
5 Requires 3.11+ to be executed,
6 because relies on `code.co_qualname` and `code.co_exceptiontable`.
7 """
8
9 from __future__ import annotations
10
11 import argparse
12 import builtins
13 import collections
14 import contextlib
15 import os
16 import re
17 import time
18 import types
19 import umarshal
20
21 TYPE_CHECKING = False
22 if TYPE_CHECKING:
23 from collections.abc import Iterator
24 from typing import Any, TextIO, Dict, FrozenSet, TextIO, Tuple
25
26 ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
27
28 verbose = False
29
30 # This must be kept in sync with Tools/cases_generator/analyzer.py
31 RESUME = 149
32
33 def isprintable(b: bytes) -> bool:
34 return all(0x20 <= c < 0x7f for c in b)
35
36
37 def make_string_literal(b: bytes) -> str:
38 res = ['"']
39 if isprintable(b):
40 res.append(b.decode("ascii").replace("\\", "\\\\").replace("\"", "\\\""))
41 else:
42 for i in b:
43 res.append(f"\\x{i:02x}")
44 res.append('"')
45 return "".join(res)
46
47
48 CO_FAST_LOCAL = 0x20
49 CO_FAST_CELL = 0x40
50 CO_FAST_FREE = 0x80
51
52 next_code_version = 1
53
54 def get_localsplus(code: types.CodeType) -> tuple[tuple[str, ...], bytes]:
55 a: collections.defaultdict[str, int] = collections.defaultdict(int)
56 for name in code.co_varnames:
57 a[name] |= CO_FAST_LOCAL
58 for name in code.co_cellvars:
59 a[name] |= CO_FAST_CELL
60 for name in code.co_freevars:
61 a[name] |= CO_FAST_FREE
62 return tuple(a.keys()), bytes(a.values())
63
64
65 def get_localsplus_counts(code: types.CodeType,
66 names: Tuple[str, ...],
67 kinds: bytes) -> Tuple[int, int, int]:
68 nlocals = 0
69 ncellvars = 0
70 nfreevars = 0
71 assert len(names) == len(kinds)
72 for name, kind in zip(names, kinds):
73 if kind & CO_FAST_LOCAL:
74 nlocals += 1
75 if kind & CO_FAST_CELL:
76 ncellvars += 1
77 elif kind & CO_FAST_CELL:
78 ncellvars += 1
79 elif kind & CO_FAST_FREE:
80 nfreevars += 1
81 assert nlocals == len(code.co_varnames) == code.co_nlocals, \
82 (nlocals, len(code.co_varnames), code.co_nlocals)
83 assert ncellvars == len(code.co_cellvars)
84 assert nfreevars == len(code.co_freevars)
85 return nlocals, ncellvars, nfreevars
86
87
88 PyUnicode_1BYTE_KIND = 1
89 PyUnicode_2BYTE_KIND = 2
90 PyUnicode_4BYTE_KIND = 4
91
92
93 def analyze_character_width(s: str) -> Tuple[int, bool]:
94 maxchar = ' '
95 for c in s:
96 maxchar = max(maxchar, c)
97 ascii = False
98 if maxchar <= '\xFF':
99 kind = PyUnicode_1BYTE_KIND
100 ascii = maxchar <= '\x7F'
101 elif maxchar <= '\uFFFF':
102 kind = PyUnicode_2BYTE_KIND
103 else:
104 kind = PyUnicode_4BYTE_KIND
105 return kind, ascii
106
107
108 def removesuffix(base: str, suffix: str) -> str:
109 if base.endswith(suffix):
110 return base[:len(base) - len(suffix)]
111 return base
112
113 class Printer:
114
115 def __init__(self, file: TextIO) -> None:
116 self.level = 0
117 self.file = file
118 self.cache: Dict[tuple[type, object, str], str] = {}
119 self.hits, self.misses = 0, 0
120 self.finis: list[str] = []
121 self.inits: list[str] = []
122 self.identifiers, self.strings = self.get_identifiers_and_strings()
123 self.write('#include "Python.h"')
124 self.write('#include "internal/pycore_object.h"')
125 self.write('#include "internal/pycore_gc.h"')
126 self.write('#include "internal/pycore_code.h"')
127 self.write('#include "internal/pycore_frame.h"')
128 self.write('#include "internal/pycore_long.h"')
129 self.write("")
130
131 def get_identifiers_and_strings(self) -> tuple[set[str], dict[str, str]]:
132 filename = os.path.join(ROOT, "Include", "internal", "pycore_global_strings.h")
133 with open(filename) as fp:
134 lines = fp.readlines()
135 identifiers: set[str] = set()
136 strings: dict[str, str] = {}
137 for line in lines:
138 if m := re.search(r"STRUCT_FOR_ID\((\w+)\)", line):
139 identifiers.add(m.group(1))
140 if m := re.search(r'STRUCT_FOR_STR\((\w+), "(.*?)"\)', line):
141 strings[m.group(2)] = m.group(1)
142 return identifiers, strings
143
144 @contextlib.contextmanager
145 def indent(self) -> Iterator[None]:
146 save_level = self.level
147 try:
148 self.level += 1
149 yield
150 finally:
151 self.level = save_level
152
153 def write(self, arg: str) -> None:
154 self.file.writelines((" "*self.level, arg, "\n"))
155
156 @contextlib.contextmanager
157 def block(self, prefix: str, suffix: str = "") -> Iterator[None]:
158 self.write(prefix + " {")
159 with self.indent():
160 yield
161 self.write("}" + suffix)
162
163 def object_head(self, typename: str) -> None:
164 self.write(f".ob_base = _PyObject_HEAD_INIT(&{typename}),")
165
166 def object_var_head(self, typename: str, size: int) -> None:
167 self.write(f".ob_base = _PyVarObject_HEAD_INIT(&{typename}, {size}),")
168
169 def field(self, obj: object, name: str) -> None:
170 self.write(f".{name} = {getattr(obj, name)},")
171
172 def generate_bytes(self, name: str, b: bytes) -> str:
173 if b == b"":
174 return "(PyObject *)&_Py_SINGLETON(bytes_empty)"
175 if len(b) == 1:
176 return f"(PyObject *)&_Py_SINGLETON(bytes_characters[{b[0]}])"
177 self.write("static")
178 with self.indent():
179 with self.block("struct"):
180 self.write("PyObject_VAR_HEAD")
181 self.write("Py_hash_t ob_shash;")
182 self.write(f"char ob_sval[{len(b) + 1}];")
183 with self.block(f"{name} =", ";"):
184 self.object_var_head("PyBytes_Type", len(b))
185 self.write(".ob_shash = -1,")
186 self.write(f".ob_sval = {make_string_literal(b)},")
187 return f"& {name}.ob_base.ob_base"
188
189 def generate_unicode(self, name: str, s: str) -> str:
190 if s in self.strings:
191 return f"&_Py_STR({self.strings[s]})"
192 if s in self.identifiers:
193 return f"&_Py_ID({s})"
194 if len(s) == 1:
195 c = ord(s)
196 if c < 128:
197 return f"(PyObject *)&_Py_SINGLETON(strings).ascii[{c}]"
198 elif c < 256:
199 return f"(PyObject *)&_Py_SINGLETON(strings).latin1[{c - 128}]"
200 if re.match(r'\A[A-Za-z0-9_]+\Z', s):
201 name = f"const_str_{s}"
202 kind, ascii = analyze_character_width(s)
203 if kind == PyUnicode_1BYTE_KIND:
204 datatype = "uint8_t"
205 elif kind == PyUnicode_2BYTE_KIND:
206 datatype = "uint16_t"
207 else:
208 datatype = "uint32_t"
209 self.write("static")
210 with self.indent():
211 with self.block("struct"):
212 if ascii:
213 self.write("PyASCIIObject _ascii;")
214 else:
215 self.write("PyCompactUnicodeObject _compact;")
216 self.write(f"{datatype} _data[{len(s)+1}];")
217 with self.block(f"{name} =", ";"):
218 if ascii:
219 with self.block("._ascii =", ","):
220 self.object_head("PyUnicode_Type")
221 self.write(f".length = {len(s)},")
222 self.write(".hash = -1,")
223 with self.block(".state =", ","):
224 self.write(".kind = 1,")
225 self.write(".compact = 1,")
226 self.write(".ascii = 1,")
227 self.write(".statically_allocated = 1,")
228 self.write(f"._data = {make_string_literal(s.encode('ascii'))},")
229 return f"& {name}._ascii.ob_base"
230 else:
231 with self.block("._compact =", ","):
232 with self.block("._base =", ","):
233 self.object_head("PyUnicode_Type")
234 self.write(f".length = {len(s)},")
235 self.write(".hash = -1,")
236 with self.block(".state =", ","):
237 self.write(f".kind = {kind},")
238 self.write(".compact = 1,")
239 self.write(".ascii = 0,")
240 self.write(".statically_allocated = 1,")
241 utf8 = s.encode('utf-8')
242 self.write(f'.utf8 = {make_string_literal(utf8)},')
243 self.write(f'.utf8_length = {len(utf8)},')
244 with self.block(f"._data =", ","):
245 for i in range(0, len(s), 16):
246 data = s[i:i+16]
247 self.write(", ".join(map(str, map(ord, data))) + ",")
248 return f"& {name}._compact._base.ob_base"
249
250
251 def generate_code(self, name: str, code: types.CodeType) -> str:
252 global next_code_version
253 # The ordering here matches PyCode_NewWithPosOnlyArgs()
254 # (but see below).
255 co_consts = self.generate(name + "_consts", code.co_consts)
256 co_names = self.generate(name + "_names", code.co_names)
257 co_filename = self.generate(name + "_filename", code.co_filename)
258 co_name = self.generate(name + "_name", code.co_name)
259 co_linetable = self.generate(name + "_linetable", code.co_linetable)
260 # We use 3.10 for type checking, but this module requires 3.11
261 # TODO: bump python version for this script.
262 co_qualname = self.generate(
263 name + "_qualname",
264 code.co_qualname, # type: ignore[attr-defined]
265 )
266 co_exceptiontable = self.generate(
267 name + "_exceptiontable",
268 code.co_exceptiontable, # type: ignore[attr-defined]
269 )
270 # These fields are not directly accessible
271 localsplusnames, localspluskinds = get_localsplus(code)
272 co_localsplusnames = self.generate(name + "_localsplusnames", localsplusnames)
273 co_localspluskinds = self.generate(name + "_localspluskinds", localspluskinds)
274 # Derived values
275 nlocals, ncellvars, nfreevars = \
276 get_localsplus_counts(code, localsplusnames, localspluskinds)
277 co_code_adaptive = make_string_literal(code.co_code)
278 self.write("static")
279 with self.indent():
280 self.write(f"struct _PyCode_DEF({len(code.co_code)})")
281 with self.block(f"{name} =", ";"):
282 self.object_var_head("PyCode_Type", len(code.co_code) // 2)
283 # But the ordering here must match that in cpython/code.h
284 # (which is a pain because we tend to reorder those for perf)
285 # otherwise MSVC doesn't like it.
286 self.write(f".co_consts = {co_consts},")
287 self.write(f".co_names = {co_names},")
288 self.write(f".co_exceptiontable = {co_exceptiontable},")
289 self.field(code, "co_flags")
290 self.field(code, "co_argcount")
291 self.field(code, "co_posonlyargcount")
292 self.field(code, "co_kwonlyargcount")
293 # The following should remain in sync with _PyFrame_NumSlotsForCodeObject
294 self.write(f".co_framesize = {code.co_stacksize + len(localsplusnames)} + FRAME_SPECIALS_SIZE,")
295 self.field(code, "co_stacksize")
296 self.field(code, "co_firstlineno")
297 self.write(f".co_nlocalsplus = {len(localsplusnames)},")
298 self.field(code, "co_nlocals")
299 self.write(f".co_ncellvars = {ncellvars},")
300 self.write(f".co_nfreevars = {nfreevars},")
301 self.write(f".co_version = {next_code_version},")
302 next_code_version += 1
303 self.write(f".co_localsplusnames = {co_localsplusnames},")
304 self.write(f".co_localspluskinds = {co_localspluskinds},")
305 self.write(f".co_filename = {co_filename},")
306 self.write(f".co_name = {co_name},")
307 self.write(f".co_qualname = {co_qualname},")
308 self.write(f".co_linetable = {co_linetable},")
309 self.write(f"._co_cached = NULL,")
310 self.write(f".co_code_adaptive = {co_code_adaptive},")
311 first_traceable = 0
312 for op in code.co_code[::2]:
313 if op == RESUME:
314 break
315 first_traceable += 1
316 self.write(f"._co_firsttraceable = {first_traceable},")
317 name_as_code = f"(PyCodeObject *)&{name}"
318 self.finis.append(f"_PyStaticCode_Fini({name_as_code});")
319 self.inits.append(f"_PyStaticCode_Init({name_as_code})")
320 return f"& {name}.ob_base.ob_base"
321
322 def generate_tuple(self, name: str, t: Tuple[object, ...]) -> str:
323 if len(t) == 0:
324 return f"(PyObject *)& _Py_SINGLETON(tuple_empty)"
325 items = [self.generate(f"{name}_{i}", it) for i, it in enumerate(t)]
326 self.write("static")
327 with self.indent():
328 with self.block("struct"):
329 self.write("PyGC_Head _gc_head;")
330 with self.block("struct", "_object;"):
331 self.write("PyObject_VAR_HEAD")
332 if t:
333 self.write(f"PyObject *ob_item[{len(t)}];")
334 with self.block(f"{name} =", ";"):
335 with self.block("._object =", ","):
336 self.object_var_head("PyTuple_Type", len(t))
337 if items:
338 with self.block(f".ob_item =", ","):
339 for item in items:
340 self.write(item + ",")
341 return f"& {name}._object.ob_base.ob_base"
342
343 def _generate_int_for_bits(self, name: str, i: int, digit: int) -> None:
344 sign = (i > 0) - (i < 0)
345 i = abs(i)
346 digits: list[int] = []
347 while i:
348 i, rem = divmod(i, digit)
349 digits.append(rem)
350 self.write("static")
351 with self.indent():
352 with self.block("struct"):
353 self.write("PyObject ob_base;")
354 self.write("uintptr_t lv_tag;")
355 self.write(f"digit ob_digit[{max(1, len(digits))}];")
356 with self.block(f"{name} =", ";"):
357 self.object_head("PyLong_Type")
358 self.write(f".lv_tag = TAG_FROM_SIGN_AND_SIZE({sign}, {len(digits)}),")
359 if digits:
360 ds = ", ".join(map(str, digits))
361 self.write(f".ob_digit = {{ {ds} }},")
362
363 def generate_int(self, name: str, i: int) -> str:
364 if -5 <= i <= 256:
365 return f"(PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS + {i}]"
366 if i >= 0:
367 name = f"const_int_{i}"
368 else:
369 name = f"const_int_negative_{abs(i)}"
370 if abs(i) < 2**15:
371 self._generate_int_for_bits(name, i, 2**15)
372 else:
373 connective = "if"
374 for bits_in_digit in 15, 30:
375 self.write(f"#{connective} PYLONG_BITS_IN_DIGIT == {bits_in_digit}")
376 self._generate_int_for_bits(name, i, 2**bits_in_digit)
377 connective = "elif"
378 self.write("#else")
379 self.write('#error "PYLONG_BITS_IN_DIGIT should be 15 or 30"')
380 self.write("#endif")
381 # If neither clause applies, it won't compile
382 return f"& {name}.ob_base"
383
384 def generate_float(self, name: str, x: float) -> str:
385 with self.block(f"static PyFloatObject {name} =", ";"):
386 self.object_head("PyFloat_Type")
387 self.write(f".ob_fval = {x},")
388 return f"&{name}.ob_base"
389
390 def generate_complex(self, name: str, z: complex) -> str:
391 with self.block(f"static PyComplexObject {name} =", ";"):
392 self.object_head("PyComplex_Type")
393 self.write(f".cval = {{ {z.real}, {z.imag} }},")
394 return f"&{name}.ob_base"
395
396 def generate_frozenset(self, name: str, fs: FrozenSet[Any]) -> str:
397 try:
398 fs_sorted = sorted(fs)
399 except TypeError:
400 # frozen set with incompatible types, fallback to repr()
401 fs_sorted = sorted(fs, key=repr)
402 ret = self.generate_tuple(name, tuple(fs_sorted))
403 self.write("// TODO: The above tuple should be a frozenset")
404 return ret
405
406 def generate_file(self, module: str, code: object)-> None:
407 module = module.replace(".", "_")
408 self.generate(f"{module}_toplevel", code)
409 self.write(EPILOGUE.format(name=module))
410
411 def generate(self, name: str, obj: object) -> str:
412 # Use repr() in the key to distinguish -0.0 from +0.0
413 key = (type(obj), obj, repr(obj))
414 if key in self.cache:
415 self.hits += 1
416 # print(f"Cache hit {key!r:.40}: {self.cache[key]!r:.40}")
417 return self.cache[key]
418 self.misses += 1
419 if isinstance(obj, types.CodeType) :
420 val = self.generate_code(name, obj)
421 elif isinstance(obj, tuple):
422 val = self.generate_tuple(name, obj)
423 elif isinstance(obj, str):
424 val = self.generate_unicode(name, obj)
425 elif isinstance(obj, bytes):
426 val = self.generate_bytes(name, obj)
427 elif obj is True:
428 return "Py_True"
429 elif obj is False:
430 return "Py_False"
431 elif isinstance(obj, int):
432 val = self.generate_int(name, obj)
433 elif isinstance(obj, float):
434 val = self.generate_float(name, obj)
435 elif isinstance(obj, complex):
436 val = self.generate_complex(name, obj)
437 elif isinstance(obj, frozenset):
438 val = self.generate_frozenset(name, obj)
439 elif obj is builtins.Ellipsis:
440 return "Py_Ellipsis"
441 elif obj is None:
442 return "Py_None"
443 else:
444 raise TypeError(
445 f"Cannot generate code for {type(obj).__name__} object")
446 # print(f"Cache store {key!r:.40}: {val!r:.40}")
447 self.cache[key] = val
448 return val
449
450
451 EPILOGUE = """
452 PyObject *
453 _Py_get_{name}_toplevel(void)
454 {{
455 return Py_NewRef((PyObject *) &{name}_toplevel);
456 }}
457 """
458
459 FROZEN_COMMENT_C = "/* Auto-generated by Programs/_freeze_module.c */"
460 FROZEN_COMMENT_PY = "/* Auto-generated by Programs/_freeze_module.py */"
461
462 FROZEN_DATA_LINE = r"\s*(\d+,\s*)+\s*"
463
464
465 def is_frozen_header(source: str) -> bool:
466 return source.startswith((FROZEN_COMMENT_C, FROZEN_COMMENT_PY))
467
468
469 def decode_frozen_data(source: str) -> types.CodeType:
470 values: list[int] = []
471 for line in source.splitlines():
472 if re.match(FROZEN_DATA_LINE, line):
473 values.extend([int(x) for x in line.split(",") if x.strip()])
474 data = bytes(values)
475 return umarshal.loads(data) # type: ignore[no-any-return]
476
477
478 def generate(args: list[str], output: TextIO) -> None:
479 printer = Printer(output)
480 for arg in args:
481 file, modname = arg.rsplit(':', 1)
482 with open(file, "r", encoding="utf8") as fd:
483 source = fd.read()
484 if is_frozen_header(source):
485 code = decode_frozen_data(source)
486 else:
487 code = compile(fd.read(), f"<frozen {modname}>", "exec")
488 printer.generate_file(modname, code)
489 with printer.block(f"void\n_Py_Deepfreeze_Fini(void)"):
490 for p in printer.finis:
491 printer.write(p)
492 with printer.block(f"int\n_Py_Deepfreeze_Init(void)"):
493 for p in printer.inits:
494 with printer.block(f"if ({p} < 0)"):
495 printer.write("return -1;")
496 printer.write("return 0;")
497 printer.write(f"\nuint32_t _Py_next_func_version = {next_code_version};\n")
498 if verbose:
499 print(f"Cache hits: {printer.hits}, misses: {printer.misses}")
500
501
502 parser = argparse.ArgumentParser()
503 parser.add_argument("-o", "--output", help="Defaults to deepfreeze.c", default="deepfreeze.c")
504 parser.add_argument("-v", "--verbose", action="store_true", help="Print diagnostics")
505 group = parser.add_mutually_exclusive_group(required=True)
506 group.add_argument("-f", "--file", help="read rule lines from a file")
507 group.add_argument('args', nargs="*", default=(),
508 help="Input file and module name (required) in file:modname format")
509
510 @contextlib.contextmanager
511 def report_time(label: str) -> Iterator[None]:
512 t0 = time.perf_counter()
513 try:
514 yield
515 finally:
516 t1 = time.perf_counter()
517 if verbose:
518 print(f"{label}: {t1-t0:.3f} sec")
519
520
521 def main() -> None:
522 global verbose
523 args = parser.parse_args()
524 verbose = args.verbose
525 output = args.output
526
527 if args.file:
528 if verbose:
529 print(f"Reading targets from {args.file}")
530 with open(args.file, "rt", encoding="utf-8-sig") as fin:
531 rules = [x.strip() for x in fin]
532 else:
533 rules = args.args
534
535 with open(output, "w", encoding="utf-8") as file:
536 with report_time("generate"):
537 generate(rules, file)
538 if verbose:
539 print(f"Wrote {os.path.getsize(output)} bytes to {output}")
540
541
542 if __name__ == "__main__":
543 main()