This PEP proposes adding a zero-overhead debugging interface to CPython that allows debuggers and profilers to safely attach to running Python processes. The interface provides safe execution points for attaching debugger code without modifying the interpreter’s normal execution path or adding runtime overhead.
A key application of this interface will be enabling pdb to attach to live processes by process ID, similar to gdb -p, allowing developers to inspect and debug Python applications interactively in real-time without stopping or restarting them.
Debugging Python processes in production and live environments presents unique challenges. Developers often need to analyze application behavior without stopping or restarting services, which is especially crucial for high-availability systems. Common scenarios include diagnosing deadlocks, inspecting memory usage, or investigating unexpected behavior in real-time.
Very few Python tools can attach to running processes, primarily because doing so requires deep expertise in both operating system debugging interfaces and CPython internals. While C/C++ debuggers like GDB and LLDB can attach to processes using well-understood techniques, Python tools must implement all of these low-level mechanisms plus handle additional complexity. For example, when GDB needs to execute code in a target process, it:
Python tools face this same challenge of code injection, but with an additional layer of complexity. Not only do they need to implement the above mechanism, they must also understand and safely interact with CPython’s runtime state, including the interpreter loop, garbage collector, thread state, and reference counting system. This combination of low-level system manipulation and deep domain specific interpreter knowledge makes implementing Python debugging tools exceptionally difficult.
The few tools (see for example DebugPy and Memray) that do attempt this resort to suboptimal and unsafe methods, using system debuggers like GDB and LLDB to forcefully inject code. This approach is fundamentally unsafe because the injected code can execute at any point during the interpreter’s execution cycle - even during critical operations like memory allocation, garbage collection, or thread state management. When this happens, the results are catastrophic: attempting to allocate memory while already inside malloc() causes crashes, modifying objects during garbage collection corrupts the interpreter’s state, and touching thread state at the wrong time leads to deadlocks.
Various tools attempt to minimize these risks through complex workarounds, such as spawning separate threads for injected code or carefully timing their operations or trying to select some good points to stop the process. However, these mitigations cannot fully solve the underlying problem: without cooperation from the interpreter, there’s no way to know if it’s safe to execute code at any given moment. Even carefully implemented tools can crash the interpreter because they’re fundamentally working against it rather than with it.
Rather than forcing tools to work around interpreter limitations with unsafe code injection, we can extend CPython with a proper debugging interface that guarantees safe execution. By adding a few thread state fields and integrating with the interpreter’s existing evaluation loop, we can ensure debugging operations only occur at well-defined safe points. This eliminates the possibility of crashes and corruption while maintaining zero overhead during normal execution.
The key insight is that we don’t need to inject code at arbitrary points - we just need to signal to the interpreter that we want code executed at the next safe opportunity. This approach works with the interpreter’s natural execution flow rather than fighting against it.
After describing this idea to the PyPy development team, this proposal has already been implemented in PyPy, proving both its feasibility and effectiveness. Their implementation demonstrates that we can provide safe debugging capabilities with zero runtime overhead during normal execution. The proposed mechanism not only reduces risks associated with current debugging approaches but also lays the foundation for future enhancements. For instance, this framework could enable integration with popular observability tools, providing real-time insights into interpreter performance or memory usage. One compelling use case for this interface is enabling pdb to attach to running Python processes, similar to how gdb allows users to attach to a program by process ID (gdb -p <pid>). With this feature, developers could inspect the state of a running application, evaluate expressions, and step through code dynamically. This approach would align Python’s debugging capabilities with those of other major programming languages and debugging tools that support this mode.
This proposal introduces a safe debugging mechanism that allows external processes to trigger code execution in a Python interpreter at well-defined safe points. The key insight is that rather than injecting code directly via system debuggers, we can leverage the interpreter’s existing evaluation loop and thread state to coordinate debugging operations.
The mechanism works by having debuggers write to specific memory locations in the target process that the interpreter then checks during its normal execution cycle. When the interpreter detects that a debugger wants to attach, it executes the requested operations only when it’s safe to do so - that is, when no internal locks are held and all data structures are in a consistent state.
A new structure is added to PyThreadState to support remote debugging:
This structure is appended to PyThreadState, adding only a few fields that are never accessed during normal execution. The debugger_pending_call field indicates when a debugger has requested execution, while debugger_script_path provides a filesystem path to a Python source file (.py) that will be executed when the interpreter reaches a safe point. The path must point to a Python source file, not compiled Python code (.pyc) or any other format.
The size of debugger_script_path will be a trade-off between binary size and how big debugging scripts’ paths can be. To limit the memory overhead per thread we will be limiting this to 512 bytes. This size will also be provided as part of the debugger support structure so debuggers know how much they can write. This value can be extended in the future if we ever need to.
Python 3.12 introduced a debug offsets table placed at the start of the PyRuntime structure. This section contains the _Py_DebugOffsets structure that allows external tools to reliably find critical runtime structures regardless of ASLR or how Python was compiled.
This proposal extends the existing debug offsets table with new fields for debugger support:
These offsets allow debuggers to locate critical debugging control structures in the target process’s memory space. The eval_breaker and remote_debugger_support offsets are relative to each PyThreadState, while the debugger_pending_call and debugger_script_path offsets are relative to each _PyRemoteDebuggerSupport structure, allowing the new structure and its fields to be found regardless of where they are in memory. debugger_script_path_size informs the attaching tool of the size of the buffer.
When a debugger wants to attach to a Python process, it follows these steps:
Once the interpreter reaches the next safe point, it will execute the Python code contained in the file specified by the debugger.
The interpreter’s regular evaluation loop already includes a check of the eval_breaker flag for handling signals, periodic tasks, and other interrupts. We leverage this existing mechanism by checking for debugger pending calls only when the eval_breaker is set, ensuring zero overhead during normal execution. This check has no overhead. Indeed, profiling with Linux perf shows this branch is highly predictable - the debugger_pending_call check is never taken during normal execution, allowing modern CPUs to effectively speculate past it.
When a debugger has set both the eval_breaker flag and debugger_pending_call, the interpreter will execute the provided debugging code at the next safe point. This all happens in a completely safe context, since the interpreter is guaranteed to be in a consistent state whenever the eval breaker is checked.
The only valid values for debugger_pending_call will initially be 0 and 1 and other values are reserved for future use.
An audit event will be raised before the code is executed, allowing this mechanism to be audited or disabled if desired by a system’s administrator.
If the code being executed raises any Python exception it will be processed as an unraisable exception in the thread where the code was executed.
To support safe execution of Python code in a remote process without having to re-implement all these steps in every tool, this proposal extends the sys module with a new function. This function allows debuggers or external tools to execute arbitrary Python code within the context of a specified Python process:
An example usage of the API would look like:
To allow redistributors, system administrators, or users to disable this mechanism, several methods will be provided to control the behavior of the interpreter:
A new PYTHON_DISABLE_REMOTE_DEBUG environment variable will be provided to control the behaviour at runtime. If set to any value (including an empty string), the interpreter will ignore any attempts to attach a debugger using this mechanism.
This environment variable will be added together with a new -X disable-remote-debug flag to the Python interpreter to allow users to disable this feature at runtime.
Additionally a new --without-remote-debug flag will be added to the configure script to allow redistributors to build Python without support for remote debugging if they so desire.
A new flag indicating the status of remote debugging will be made available via the debug offsets so tools can query if a remote process has disabled the feature. This way, tools can offer a useful error message explaining why they won’t work, instead of believing that they have attached and then never having their script run.
The overall execution pattern resembles how Python handles signals internally. The interpreter guarantees that injected code only runs at safe points, never interrupting atomic operations within the interpreter itself. This approach ensures that debugging operations cannot corrupt the interpreter state while still providing timely execution in most real-world scenarios.
However, debugging code injected through this interface can execute in any thread. This behavior is different than how Python handles signals, since signal handlers can only run in the main thread. If a debugger wants to inject code into every running thread, it must inject it into every PyThreadState. If a debugger wants to run code in the first available thread, it needs to inject it into every PyThreadState, and that injected code must check whether it has already been run by another thread (likely by setting some flag in the globals of some module).
Note that the Global Interpreter Lock (GIL) continues to govern execution as normal when the injected code runs. This means if a target thread is currently executing a C extension that holds the GIL continuously, the injected code won’t be able to run until that operation completes and the GIL becomes available. However, the interface introduces no additional GIL contention beyond what the injected code itself requires. Importantly, the interface remains fully compatible with Python’s free-threaded mode.
It may be useful for a debugger that injected some code to be run to follow that up by sending some pre-registered signal to the process, which can interrupt any blocking I/O or sleep states waiting for external resources, and allow a safe opportunity to run the injected code.
This change has no impact on existing Python code or interpreter performance. The added fields are only accessed during debugger attachment, and the checking mechanism piggybacks on existing interpreter safe points.
This interface does not introduce new security concerns as it is only usable by processes that can already write to arbitrary memory within a given process and execute arbitrary code on the machine (in order to create the file containing the Python code to be executed).
Furthermore, the execution of the code is gated by the interpreter’s audit hooks, which can be used to monitor or prevent the execution of the code in sensitive environments.
Existing operating system security mechanisms are effective for guarding against attackers gaining arbitrary memory write access. Although the PEP doesn’t specify how memory should be written to the target process, in practice this will be done using standard system calls that are already being used by other debuggers and tools. Some examples are:
All mechanisms ensure that:
The memory operations themselves are well-established and have been used safely for decades in tools like GDB, LLDB, and various system profilers.
It’s important to note that any attempt to attach to a Python process via this mechanism would be detectable by system-level monitoring tools as well as by Python audit hooks. This transparency provides an additional layer of accountability, allowing administrators to audit debugging operations in sensitive environments.
Further, the strict reliance on OS-level security controls ensures that existing system policies remain effective. For enterprise environments, this means administrators can continue to enforce debugging restrictions using standard tools and policies without requiring additional configuration. For instance, leveraging Linux’s ptrace_scope or macOS’s taskgated to restrict debugger access will equally govern the proposed interface.
By maintaining compatibility with existing security frameworks, this design ensures that adopting the new interface requires no changes to established.
Additionally, the fact that the code to be executed is gated by the interpreter’s audit hooks means that the execution of the code can be monitored and controlled by system administrators. This means that even if the attacker has compromised the application and the filesystem, leveraging this interface for malicious purposes provides a very risky proposition for an attacker, as they risk exposing their actions to system administrators that could not only detect the attack but also take action to prevent it.
Finally, is important to note that if an attacker has arbitrary memory write access to a process and has compromised the filesystem, they can already escalate to arbitrary code execution using other existing mechanisms, so this interface does not introduce any new risks in this scenario.
For tool authors, this interface becomes the standard way to implement debugger attachment, replacing unsafe system debugger approaches. A section in the Python Developer Guide could describe the internal workings of the mechanism, including the debugger_support offsets and how to interact with them using system APIs.
End users need not be aware of the interface, benefiting only from improved debugging tool stability and reliability.
A reference implementation with a prototype adding remote support for pdb can be found here.
We have chosen to have debuggers write the path to a file containing Python code into a buffer in the remote process. This has been deemed more secure than writing the Python code to be executed itself into a buffer in the remote process, because it means that an attacker who has gained arbitrary writes in a process but not arbitrary code execution or file system manipulation can’t escalate to arbitrary code execution through this interface.
This does require the attaching debugger to pay close attention to filesystem permissions when creating the file containing the code to be executed, however. If an attacker has the ability to overwrite the file, or to replace a symlink in the file path to point to somewhere attacker controlled, this would allow them to force their malicious code to be executed rather than the code the debugger intends to run.
During the review of this PEP it has been suggested using a single shared buffer at the runtime level for all debugger communications. While this appeared simpler and required less memory, we discovered it would actually prevent scenarios where multiple debuggers need to coordinate operations across different threads, or where a single debugger needs to orchestrate complex debugging operations. A single shared buffer would force serialization of all debugging operations, making it impossible for debuggers to work independently on different threads.
The per-thread buffer approach, despite its memory overhead in highly threaded applications, enables these important debugging scenarios by allowing each debugger to communicate independently with its target thread.
We would like to thank CF Bolz-Tereick for their insightful comments and suggestions when discussing this proposal.
This document is placed in the public domain or under the CC0-1.0-Universal license, whichever is more permissive.
Source: https://github.com/python/peps/blob/main/peps/pep-0768.rst
Last modified: 2025-10-04 13:46:29 UTC