Debian Codegraph @

Tools/jit/_targets.py

raw
1 """Target-specific code generation, parsing, and processing."""
2
3 import asyncio
4 import dataclasses
5 import hashlib
6 import json
7 import os
8 import pathlib
9 import re
10 import sys
11 import tempfile
12 import typing
13
14 import _llvm
15 import _schema
16 import _stencils
17 import _writer
18
19 if sys.version_info < (3, 11):
20 raise RuntimeError("Building the JIT compiler requires Python 3.11 or newer!")
21
22 TOOLS_JIT_BUILD = pathlib.Path(__file__).resolve()
23 TOOLS_JIT = TOOLS_JIT_BUILD.parent
24 TOOLS = TOOLS_JIT.parent
25 CPYTHON = TOOLS.parent
26 PYTHON_EXECUTOR_CASES_C_H = CPYTHON / "Python" / "executor_cases.c.h"
27 TOOLS_JIT_TEMPLATE_C = TOOLS_JIT / "template.c"
28
29
30 _S = typing.TypeVar("_S", _schema.COFFSection, _schema.ELFSection, _schema.MachOSection)
31 _R = typing.TypeVar(
32 "_R", _schema.COFFRelocation, _schema.ELFRelocation, _schema.MachORelocation
33 )
34
35
36 @dataclasses.dataclass
37 class _Target(typing.Generic[_S, _R]):
38 triple: str
39 _: dataclasses.KW_ONLY
40 alignment: int = 1
41 args: typing.Sequence[str] = ()
42 ghccc: bool = False
43 prefix: str = ""
44 stable: bool = False
45 debug: bool = False
46 verbose: bool = False
47
48 def _compute_digest(self, out: pathlib.Path) -> str:
49 hasher = hashlib.sha256()
50 hasher.update(self.triple.encode())
51 hasher.update(self.debug.to_bytes())
52 # These dependencies are also reflected in _JITSources in regen.targets:
53 hasher.update(PYTHON_EXECUTOR_CASES_C_H.read_bytes())
54 hasher.update((out / "pyconfig.h").read_bytes())
55 for dirpath, _, filenames in sorted(os.walk(TOOLS_JIT)):
56 # Exclude cache files from digest computation to ensure reproducible builds.
57 if dirpath.endswith("__pycache__"):
58 continue
59 for filename in sorted(filenames):
60 hasher.update(pathlib.Path(dirpath, filename).read_bytes())
61 return hasher.hexdigest()
62
63 async def _parse(self, path: pathlib.Path) -> _stencils.StencilGroup:
64 group = _stencils.StencilGroup()
65 args = ["--disassemble", "--reloc", f"{path}"]
66 output = await _llvm.maybe_run("llvm-objdump", args, echo=self.verbose)
67 if output is not None:
68 group.code.disassembly.extend(
69 line.expandtabs().strip()
70 for line in output.splitlines()
71 if not line.isspace()
72 )
73 args = [
74 "--elf-output-style=JSON",
75 "--expand-relocs",
76 # "--pretty-print",
77 "--section-data",
78 "--section-relocations",
79 "--section-symbols",
80 "--sections",
81 f"{path}",
82 ]
83 output = await _llvm.run("llvm-readobj", args, echo=self.verbose)
84 # --elf-output-style=JSON is only *slightly* broken on Mach-O...
85 output = output.replace("PrivateExtern\n", "\n")
86 output = output.replace("Extern\n", "\n")
87 # ...and also COFF:
88 output = output[output.index("[", 1, None) :]
89 output = output[: output.rindex("]", None, -1) + 1]
90 sections: list[dict[typing.Literal["Section"], _S]] = json.loads(output)
91 for wrapped_section in sections:
92 self._handle_section(wrapped_section["Section"], group)
93 # The trampoline's entry point is just named "_ENTRY", since on some
94 # platforms we later assume that any function starting with "_JIT_" uses
95 # the GHC calling convention:
96 entry_symbol = "_JIT_ENTRY" if "_JIT_ENTRY" in group.symbols else "_ENTRY"
97 assert group.symbols[entry_symbol] == (_stencils.HoleValue.CODE, 0)
98 if group.data.body:
99 line = f"0: {str(bytes(group.data.body)).removeprefix('b')}"
100 group.data.disassembly.append(line)
101 group.process_relocations(alignment=self.alignment)
102 return group
103
104 def _handle_section(self, section: _S, group: _stencils.StencilGroup) -> None:
105 raise NotImplementedError(type(self))
106
107 def _handle_relocation(
108 self, base: int, relocation: _R, raw: bytearray
109 ) -> _stencils.Hole:
110 raise NotImplementedError(type(self))
111
112 async def _compile(
113 self, opname: str, c: pathlib.Path, tempdir: pathlib.Path
114 ) -> _stencils.StencilGroup:
115 # "Compile" the trampoline to an empty stencil group if it's not needed:
116 if opname == "trampoline" and not self.ghccc:
117 return _stencils.StencilGroup()
118 o = tempdir / f"{opname}.o"
119 args = [
120 f"--target={self.triple}",
121 "-DPy_BUILD_CORE_MODULE",
122 "-D_DEBUG" if self.debug else "-DNDEBUG",
123 f"-D_JIT_OPCODE={opname}",
124 "-D_PyJIT_ACTIVE",
125 "-D_Py_JIT",
126 "-I.",
127 f"-I{CPYTHON / 'Include'}",
128 f"-I{CPYTHON / 'Include' / 'internal'}",
129 f"-I{CPYTHON / 'Include' / 'internal' / 'mimalloc'}",
130 f"-I{CPYTHON / 'Python'}",
131 "-O3",
132 "-c",
133 # This debug info isn't necessary, and bloats out the JIT'ed code.
134 # We *may* be able to re-enable this, process it, and JIT it for a
135 # nicer debugging experience... but that needs a lot more research:
136 "-fno-asynchronous-unwind-tables",
137 # Don't call built-in functions that we can't find or patch:
138 "-fno-builtin",
139 # Emit relaxable 64-bit calls/jumps, so we don't have to worry about
140 # about emitting in-range trampolines for out-of-range targets.
141 # We can probably remove this and emit trampolines in the future:
142 "-fno-plt",
143 # Don't call stack-smashing canaries that we can't find or patch:
144 "-fno-stack-protector",
145 "-std=c11",
146 *self.args,
147 ]
148 if self.ghccc:
149 # This is a bit of an ugly workaround, but it makes the code much
150 # smaller and faster, so it's worth it. We want to use the GHC
151 # calling convention, but Clang doesn't support it. So, we *first*
152 # compile the code to LLVM IR, perform some text replacements on the
153 # IR to change the calling convention(!), and then compile *that*.
154 # Once we have access to Clang 19, we can get rid of this and use
155 # __attribute__((preserve_none)) directly in the C code instead:
156 ll = tempdir / f"{opname}.ll"
157 args_ll = args + [
158 # -fomit-frame-pointer is necessary because the GHC calling
159 # convention uses RBP to pass arguments:
160 "-S",
161 "-emit-llvm",
162 "-fomit-frame-pointer",
163 "-o",
164 f"{ll}",
165 f"{c}",
166 ]
167 await _llvm.run("clang", args_ll, echo=self.verbose)
168 ir = ll.read_text()
169 # This handles declarations, definitions, and calls to named symbols
170 # starting with "_JIT_":
171 ir = re.sub(
172 r"(((noalias|nonnull|noundef) )*ptr @_JIT_\w+\()", r"ghccc \1", ir
173 )
174 # This handles calls to anonymous callees, since anything with
175 # "musttail" needs to use the same calling convention:
176 ir = ir.replace("musttail call", "musttail call ghccc")
177 # Sometimes *both* replacements happen at the same site, so fix it:
178 ir = ir.replace("ghccc ghccc", "ghccc")
179 ll.write_text(ir)
180 args_o = args + ["-Wno-unused-command-line-argument", "-o", f"{o}", f"{ll}"]
181 else:
182 args_o = args + ["-o", f"{o}", f"{c}"]
183 await _llvm.run("clang", args_o, echo=self.verbose)
184 return await self._parse(o)
185
186 async def _build_stencils(self) -> dict[str, _stencils.StencilGroup]:
187 generated_cases = PYTHON_EXECUTOR_CASES_C_H.read_text()
188 opnames = sorted(re.findall(r"\n {8}case (\w+): \{\n", generated_cases))
189 tasks = []
190 with tempfile.TemporaryDirectory() as tempdir:
191 work = pathlib.Path(tempdir).resolve()
192 async with asyncio.TaskGroup() as group:
193 coro = self._compile("trampoline", TOOLS_JIT / "trampoline.c", work)
194 tasks.append(group.create_task(coro, name="trampoline"))
195 for opname in opnames:
196 coro = self._compile(opname, TOOLS_JIT_TEMPLATE_C, work)
197 tasks.append(group.create_task(coro, name=opname))
198 return {task.get_name(): task.result() for task in tasks}
199
200 def build(
201 self, out: pathlib.Path, *, comment: str = "", force: bool = False
202 ) -> None:
203 """Build jit_stencils.h in the given directory."""
204 if not self.stable:
205 warning = f"JIT support for {self.triple} is still experimental!"
206 request = "Please report any issues you encounter.".center(len(warning))
207 outline = "=" * len(warning)
208 print("\n".join(["", outline, warning, request, outline, ""]))
209 digest = f"// {self._compute_digest(out)}\n"
210 jit_stencils = out / "jit_stencils.h"
211 if (
212 not force
213 and jit_stencils.exists()
214 and jit_stencils.read_text().startswith(digest)
215 ):
216 return
217 stencil_groups = asyncio.run(self._build_stencils())
218 jit_stencils_new = out / "jit_stencils.h.new"
219 try:
220 with jit_stencils_new.open("w") as file:
221 file.write(digest)
222 if comment:
223 file.write(f"// {comment}\n")
224 file.write("\n")
225 for line in _writer.dump(stencil_groups):
226 file.write(f"{line}\n")
227 try:
228 jit_stencils_new.replace(jit_stencils)
229 except FileNotFoundError:
230 # another process probably already moved the file
231 if not jit_stencils.is_file():
232 raise
233 finally:
234 jit_stencils_new.unlink(missing_ok=True)
235
236
237 class _COFF(
238 _Target[_schema.COFFSection, _schema.COFFRelocation]
239 ): # pylint: disable = too-few-public-methods
240 def _handle_section(
241 self, section: _schema.COFFSection, group: _stencils.StencilGroup
242 ) -> None:
243 flags = {flag["Name"] for flag in section["Characteristics"]["Flags"]}
244 if "SectionData" in section:
245 section_data_bytes = section["SectionData"]["Bytes"]
246 else:
247 # Zeroed BSS data, seen with printf debugging calls:
248 section_data_bytes = [0] * section["RawDataSize"]
249 if "IMAGE_SCN_MEM_EXECUTE" in flags:
250 value = _stencils.HoleValue.CODE
251 stencil = group.code
252 elif "IMAGE_SCN_MEM_READ" in flags:
253 value = _stencils.HoleValue.DATA
254 stencil = group.data
255 else:
256 return
257 base = len(stencil.body)
258 group.symbols[section["Number"]] = value, base
259 stencil.body.extend(section_data_bytes)
260 for wrapped_symbol in section["Symbols"]:
261 symbol = wrapped_symbol["Symbol"]
262 offset = base + symbol["Value"]
263 name = symbol["Name"]
264 name = name.removeprefix(self.prefix)
265 if name not in group.symbols:
266 group.symbols[name] = value, offset
267 for wrapped_relocation in section["Relocations"]:
268 relocation = wrapped_relocation["Relocation"]
269 hole = self._handle_relocation(base, relocation, stencil.body)
270 stencil.holes.append(hole)
271
272 def _unwrap_dllimport(self, name: str) -> tuple[_stencils.HoleValue, str | None]:
273 if name.startswith("__imp_"):
274 name = name.removeprefix("__imp_")
275 name = name.removeprefix(self.prefix)
276 return _stencils.HoleValue.GOT, name
277 name = name.removeprefix(self.prefix)
278 return _stencils.symbol_to_value(name)
279
280 def _handle_relocation(
281 self, base: int, relocation: _schema.COFFRelocation, raw: bytearray
282 ) -> _stencils.Hole:
283 match relocation:
284 case {
285 "Offset": offset,
286 "Symbol": s,
287 "Type": {"Name": "IMAGE_REL_I386_DIR32" as kind},
288 }:
289 offset += base
290 value, symbol = self._unwrap_dllimport(s)
291 addend = int.from_bytes(raw[offset : offset + 4], "little")
292 case {
293 "Offset": offset,
294 "Symbol": s,
295 "Type": {
296 "Name": "IMAGE_REL_AMD64_REL32" | "IMAGE_REL_I386_REL32" as kind
297 },
298 }:
299 offset += base
300 value, symbol = self._unwrap_dllimport(s)
301 addend = (
302 int.from_bytes(raw[offset : offset + 4], "little", signed=True) - 4
303 )
304 case {
305 "Offset": offset,
306 "Symbol": s,
307 "Type": {
308 "Name": "IMAGE_REL_ARM64_BRANCH26"
309 | "IMAGE_REL_ARM64_PAGEBASE_REL21"
310 | "IMAGE_REL_ARM64_PAGEOFFSET_12A"
311 | "IMAGE_REL_ARM64_PAGEOFFSET_12L" as kind
312 },
313 }:
314 offset += base
315 value, symbol = self._unwrap_dllimport(s)
316 addend = 0
317 case _:
318 raise NotImplementedError(relocation)
319 return _stencils.Hole(offset, kind, value, symbol, addend)
320
321
322 class _ELF(
323 _Target[_schema.ELFSection, _schema.ELFRelocation]
324 ): # pylint: disable = too-few-public-methods
325 def _handle_section(
326 self, section: _schema.ELFSection, group: _stencils.StencilGroup
327 ) -> None:
328 section_type = section["Type"]["Name"]
329 flags = {flag["Name"] for flag in section["Flags"]["Flags"]}
330 if section_type == "SHT_RELA":
331 assert "SHF_INFO_LINK" in flags, flags
332 assert not section["Symbols"]
333 maybe_symbol = group.symbols.get(section["Info"])
334 if maybe_symbol is None:
335 # These are relocations for a section we're not emitting. Skip:
336 return
337 value, base = maybe_symbol
338 if value is _stencils.HoleValue.CODE:
339 stencil = group.code
340 else:
341 assert value is _stencils.HoleValue.DATA
342 stencil = group.data
343 for wrapped_relocation in section["Relocations"]:
344 relocation = wrapped_relocation["Relocation"]
345 hole = self._handle_relocation(base, relocation, stencil.body)
346 stencil.holes.append(hole)
347 elif section_type == "SHT_PROGBITS":
348 if "SHF_ALLOC" not in flags:
349 return
350 if "SHF_EXECINSTR" in flags:
351 value = _stencils.HoleValue.CODE
352 stencil = group.code
353 else:
354 value = _stencils.HoleValue.DATA
355 stencil = group.data
356 group.symbols[section["Index"]] = value, len(stencil.body)
357 for wrapped_symbol in section["Symbols"]:
358 symbol = wrapped_symbol["Symbol"]
359 offset = len(stencil.body) + symbol["Value"]
360 name = symbol["Name"]["Name"]
361 name = name.removeprefix(self.prefix)
362 group.symbols[name] = value, offset
363 stencil.body.extend(section["SectionData"]["Bytes"])
364 assert not section["Relocations"]
365 else:
366 assert section_type in {
367 "SHT_GROUP",
368 "SHT_LLVM_ADDRSIG",
369 "SHT_NOTE",
370 "SHT_NULL",
371 "SHT_STRTAB",
372 "SHT_SYMTAB",
373 }, section_type
374
375 def _handle_relocation(
376 self, base: int, relocation: _schema.ELFRelocation, raw: bytearray
377 ) -> _stencils.Hole:
378 symbol: str | None
379 match relocation:
380 case {
381 "Addend": addend,
382 "Offset": offset,
383 "Symbol": {"Name": s},
384 "Type": {
385 "Name": "R_AARCH64_ADR_GOT_PAGE"
386 | "R_AARCH64_LD64_GOT_LO12_NC"
387 | "R_X86_64_GOTPCREL"
388 | "R_X86_64_GOTPCRELX"
389 | "R_X86_64_REX_GOTPCRELX" as kind
390 },
391 }:
392 offset += base
393 s = s.removeprefix(self.prefix)
394 value, symbol = _stencils.HoleValue.GOT, s
395 case {
396 "Addend": addend,
397 "Offset": offset,
398 "Symbol": {"Name": s},
399 "Type": {"Name": kind},
400 }:
401 offset += base
402 s = s.removeprefix(self.prefix)
403 value, symbol = _stencils.symbol_to_value(s)
404 case _:
405 raise NotImplementedError(relocation)
406 return _stencils.Hole(offset, kind, value, symbol, addend)
407
408
409 class _MachO(
410 _Target[_schema.MachOSection, _schema.MachORelocation]
411 ): # pylint: disable = too-few-public-methods
412 def _handle_section(
413 self, section: _schema.MachOSection, group: _stencils.StencilGroup
414 ) -> None:
415 assert section["Address"] >= len(group.code.body)
416 assert "SectionData" in section
417 flags = {flag["Name"] for flag in section["Attributes"]["Flags"]}
418 name = section["Name"]["Value"]
419 name = name.removeprefix(self.prefix)
420 if "Debug" in flags:
421 return
422 if "SomeInstructions" in flags:
423 value = _stencils.HoleValue.CODE
424 stencil = group.code
425 start_address = 0
426 group.symbols[name] = value, section["Address"] - start_address
427 else:
428 value = _stencils.HoleValue.DATA
429 stencil = group.data
430 start_address = len(group.code.body)
431 group.symbols[name] = value, len(group.code.body)
432 base = section["Address"] - start_address
433 group.symbols[section["Index"]] = value, base
434 stencil.body.extend(
435 [0] * (section["Address"] - len(group.code.body) - len(group.data.body))
436 )
437 stencil.body.extend(section["SectionData"]["Bytes"])
438 assert "Symbols" in section
439 for wrapped_symbol in section["Symbols"]:
440 symbol = wrapped_symbol["Symbol"]
441 offset = symbol["Value"] - start_address
442 name = symbol["Name"]["Name"]
443 name = name.removeprefix(self.prefix)
444 group.symbols[name] = value, offset
445 assert "Relocations" in section
446 for wrapped_relocation in section["Relocations"]:
447 relocation = wrapped_relocation["Relocation"]
448 hole = self._handle_relocation(base, relocation, stencil.body)
449 stencil.holes.append(hole)
450
451 def _handle_relocation(
452 self, base: int, relocation: _schema.MachORelocation, raw: bytearray
453 ) -> _stencils.Hole:
454 symbol: str | None
455 match relocation:
456 case {
457 "Offset": offset,
458 "Symbol": {"Name": s},
459 "Type": {
460 "Name": "ARM64_RELOC_GOT_LOAD_PAGE21"
461 | "ARM64_RELOC_GOT_LOAD_PAGEOFF12" as kind
462 },
463 }:
464 offset += base
465 s = s.removeprefix(self.prefix)
466 value, symbol = _stencils.HoleValue.GOT, s
467 addend = 0
468 case {
469 "Offset": offset,
470 "Symbol": {"Name": s},
471 "Type": {"Name": "X86_64_RELOC_GOT" | "X86_64_RELOC_GOT_LOAD" as kind},
472 }:
473 offset += base
474 s = s.removeprefix(self.prefix)
475 value, symbol = _stencils.HoleValue.GOT, s
476 addend = (
477 int.from_bytes(raw[offset : offset + 4], "little", signed=True) - 4
478 )
479 case {
480 "Offset": offset,
481 "Section": {"Name": s},
482 "Type": {"Name": "X86_64_RELOC_SIGNED" as kind},
483 } | {
484 "Offset": offset,
485 "Symbol": {"Name": s},
486 "Type": {"Name": "X86_64_RELOC_BRANCH" | "X86_64_RELOC_SIGNED" as kind},
487 }:
488 offset += base
489 s = s.removeprefix(self.prefix)
490 value, symbol = _stencils.symbol_to_value(s)
491 addend = (
492 int.from_bytes(raw[offset : offset + 4], "little", signed=True) - 4
493 )
494 case {
495 "Offset": offset,
496 "Section": {"Name": s},
497 "Type": {"Name": kind},
498 } | {
499 "Offset": offset,
500 "Symbol": {"Name": s},
501 "Type": {"Name": kind},
502 }:
503 offset += base
504 s = s.removeprefix(self.prefix)
505 value, symbol = _stencils.symbol_to_value(s)
506 addend = 0
507 case _:
508 raise NotImplementedError(relocation)
509 return _stencils.Hole(offset, kind, value, symbol, addend)
510
511
512 def get_target(host: str) -> _COFF | _ELF | _MachO:
513 """Build a _Target for the given host "triple" and options."""
514 # ghccc currently crashes Clang when combined with musttail on aarch64. :(
515 target: _COFF | _ELF | _MachO
516 if re.fullmatch(r"aarch64-apple-darwin.*", host):
517 target = _MachO(host, alignment=8, prefix="_")
518 elif re.fullmatch(r"aarch64-pc-windows-msvc", host):
519 args = ["-fms-runtime-lib=dll"]
520 target = _COFF(host, alignment=8, args=args)
521 elif re.fullmatch(r"aarch64-.*-linux-gnu", host):
522 args = [
523 "-fpic",
524 # On aarch64 Linux, intrinsics were being emitted and this flag
525 # was required to disable them.
526 "-mno-outline-atomics",
527 ]
528 target = _ELF(host, alignment=8, args=args)
529 elif re.fullmatch(r"i686-pc-windows-msvc", host):
530 args = ["-DPy_NO_ENABLE_SHARED"]
531 target = _COFF(host, args=args, ghccc=True, prefix="_")
532 elif re.fullmatch(r"x86_64-apple-darwin.*", host):
533 target = _MachO(host, ghccc=True, prefix="_")
534 elif re.fullmatch(r"x86_64-pc-windows-msvc", host):
535 args = ["-fms-runtime-lib=dll"]
536 target = _COFF(host, args=args, ghccc=True)
537 elif re.fullmatch(r"x86_64-.*-linux-gnu", host):
538 args = ["-fpic"]
539 target = _ELF(host, args=args, ghccc=True)
540 else:
541 raise ValueError(host)
542 return target