ptrace POKETEXT修改程序文本的工作原理及权限相关技术问询
1. Working Mechanism of PTRACE_POKETEXT for Modifying Program Text
PTRACE_POKETEXT is a ptrace request that lets a tracing process write data into the address space of a traced process—originally built for modifying text segments (executable code), though on most modern architectures it’s functionally identical to PTRACE_POKEDATA (which handles general data writes). Here’s the step-by-step breakdown:
- First, the tracing process must have the traced process paused (usually via sending
SIGSTOPor catching a signal that triggers a stop, like a breakpoint). - The tracing process calls
ptrace(PTRACE_POKETEXT, traced_pid, target_address, data):- The kernel validates that the tracing process has the necessary privileges (it must be the parent of the traced process, or hold
CAP_SYS_PTRACEcapabilities). - The kernel directly accesses the traced process’s memory address space, writing the
data(typically a word-sized value matching the architecture’s pointer width) totarget_address.
- The kernel validates that the tracing process has the necessary privileges (it must be the parent of the traced process, or hold
- After the write completes, the tracing process can resume the traced process with
PTRACE_CONTor another resume request.
Crucially, all this happens through the kernel as an intermediary—no cooperation from the traced process is required beyond being in a stopped state.
2. Bypassing Read-Only Permissions & Visibility of Permission Changes
Short answer: PTRACE_POKETEXT doesn’t "bypass" read-only permissions directly, but the kernel temporarily modifies the target page’s permissions to allow writing, then restores them afterward. This permission change is completely invisible to the traced process.
Let’s elaborate:
- When the kernel processes a PTRACE_POKETEXT request, it checks the page’s current permissions. If the page is marked read-only (common for text/executable segments), the kernel will:
- Temporarily flip the page’s permissions to read-write.
- Execute the write operation to the target address.
- Revert the page’s permissions back to their original read-only state.
- The traced process never detects this temporary permission shift because:
- The traced process is stopped for the entire duration of the ptrace operation.
- When it resumes execution, the page permissions are already restored to their original state. Any memory accesses the traced process makes afterward will behave as if the page was never made writable.
- This works because ptrace operates at the kernel level, where it has full control over process memory permissions—user-space processes (including the traced one) can’t observe these transient kernel-internal changes.
内容的提问来源于stack exchange,提问作者budchan chao

