Skip to content
1 change: 1 addition & 0 deletions Include/internal/pycore_runtime_structs.h
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ struct pyruntimestate {
struct _pymem_allocators allocators;
struct _obmalloc_global_state obmalloc;
struct pyhash_runtime_state pyhash_state;
uint64_t fork_generation;
struct _pythread_runtime_state threads;
struct _signals_runtime_state signals;

Expand Down
46 changes: 45 additions & 1 deletion Lib/test/test_external_inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@
threading_helper,
SHORT_TIMEOUT,
busy_retry,
requires_fork,
requires_gil_enabled,
requires_remote_subprocess_debugging,
)
from test.support.import_helper import import_module
from test.support.script_helper import make_script
from test.support.script_helper import assert_python_ok, make_script
from test.support.socket_helper import find_unused_port

import subprocess
Expand Down Expand Up @@ -476,6 +477,49 @@ def _extract_coroutine_stacks_lineno_only(self, stack_trace):
# ============================================================================


@unittest.skipUnless(sys.platform == "darwin", "requires Mach task ports")
class TestUnwinderAfterFork(unittest.TestCase):
@requires_fork()
def test_inherited_unwinder(self):
try:
RemoteUnwinder(os.getpid())
except PermissionError as exc:
self.skipTest(f"self-inspection is unavailable: {exc}")

assert_python_ok("-c", textwrap.dedent("""
import os
import unittest
from _remote_debugging import RemoteUnwinder
from test.support import SHORT_TIMEOUT, wait_process

untouched = RemoteUnwinder(os.getpid())
unwinder = RemoteUnwinder(os.getpid(), stats=True)
assert untouched.get_stack_trace()
assert unwinder.get_stack_trace()

pid = os.fork()
if pid:
wait_process(pid, exitcode=0, timeout=SHORT_TIMEOUT)
assert unwinder.get_stack_trace()
else:
check = unittest.TestCase()
for name in (
"get_stats", "get_stack_trace", "get_async_stack_trace",
"get_all_awaited_by", "pause_threads", "resume_threads",
):
with check.assertRaisesRegex(
RuntimeError, "after fork", msg=name
):
getattr(unwinder, name)()
with check.assertRaisesRegex(RuntimeError, "after fork"):
unwinder.__init__(os.getpid())
fresh = RemoteUnwinder(os.getpid())
assert fresh.get_stack_trace()
del untouched, unwinder
assert fresh.get_stack_trace()
"""))


@requires_remote_subprocess_debugging()
class TestSelfStackTrace(RemoteInspectionTestBase):
def _extract_coroutine_funcnames(self, trace):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Speed up :mod:`profiling.sampling` on macOS by mapping the target process's
memory pages into the profiler with ``mach_vm_remap`` instead of copying them
on every sample. Patch by Maurycy Pawłowski-Wieroński.
15 changes: 11 additions & 4 deletions Modules/_remote_debugging/frame_cache.c
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,17 @@ read_last_profiled_anchor(RemoteUnwinderObject *unwinder,
// remote-memory read.
if (seq_offset == frame_offset + sizeof(uintptr_t)) {
uintptr_t live_anchor[2];
if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle,
thread_state_addr + frame_offset,
sizeof(live_anchor),
live_anchor) < 0) {
int rc = _Py_RemoteDebug_AliasedReadRemoteMemory(
&unwinder->handle, thread_state_addr + frame_offset,
sizeof(live_anchor), live_anchor);
if (rc < 0) {
return -1;
}
if (rc > 0
&& _Py_RemoteDebug_ReadRemoteMemory(
&unwinder->handle, thread_state_addr + frame_offset,
sizeof(live_anchor), live_anchor) < 0)
{
return -1;
}
anchor->frame = live_anchor[0];
Expand Down
61 changes: 60 additions & 1 deletion Modules/_remote_debugging/module.c
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,17 @@ class _remote_debugging.RemoteUnwinder "RemoteUnwinderObject *" "&RemoteUnwinder
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=12b4dce200381115]*/

static int
check_unwinder_process(RemoteUnwinderObject *self)
{
if (self->handle.pid && _Py_RemoteDebug_HandleIsInherited(&self->handle)) {
PyErr_SetString(PyExc_RuntimeError,
"Create a new RemoteUnwinder after fork");
return -1;
}
return 0;
}

/*[clinic input]
@permit_long_summary
_remote_debugging.RemoteUnwinder.__init__
Expand Down Expand Up @@ -344,6 +355,9 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self,
int stats)
/*[clinic end generated code: output=acfe554c8a92cf6b input=3b5a5ad153709125]*/
{
if (check_unwinder_process(self) < 0) {
return -1;
}
// Validate that all_threads and only_active_thread are not both True
if (all_threads && only_active_thread) {
PyErr_SetString(PyExc_ValueError,
Expand All @@ -359,6 +373,9 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self,
}
#endif

if (self->handle.pid != 0) {
_Py_RemoteDebug_CleanupProcHandle(&self->handle);
}
self->native = native;
self->gc = gc;
self->opcodes = opcodes;
Expand Down Expand Up @@ -582,6 +599,28 @@ read_interp_state_and_maybe_thread_frame(
{
prefetch->tstate = NULL;
prefetch->frame = NULL;
int aliased = _Py_RemoteDebug_AliasedReadRemoteMemory(
&unwinder->handle, interpreter_addr, INTERP_STATE_BUFFER_SIZE,
interp_state_buffer);
if (aliased < 0) {
return -1;
}
if (aliased == 0) {
if (prefetch->tstate_addr != 0) {
size_t tstate_size =
(size_t)unwinder->debug_offsets.thread_state.size;
int rc = _Py_RemoteDebug_AliasedReadRemoteMemory(
&unwinder->handle, prefetch->tstate_addr, tstate_size,
tstate_buffer);
if (rc == 0) {
prefetch->tstate = tstate_buffer;
}
else if (rc < 0) {
PyErr_Clear();
}
}
return 0;
}
if (prefetch->tstate_addr != 0) {
size_t tstate_size = (size_t)unwinder->debug_offsets.thread_state.size;
_Py_RemoteReadSegment segments[3] = {
Expand Down Expand Up @@ -680,6 +719,9 @@ static PyObject *
_remote_debugging_RemoteUnwinder_get_stack_trace_impl(RemoteUnwinderObject *self)
/*[clinic end generated code: output=666192b90c69d567 input=86a992b853f48aa9]*/
{
if (check_unwinder_process(self) < 0) {
return NULL;
}
STATS_INC(self, total_samples);

PyObject* result = PyList_New(0);
Expand Down Expand Up @@ -934,6 +976,9 @@ static PyObject *
_remote_debugging_RemoteUnwinder_get_all_awaited_by_impl(RemoteUnwinderObject *self)
/*[clinic end generated code: output=6a49cd345e8aec53 input=17fcd3d7bb835624]*/
{
if (check_unwinder_process(self) < 0) {
return NULL;
}
if (ensure_async_debug_offsets(self) < 0) {
return NULL;
}
Expand Down Expand Up @@ -1059,6 +1104,9 @@ static PyObject *
_remote_debugging_RemoteUnwinder_get_async_stack_trace_impl(RemoteUnwinderObject *self)
/*[clinic end generated code: output=6433d52b55e87bbe input=a95958816358476a]*/
{
if (check_unwinder_process(self) < 0) {
return NULL;
}
if (ensure_async_debug_offsets(self) < 0) {
return NULL;
}
Expand Down Expand Up @@ -1137,6 +1185,9 @@ static PyObject *
_remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self)
/*[clinic end generated code: output=21e36477122be2a0 input=87905c65038fb06e]*/
{
if (check_unwinder_process(self) < 0) {
return NULL;
}
if (!self->collect_stats) {
PyErr_SetString(PyExc_RuntimeError,
"Statistics collection was not enabled. "
Expand Down Expand Up @@ -1248,6 +1299,9 @@ static PyObject *
_remote_debugging_RemoteUnwinder_pause_threads_impl(RemoteUnwinderObject *self)
/*[clinic end generated code: output=aaf2bdc0a725750c input=b91dde5517c9dde2]*/
{
if (check_unwinder_process(self) < 0) {
return NULL;
}
#ifdef Py_REMOTE_DEBUG_SUPPORTS_BLOCKING
if (self->threads_stopped) {
Py_RETURN_FALSE;
Expand Down Expand Up @@ -1284,6 +1338,9 @@ static PyObject *
_remote_debugging_RemoteUnwinder_resume_threads_impl(RemoteUnwinderObject *self)
/*[clinic end generated code: output=8d6781ea37095536 input=130758d55d46897a]*/
{
if (check_unwinder_process(self) < 0) {
return NULL;
}
#ifdef Py_REMOTE_DEBUG_SUPPORTS_BLOCKING
if (!self->threads_stopped) {
Py_RETURN_FALSE;
Expand Down Expand Up @@ -1316,7 +1373,9 @@ RemoteUnwinder_dealloc(PyObject *op)
PyTypeObject *tp = Py_TYPE(self);

#ifdef Py_REMOTE_DEBUG_SUPPORTS_BLOCKING
if (self->threads_stopped) {
if (self->threads_stopped
&& !_Py_RemoteDebug_HandleIsInherited(&self->handle))
{
_Py_RemoteDebug_ResumeAllThreads(self, &self->threads_state);
self->threads_stopped = 0;
}
Expand Down
15 changes: 12 additions & 3 deletions Modules/_remote_debugging/threads.c
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,11 @@ read_thread_state_and_maybe_frame(
int *frame_read)
{
*frame_read = 0;
int aliased = _Py_RemoteDebug_AliasedReadRemoteMemory(
&unwinder->handle, tstate_addr, tstate_size, tstate_buffer);
if (aliased <= 0) {
return aliased;
}
if (predicted_frame_addr != 0) {
_Py_RemoteReadSegment segments[2] = {
{tstate_addr, tstate_buffer, tstate_size},
Expand Down Expand Up @@ -343,11 +348,15 @@ unwind_stack_for_thread(
}
}
else {
int rc = _Py_RemoteDebug_ReadRemoteMemory(
&unwinder->handle,
int unused_frame_read = 0;
int rc = read_thread_state_and_maybe_frame(
unwinder,
*current_tstate,
(size_t)unwinder->debug_offsets.thread_state.size,
local_ts);
local_ts,
0,
NULL,
&unused_frame_read);
if (rc < 0) {
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read thread state");
goto error;
Expand Down
2 changes: 2 additions & 0 deletions Modules/posixmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,8 @@ PyOS_AfterFork_Child(void)
PyStatus status;
_PyRuntimeState *runtime = &_PyRuntime;

runtime->fork_generation++;

// re-creates runtime->interpreters.mutex (HEAD_UNLOCK)
status = _PyRuntimeState_ReInitThreads(runtime);
if (_PyStatus_EXCEPTION(status)) {
Expand Down
Loading
Loading