Skip to content
Open
Show file tree
Hide file tree
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
3 changes: 2 additions & 1 deletion Include/internal/pycore_jit.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@ typedef _Py_CODEUNIT *(*jit_func)(
_PyStackRef _tos_cache0, _PyStackRef _tos_cache1, _PyStackRef _tos_cache2
);

_Py_CODEUNIT *_PyJIT_Entry(
_Py_CODEUNIT *_Py_LazyJitShim(
_PyExecutorObject *executor, _PyInterpreterFrame *frame,
_PyStackRef *stack_pointer, PyThreadState *tstate
);

int _PyJIT_Compile(_PyExecutorObject *executor, const _PyUOpInstruction *trace, size_t length);
void _PyJIT_Free(_PyExecutorObject *executor);
void _PyJIT_Fini(void);
PyAPI_FUNC(int) _PyJIT_AddressInJitCode(PyInterpreterState *interp, uintptr_t addr);

#endif // _Py_JIT
Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_c_stack_unwind.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@


STACK_DEPTH = 10
# Downstream: the JIT shim is compiled at runtime and JIT code is not
# registered with unwind info, so GNU backtrace stops at JIT frames.
JIT_UNWIND_UNSUPPORTED = "JIT frames have no registered unwind info"


def _manual_unwind_expected(machine):
Expand Down Expand Up @@ -350,6 +353,8 @@ def test_gnu_backtrace_unwinds_through_jit_frames(self):
python_frames = result.get("python_frames", 0)
jit_frames = result.get("jit_frames", 0)
jit_backend = result.get("jit_backend")
if using_jit and jit_backend == "jit":
self.skipTest(JIT_UNWIND_UNSUPPORTED)

self.assertGreaterEqual(
python_frames,
Expand All @@ -369,6 +374,7 @@ def test_gnu_backtrace_unwinds_through_jit_frames(self):
f"unexpected JIT frames counted in GNU backtrace with env {env}",
)

@unittest.skip(JIT_UNWIND_UNSUPPORTED)
def test_gnu_backtrace_jit_frames_disappear_after_executor_free(self):
if not (hasattr(sys, "_jit") and sys._jit.is_available()):
self.skipTest("JIT is not available")
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_gdb/test_jit.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ def setUpModule():
"GDB JIT CFI emitter only supports x86_64 and AArch64")
@unittest.skipUnless(NATIVE_JIT_ENABLED,
"requires native JIT execution active")
# Downstream: the JIT shim is compiled at runtime, so there is no linked
# _PyJIT_Entry and JIT code is not registered with the GDB JIT interface.
@unittest.skip("JIT code is not registered with the GDB JIT interface")
class JitBacktraceTests(DebuggerTests):
def get_stack_trace(self, **kwargs):
# These tests validate the JIT-relevant part of the backtrace via
Expand Down
18 changes: 6 additions & 12 deletions Makefile.pre.in
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ LDLIBRARYDIR= @LDLIBRARYDIR@
INSTSONAME= @INSTSONAME@
LIBRARY_DEPS= @LIBRARY_DEPS@
LINK_PYTHON_DEPS=@LINK_PYTHON_DEPS@
JIT_OBJS= @JIT_SHIM_O@
JIT_OBJS=
PY_ENABLE_SHARED= @PY_ENABLE_SHARED@
STATIC_LIBPYTHON= @STATIC_LIBPYTHON@

Expand Down Expand Up @@ -3229,10 +3229,9 @@ Python/emscripten_trampoline_inner.wasm: $(srcdir)/Python/emscripten_trampoline_
Python/emscripten_trampoline_wasm.c: Python/emscripten_trampoline_inner.wasm
$(PYTHON_FOR_REGEN) $(srcdir)/Platforms/emscripten/prepare_external_wasm.py $< $@ getWasmTrampolineModule

JIT_SHIM_BUILD_OBJS= @JIT_SHIM_BUILD_O@
JIT_UNWIND_INFO_H= $(if $(JIT_OBJS),jit_unwind_info.h $(patsubst jit_stencils-%.h,jit_unwind_info-%.h,@JIT_STENCILS_H@))
JIT_BUILD_TARGETS= jit_stencils.h @JIT_STENCILS_H@ $(JIT_UNWIND_INFO_H) $(JIT_SHIM_BUILD_OBJS)
JIT_TARGETS= $(JIT_BUILD_TARGETS) $(filter-out $(JIT_SHIM_BUILD_OBJS),$(JIT_OBJS))
JIT_UNWIND_INFO_H= $(if @JIT_STENCILS_H@,jit_unwind_info.h $(patsubst jit_stencils-%.h,jit_unwind_info-%.h,@JIT_STENCILS_H@))
JIT_BUILD_TARGETS= $(if @JIT_STENCILS_H@,jit_stencils.h @JIT_STENCILS_H@ $(JIT_UNWIND_INFO_H))
JIT_TARGETS= $(JIT_BUILD_TARGETS)
JIT_GENERATED_STAMP= .jit-stamp

JIT_DEPS = \
Expand All @@ -3253,9 +3252,6 @@ $(JIT_BUILD_TARGETS): $(JIT_GENERATED_STAMP)
test -f "$@"; \
fi

jit_shim-universal2-apple-darwin.o: jit_shim-aarch64-apple-darwin.o jit_shim-x86_64-apple-darwin.o
lipo -create -output $@ jit_shim-aarch64-apple-darwin.o jit_shim-x86_64-apple-darwin.o

Python/jit.o: $(srcdir)/Python/jit.c @JIT_STENCILS_H@
$(CC) -c $(PY_CORE_CFLAGS) -o $@ $<

Expand Down Expand Up @@ -3343,9 +3339,7 @@ docclean:
# data. The PGO data is only valid if source code remains unchanged.
.PHONY: clean-retain-profile
clean-retain-profile: pycremoval
# Keep the generated JIT shim objects with the rest of the JIT generated
# files: they are regenerated as a group and tracked by .jit-stamp.
find . -name '*.[oa]' ! -name 'jit_shim*.o' -exec rm -f {} ';'
find . -name '*.[oa]' -exec rm -f {} ';'
find . -name '*.s[ol]' -exec rm -f {} ';'
find . -name '*.so.[0-9]*.[0-9]*' -exec rm -f {} ';'
find . -name '*.lto' -exec rm -f {} ';'
Expand Down Expand Up @@ -3389,7 +3383,7 @@ clean-profile: clean-retain-profile clean-bolt
# gh-141808: The JIT stencils are deliberately kept in clean-profile
.PHONY: clean-jit-stencils
clean-jit-stencils:
-rm -f $(JIT_TARGETS) $(JIT_GENERATED_STAMP) jit_stencils*.h jit_unwind_info*.h jit_shim*.o
-rm -f $(JIT_TARGETS) $(JIT_GENERATED_STAMP) jit_stencils*.h jit_unwind_info*.h

.PHONY: clean
clean: clean-profile clean-jit-stencils
Expand Down
2 changes: 1 addition & 1 deletion Python/ceval.c
Original file line number Diff line number Diff line change
Expand Up @@ -1369,7 +1369,7 @@ _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int
}
#ifdef _Py_TIER2
#ifdef _Py_JIT
_PyJitEntryFuncPtr _Py_jit_entry = _PyJIT_Entry;
_PyJitEntryFuncPtr _Py_jit_entry = _Py_LazyJitShim;
#else
_PyJitEntryFuncPtr _Py_jit_entry = _PyTier2Interpreter;
#endif
Expand Down
108 changes: 108 additions & 0 deletions Python/jit.c
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ jit_error(const char *message)
PyErr_Format(PyExc_RuntimeWarning, "JIT %s (%d)", message, hint);
}

static size_t _Py_jit_shim_size = 0;
static _PyJitCodeRegistration *_Py_jit_shim_registration = NULL;

static int
address_in_executor_array(_PyExecutorObject **ptrs, size_t count, uintptr_t addr)
{
Expand Down Expand Up @@ -104,6 +107,13 @@ _PyJIT_AddressInJitCode(PyInterpreterState *interp, uintptr_t addr)
if (interp == NULL) {
return 0;
}
if (_Py_jit_entry != _Py_LazyJitShim && _Py_jit_shim_size != 0) {
uintptr_t start = (uintptr_t)_Py_jit_entry;
uintptr_t end = start + _Py_jit_shim_size;
if (addr >= start && addr < end) {
return 1;
}
}
if (address_in_executor_array(interp->executor_ptrs, interp->executor_count, addr)) {
return 1;
}
Expand Down Expand Up @@ -725,6 +735,84 @@ _PyJIT_Compile(_PyExecutorObject *executor, const _PyUOpInstruction trace[], siz
return 0;
}

/* One-off compilation of the JIT entry shim.
* The shim is compiled once because it is effectively a normal function, but
* still needs the JIT stencil machinery for the JIT-specific calling convention.
* Don't forget to call _PyJIT_Fini later.
*/
static _PyJitEntryFuncPtr
compile_shim(void)
{
_PyExecutorObject dummy;
const StencilGroup *group;
size_t code_size = 0;
size_t data_size = 0;
jit_state state = {0};
group = &shim;
code_size += group->code_size;
data_size += group->data_size;
combine_symbol_mask(group->trampoline_mask, state.trampolines.mask);
combine_symbol_mask(group->got_mask, state.got_symbols.mask);
for (size_t i = 0; i < Py_ARRAY_LENGTH(state.trampolines.mask); i++) {
state.trampolines.size += _Py_popcount32(state.trampolines.mask[i]) * TRAMPOLINE_SIZE;
}
for (size_t i = 0; i < Py_ARRAY_LENGTH(state.got_symbols.mask); i++) {
state.got_symbols.size += _Py_popcount32(state.got_symbols.mask[i]) * GOT_SLOT_SIZE;
}
// Round up to the nearest page:
size_t page_size = get_page_size();
assert((page_size & (page_size - 1)) == 0);
size_t code_padding = DATA_ALIGN - ((code_size + state.trampolines.size) & (DATA_ALIGN - 1));
size_t padding = page_size - ((code_size + state.trampolines.size + code_padding + data_size + state.got_symbols.size) & (page_size - 1));
size_t total_size = code_size + state.trampolines.size + code_padding + data_size + state.got_symbols.size + padding;
unsigned char *memory = jit_alloc(total_size);
if (memory == NULL) {
return NULL;
}
unsigned char *code = memory;
state.trampolines.mem = memory + code_size;
unsigned char *data = memory + code_size + state.trampolines.size + code_padding;
state.got_symbols.mem = data + data_size;
// Compile the shim, which handles converting between the native
// calling convention and the calling convention used by jitted code.
group = &shim;
group->emit(code, data, &dummy, NULL, &state);
code += group->code_size;
data += group->data_size;
assert(code == memory + code_size);
assert(data == memory + code_size + state.trampolines.size + code_padding + data_size);
if (mark_executable(memory, total_size)) {
jit_free(memory, total_size);
return NULL;
}
_Py_jit_shim_size = total_size;
_Py_jit_shim_registration = _PyJit_RegisterCode(
memory,
code_size + state.trampolines.size,
"jit",
"shim");
return (_PyJitEntryFuncPtr)memory;
}

static PyMutex lazy_jit_mutex = { 0 };

_Py_CODEUNIT *
_Py_LazyJitShim(
_PyExecutorObject *executor, _PyInterpreterFrame *frame, _PyStackRef *stack_pointer, PyThreadState *tstate
) {
PyMutex_Lock(&lazy_jit_mutex);
if (_Py_jit_entry == _Py_LazyJitShim) {
_PyJitEntryFuncPtr shim = compile_shim();
if (shim == NULL) {
PyMutex_Unlock(&lazy_jit_mutex);
Py_FatalError("Cannot allocate core JIT code");
}
_Py_jit_entry = shim;
}
PyMutex_Unlock(&lazy_jit_mutex);
return _Py_jit_entry(executor, frame, stack_pointer, tstate);
}

// Free executor's memory allocated with _PyJIT_Compile
void
_PyJIT_Free(_PyExecutorObject *executor)
Expand All @@ -743,4 +831,24 @@ _PyJIT_Free(_PyExecutorObject *executor)
}
}

// Free shim memory allocated with compile_shim.
void
_PyJIT_Fini(void)
{
PyMutex_Lock(&lazy_jit_mutex);
unsigned char *memory = (unsigned char *)_Py_jit_entry;
size_t size = _Py_jit_shim_size;
if (size) {
_Py_jit_entry = _Py_LazyJitShim;
_Py_jit_shim_size = 0;
_PyJit_UnregisterCode(_Py_jit_shim_registration);
_Py_jit_shim_registration = NULL;
if (jit_free(memory, size)) {
PyErr_FormatUnraisable("Exception ignored while "
"freeing JIT entry code");
}
}
PyMutex_Unlock(&lazy_jit_mutex);
}

#endif // _Py_JIT
36 changes: 20 additions & 16 deletions Python/jit_unwind.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@

#if defined(PY_HAVE_JIT_GDB_UNWIND)
# include "jit_unwind_info.h"
# if !JIT_UNWIND_INFO_SUPPORTED
# error "JIT unwind info was not generated for this target"
# endif
#endif
#ifndef JIT_UNWIND_INFO_SUPPORTED
# define JIT_UNWIND_INFO_SUPPORTED 0
#endif

#if defined(PY_HAVE_PERF_TRAMPOLINE) \
Expand Down Expand Up @@ -226,13 +226,13 @@ static void elfctx_append_uleb128(ELFObjectContext* ctx, uint32_t v) {
// =============================================================================

static void elf_init_ehframe_perf(ELFObjectContext* ctx);
#if defined(PY_HAVE_JIT_GDB_UNWIND)
#if defined(PY_HAVE_JIT_GDB_UNWIND) && JIT_UNWIND_INFO_SUPPORTED
static void elf_init_ehframe_gdb(ELFObjectContext* ctx);
#endif

static inline void elf_init_ehframe(ELFObjectContext* ctx, int absolute_addr) {
if (absolute_addr) {
#if defined(PY_HAVE_JIT_GDB_UNWIND)
#if defined(PY_HAVE_JIT_GDB_UNWIND) && JIT_UNWIND_INFO_SUPPORTED
elf_init_ehframe_gdb(ctx);
#else
Py_UNREACHABLE();
Expand All @@ -246,6 +246,9 @@ static inline void elf_init_ehframe(ELFObjectContext* ctx, int absolute_addr) {
size_t
_PyJitUnwind_EhFrameSize(int absolute_addr)
{
if (absolute_addr && !JIT_UNWIND_INFO_SUPPORTED) {
return 0;
}
/* The .eh_frame we emit is small and bounded; keep a generous buffer. */
uint8_t scratch[512];
_Static_assert(sizeof(scratch) >= 256,
Expand Down Expand Up @@ -651,15 +654,14 @@ static void elf_init_ehframe_perf(ELFObjectContext* ctx) {
/*
* Build .eh_frame data for the GDB JIT interface.
*
* The executor runs inside the frame established by _PyJIT_Entry, but the
* synthetic executor FDE collapses that state into a single logical JIT frame
* that unwinds directly into _PyEval_*. Executor stencils never touch the
* frame pointer - enforced by Tools/jit/_optimizers.py _validate() and
* -mframe-pointer=reserved - so the steady-state rule is valid at every PC
* and the FDE body is empty. Tools/jit/_targets.py derives the initial CFI
* rules from the row active at the executor call in the compiled shim object.
* When generated shim CFI is available, the executor runs inside the frame
* established by the JIT entry shim, but the synthetic executor FDE collapses
* that state into a single logical JIT frame that unwinds directly into
* _PyEval_*. Executor stencils never touch the frame pointer - enforced by
* Tools/jit/_optimizers.py _validate() and -mframe-pointer=reserved - so the
* steady-state rule is valid at every PC and the FDE body is empty.
*/
#if defined(PY_HAVE_JIT_GDB_UNWIND)
#if defined(PY_HAVE_JIT_GDB_UNWIND) && JIT_UNWIND_INFO_SUPPORTED
static void elf_init_ehframe_gdb(ELFObjectContext* ctx) {
int fde_ptr_enc = DWRF_EH_PE_absptr;
uint8_t* p = ctx->p;
Expand Down Expand Up @@ -696,7 +698,7 @@ static void elf_init_ehframe_gdb(ELFObjectContext* ctx) {

ctx->p = p;
}
#endif
#endif // defined(PY_HAVE_JIT_GDB_UNWIND) && JIT_UNWIND_INFO_SUPPORTED

#if defined(PY_HAVE_JIT_GDB_UNWIND)
enum {
Expand Down Expand Up @@ -736,6 +738,7 @@ __jit_debug_register_code(void)
#endif
}

#if JIT_UNWIND_INFO_SUPPORTED
static uint16_t
gdb_jit_machine_id(void)
{
Expand Down Expand Up @@ -928,6 +931,7 @@ gdb_jit_register_code(
PyMutex_Unlock(&_Py_jit_debug_mutex);
return entry;
}
#endif // JIT_UNWIND_INFO_SUPPORTED
#endif // defined(PY_HAVE_JIT_GDB_UNWIND)

void *
Expand All @@ -936,7 +940,7 @@ _PyJitUnwind_GdbRegisterCode(const void *code_addr,
const char *entry,
const char *filename)
{
#if defined(PY_HAVE_JIT_GDB_UNWIND)
#if defined(PY_HAVE_JIT_GDB_UNWIND) && JIT_UNWIND_INFO_SUPPORTED
/* GDB expects a stable symbol name and absolute addresses in .eh_frame. */
if (entry == NULL) {
entry = "";
Expand Down Expand Up @@ -975,7 +979,7 @@ _PyJitUnwind_GdbRegisterCode(const void *code_addr,
void
_PyJitUnwind_GdbUnregisterCode(void *handle)
{
#if defined(PY_HAVE_JIT_GDB_UNWIND)
#if defined(PY_HAVE_JIT_GDB_UNWIND) && JIT_UNWIND_INFO_SUPPORTED
struct jit_code_entry *entry = (struct jit_code_entry *)handle;
if (entry == NULL) {
return;
Expand Down
6 changes: 6 additions & 0 deletions Python/pylifecycle.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include "pycore_global_objects_fini_generated.h" // _PyStaticObjects_CheckRefcnt()
#include "pycore_initconfig.h" // _PyStatus_OK()
#include "pycore_interpolation.h" // _PyInterpolation_InitTypes()
#include "pycore_jit.h" // _PyJIT_Fini()
#include "pycore_long.h" // _PyLong_InitTypes()
#include "pycore_moduleobject.h" // _PyModule_InitModuleDictWatcher()
#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
Expand Down Expand Up @@ -2566,6 +2567,11 @@ _Py_Finalize(_PyRuntimeState *runtime)

finalize_interp_clear(tstate);

#ifdef _Py_JIT
/* Free JIT shim memory */
_PyJIT_Fini();
#endif

#ifdef Py_TRACE_REFS
/* Display addresses (& refcnts) of all objects still alive.
* An address can be used to find the repr of the object, printed
Expand Down
Loading