Skip to content

feat(ptrace): implement ptrace - #2198

Merged
fslongjin merged 15 commits into
DragonOS-Community:masterfrom
oeasy1412:feat-ptrace
Aug 28, 2026
Merged

feat(ptrace): implement ptrace#2198
fslongjin merged 15 commits into
DragonOS-Community:masterfrom
oeasy1412:feat-ptrace

Conversation

@oeasy1412

@oeasy1412 oeasy1412 commented Aug 16, 2026

Copy link
Copy Markdown
Member

Summary

This PR adds a Linux 6.6-compatible ptrace foundation to DragonOS and integrates it with signals, syscall dispatch, seccomp, process lifecycle events, wait/zombie ownership, remote memory access, x86 debug traps, and uprobes.

The implementation has been reworked from a single large ptrace file into a small set of ownership-oriented modules. It intentionally keeps one ptrace state machine, the existing scheduler state, and the existing global relation transaction lock; it does not add a second scheduler model, a generic command framework, production test hooks, or a new global sleeping lock.

Architecture

flowchart LR
    ABI["sys_ptrace.rs<br/>ABI dispatch"] --> OP["operation.rs<br/>generation-bound request guard"]
    HOOKS["signal / syscall / fork / exec / exit / seccomp"] --> CORE["ptrace/mod.rs<br/>stop and event orchestration"]
    CORE --> LIFE["lifecycle.rs<br/>cross-object lifecycle transactions"]
    CORE --> STOP["stop.rs<br/>typed stop/session state"]
    OP --> STOP
    OP --> REL["relation.rs<br/>ownership and O(1) relation index"]
    LIFE --> REL
    LIFE --> STOP
    OP --> REMOTE["remote_access.rs<br/>shared cross-mm access"]
    ABI_TYPES["abi.rs<br/>requests, options, events, syscall-info"] --> CORE
Loading

Module responsibilities

Module Responsibility
ptrace/abi.rs Linux ptrace requests, options, event encodings, register and syscall-info ABI
ptrace/stop.rs Active stop phase, pending stop, completed resume, freeze owner, and generation transitions
ptrace/relation.rs Bidirectional tracer/tracee ownership, permissions, session generation, and O(1) slot-based link/unlink
ptrace/lifecycle.rs Attach/seize/detach, wait/zombie handoff, tracer exit, fork inheritance, group-stop, and SIGCONT transactions
ptrace/operation.rs Stable register, memory, siginfo, sigmask, and event-message operations through PtraceRequestGuard
ptrace/mod.rs Signal-delivery, syscall, debug-trap, and option-gated event orchestration

Each PCB embeds one PtraceTask ownership header:

  • PtraceRelations owns the tracer, tracee vector, O(1) tracee slot, and monotonic session generation.
  • A single irq-safe PtraceState lock owns stop, resume, pending-event, freeze, EXITKILL, and x86 debug state.
  • PTRACE_RELATION_LOCK remains the transaction boundary for relation changes. Fallible allocations are prepared outside irq-disabled critical sections and revalidated before an infallible commit.

State and lifecycle model

A scheduler stop is represented as one typed active phase:

stateDiagram-v2
    [*] --> NoActiveStop
    NoActiveStop --> Traced: publish stop generation N
    Traced --> Listening: PTRACE_LISTEN
    Traced --> NoActiveStop: resume / detach / fatal / reset
    Listening --> NoActiveStop: retrap / detach / fatal / reset
Loading

Pending event stops, completed resume records, and request freezes are deliberately separate overlays because they can coexist with an active Traced or Listening stop.

Important lifecycle guarantees:

  • Every relation has a monotonic session generation. Pending stops, events, waits, debug handoffs, fork inheritance, and request guards are bound to the exact session that created them.
  • PtraceRequestGuard installs a (session_generation, stop_generation) freeze owner, rejects fatal-signal races, waits for running == false, and revalidates ownership before exposing a kernel-stack TrapFrame.
  • Detach, resume, LISTEN, tracer exit, fatal wakeup, and reset consume or revoke the same freeze token and replay a deferred fatal wake exactly once.
  • PTRACE_O_EXITKILL is published as an irrevocable teardown verdict in the old relation transaction, preventing it from being redirected into a replacement tracing session.
  • Traced zombies use an explicit claimed state so exactly one tracer waiter owns the handoff before the real parent receives the final exit status.
  • Multithreaded group-stop uses a shared generation and pending participant count. Counted and uncounted tickets cover normal participants and threads cloned into an already completed group-stop without introducing a second job-control framework.
  • Typed event outcomes distinguish Disabled, NotCommitted, and Committed, so EXEC, SECCOMP, SIGCONT, and other events cannot leak from an old tracer session into a new one.

Implemented ptrace behavior

Relationships and execution control

  • PTRACE_TRACEME, PTRACE_ATTACH, PTRACE_SEIZE, and PTRACE_DETACH
  • PTRACE_CONT, PTRACE_SYSCALL, PTRACE_SINGLESTEP
  • PTRACE_SYSEMU and PTRACE_SYSEMU_SINGLESTEP
  • PTRACE_INTERRUPT, PTRACE_LISTEN, and PTRACE_EVENT_STOP
  • Concurrent attach/seize ownership, tracer exit, group-stop preservation, EXITKILL, and clean-session takeover

Register, signal, and event ABI

  • PTRACE_GETREGS / PTRACE_SETREGS
  • PTRACE_GETREGSET / PTRACE_SETREGSET for NT_PRSTATUS
  • PTRACE_PEEKUSER / PTRACE_POKEUSER, including x86 DR0-DR7
  • PTRACE_GETSIGINFO / PTRACE_SETSIGINFO
  • PTRACE_GETSIGMASK / PTRACE_SETSIGMASK
  • PTRACE_SETOPTIONS, PTRACE_GETEVENTMSG, and PTRACE_GET_SYSCALL_INFO
  • Linux-compatible siginfo union conversion and partial register-set behavior

Supported event options include TRACESYSGOOD, TRACEFORK, TRACEVFORK, TRACECLONE, TRACEEXEC, TRACEVFORKDONE, TRACEEXIT, TRACESECCOMP, and EXITKILL. PTRACE_O_SUSPEND_SECCOMP is intentionally rejected with EINVAL because DragonOS does not implement seccomp suspension.

Syscall, seccomp, signal, and process lifecycle integration

  • Signal-delivery stops allow the tracer to suppress or replace a signal while preserving Linux siginfo semantics.
  • Syscall entry/exit stops support syscall-number and argument rewriting, negative syscall sentinels, SYSEMU, TRACESYSGOOD, and syscall-info snapshots.
  • SECCOMP_RET_TRACE uses a typed event result and reloads the syscall number plus all six arguments after a committed TRACE stop.
  • Fork/clone/vfork, exec, exit, and vfork-done events are bound to the captured tracing session.
  • Traditional EXEC fallback emits a bare SIGTRAP only when the captured session had the event disabled; an event from a vanished session is not redirected to a new tracer.
  • /proc/<pid>/status reports the actual tracer TID in the reader's PID namespace.

Remote memory access

AddressSpace::access_remote_vm() is the shared cross-mm engine for ptrace memory requests, /proc/<pid>/mem, and process_vm_readv/writev.

  • Ptrace and proc-mem use forced-access semantics; process_vm_* respects normal VMA permissions.
  • Access control follows dumpability, same-user-namespace credentials, capability-subset checks, CAP_SYS_PTRACE, and Yama-style policy.
  • Transfers return Linux-compatible precise short counts across local or remote holes and share one iovec cursor, including zero-length segments and the 1024-iovec limit.
  • Managed pages are pinned while PTE identity is validated, but the mm lock is released before copying.
  • Forced writes perform COW where required, preserve MAP_PRIVATE backing, and publish page-cache dirty generation before modifying shared file-backed bytes.
  • RISC-V forced remote writes use per-mm stale CPU masks and SBI RFENCE synchronization so modified executable code is not observed through a stale I-cache.
  • Generic VM_IO / VM_PFNMAP / unsupported external-PFN mappings remain rejected; no unsafe special-VMA callback or FUSE-DAX workaround is introduced.

x86_64 debug, segment, and uprobe integration

  • Hardware breakpoints, watchpoints, single-step, ICEBP, virtual DR6, RF handling, and debug-register context switching are implemented without leaking state between tasks or tracing sessions.
  • User #BP/#DB routing coordinates ptrace and uprobe XOL completion: a real uprobe completion is consumed by XOL, while unrelated single-step or hardware-breakpoint causes continue through the ptrace/SIGTRAP path.
  • CS/SS must be non-zero RPL3 selectors; DS/ES/FS/GS must be zero or RPL3. Selectors are truncated to the architectural low 16 bits before validation.
  • SETREGS/SETREGSET preserve Linux's sequential per-word partial-commit behavior after validating the complete user range.
  • FS/GS selectors and bases are stored together and restored with both CR4.FSGSBASE and legacy descriptor-owned base semantics.
  • Missing data-segment descriptors are cleared through exception-table-protected loaders. Invalid CS/SS values reach the real iret fault path with the original faulting frame preserved.
  • Context switch and VMX host transitions preserve DS/ES/FS/GS selectors and bases; the GS selector loader uses an irq-safe, exception-protected SWAPGS sequence.

GDB validation

The original contributor's GDB validation captures are retained below as real-world debugger evidence:

GDB ptrace validation GDB ptrace validation continuation

Validation

All checks below apply to head 415b079254fdf6f15ee62fa753e92107f86aecdc.

Gate Result
Build Check PASS: x86_64, RISC-V, and LoongArch builds, format checks, and kernel static checks
Dunitest x86_64 PASS
x86_64 integration/syscall tests PASS
MM host tests PASS
Local Ubuntu 24.04 x86_64, 2-vCPU full dunitest 1172 total / 1143 passed / 29 environment skips / 0 failed / 0 timed out
Linux and DragonOS targeted x86 ptrace register/debug oracle 12/12 passed on each
Final three-role adversarial review No remaining major or critical findings
Codex review of the current head No major issues found

The gVisor ptrace blocklist is empty. The DragonOS runner declares only the verified INT3:TRUE platform capability, so the Int3 test executes instead of being skipped.

Explicit scope limits

  • Only NT_PRSTATUS is implemented for GETREGSET/SETREGSET; FP/XSTATE regsets are future work.
  • PTRACE_O_SUSPEND_SECCOMP is not implemented and returns EINVAL.
  • Generic remote access to special/external-PFN VMAs is not implemented without a safe provider contract.
  • RISC-V runtime guest and virtiofs-DAX device testing are not claimed; cross-architecture build/static checks do not replace those runtime tests.
  • The VMX selector/base paths are build- and code-review-validated; direct KVM runtime validation is currently limited by an unrelated existing VM-exit todo!().

@github-actions github-actions Bot added enhancement New feature or request test Unitest/User space test labels Aug 16, 2026
@fslongjin

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b06e133273

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/process/syscall/sys_ptrace.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/process/syscall/sys_ptrace.rs Outdated
Comment thread kernel/src/arch/x86_64/syscall/mod.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/filesystem/procfs/pid/mem.rs Outdated
@oeasy1412
oeasy1412 force-pushed the feat-ptrace branch 3 times, most recently from 27a3212 to b087c14 Compare August 21, 2026 14:48
@oeasy1412 oeasy1412 changed the title feat(ptrace): feat(ptrace): implement ptrace Aug 21, 2026

@fslongjin fslongjin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the substantial work on this ptrace implementation. The request coverage is broad, the state/event organization is moving in a useful direction, and the latest revision fixes several issues raised on the earlier commit. I also verified that the current commit builds successfully with make kernel.

I am requesting changes because the remaining issues cross kernel security and lifetime boundaries rather than being isolated compatibility details:

  • register access does not yet own a provably frozen tracee context, so GETREGS/SETREGS can race with a fatal-signal wakeup;
  • the ptrace/proc-mem permission model is incomplete around dumpability and FSCREDS;
  • x86 hardware breakpoints can target kernel execution and DR7 is not fully validated;
  • remote writes bypass MM/page-cache dirtying;
  • several new integration paths can lose syscall-stop, scheduling, or timer events, and the mm teardown path adds an O(N) process-table scan to exec/exit.

The common architectural theme is ownership. The generic ptrace layer should own tracer relationships and stop/event transitions; the scheduler should provide a frozen-context contract; the architecture backend should validate registers and user-only hardware breakpoints; and the MM layer should own remote-memory/COW/page-cache semantics. This does not require overengineering, but those boundaries need to be explicit before the feature can safely expose write/control operations.

Please also add focused regression coverage for the races and permission transitions above. The current integration run is encouraging, but PtraceTest.Int3 is still blocklisted and several YAMA/PR_SET_PTRACER cases are skipped, so the passing suite does not exercise these failure modes. Once the lifetime, permission, debug-register, and remote-MM issues are addressed, I would be happy to review the next revision.

Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/filesystem/procfs/pid/mem.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/process/ptrace.rs Outdated
Comment thread kernel/src/syscall/mod.rs Outdated
Comment thread kernel/src/process/manager/sched.rs Outdated
Comment thread kernel/src/process/posix_timer.rs Outdated
Comment thread kernel/src/process/manager/exit.rs Outdated
@oeasy1412
oeasy1412 requested a review from fslongjin August 23, 2026 14:53
@fslongjin

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 39b77beb4b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread kernel/src/process/execve.rs Outdated
Comment thread kernel/src/mm/remote_access.rs Outdated
Comment thread kernel/src/arch/x86_64/ipc/signal.rs Outdated
Comment thread kernel/src/mm/syscall/sys_process_vm.rs Outdated
Signed-off-by: aLinChe <1129332011@qq.com>
Signed-off-by: aLinChe <1129332011@qq.com>
Signed-off-by: aLinChe <1129332011@qq.com>
Signed-off-by: aLinChe <1129332011@qq.com>
Signed-off-by: aLinChe <1129332011@qq.com>
Signed-off-by: aLinChe <1129332011@qq.com>
Signed-off-by: longjin <longjin@dragonos.org>
Signed-off-by: longjin <longjin@dragonos.org>
@fslongjin

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2f1796ca38

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread kernel/src/syscall/mod.rs Outdated
Comment thread kernel/src/mm/remote_access.rs
Comment thread kernel/src/process/syscall/sys_ptrace.rs Outdated
Comment thread kernel/src/process/syscall/sys_ptrace.rs
fslongjin and others added 2 commits August 27, 2026 16:20
Translate the Chinese comments and human-readable string messages in the
newly added or modified lines of this PR's changes into idiomatic
English, so that the new change set contains no Chinese comments.

Covers 56 files across the ptrace/uprobe/signal/syscall/mm/sched
subsystems and their related dunitest suites. Only comment and doc text
was translated; code, identifiers, and formatting are unchanged. Rust
code is formatted via `make fmt`.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: longjin <longjin@dragonos.org>
Signed-off-by: longjin <longjin@dragonos.org>
Signed-off-by: longjin <longjin@dragonos.org>
Signed-off-by: longjin <longjin@dragonos.org>
@fslongjin

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6bda640eca

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread kernel/src/process/syscall/sys_ptrace.rs
Comment thread kernel/src/syscall/mod.rs
Comment thread kernel/src/filesystem/procfs/pid/status.rs Outdated
Signed-off-by: longjin <longjin@dragonos.org>
@fslongjin

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c8e784b647

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread kernel/src/ipc/signal_types.rs Outdated
Comment thread kernel/src/process/syscall/sys_ptrace.rs
Comment thread kernel/src/process/syscall/sys_personality.rs
Signed-off-by: longjin <longjin@dragonos.org>

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ee3efcf1eb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread kernel/src/process/ptrace/operation.rs Outdated
Comment thread kernel/src/process/ptrace/operation.rs
Signed-off-by: longjin <longjin@dragonos.org>

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 415b079254

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions github-actions Bot removed the test Unitest/User space test label Aug 28, 2026
@fslongjin
fslongjin merged commit 5a0707b into DragonOS-Community:master Aug 28, 2026
35 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants