ptwrite uprobes v2
Subsystems (9)
uprobes currently always require entering the kernel to log anything. While that works well, it is rather slow.
Modern Intel CPUs have the ptwrite instruction, which can log data to the Processor Trace buffer without entering the kernel.
This patch adds support in uprobes to patch in ptwrites instead of the normal probes. If a user collects Processor Trace with perf the logged data will appear in the PT log, otherwise the instructions will be nops.
The benefit is much faster logging, but it also has a lot of limitations. There is little filtering (other than what perf or PT can do), no EBPF, there are restrictions on what can be logged, and of course it depends on PT being recorded.
For more details and performance numbers see the Documentation patch, but it's multiple orders of magnitude faster than classic uprobes.
This is v2 of the patchkit with various cleanups, fixes, simplifications. It fixes the VMA iterator bug that caused crashes, as well
as addressing a lot of Sashiko feedback.
I stripped it down to only the minimal kernel code without the user tools with minimal dependencies. The fault handling is deferred for now.
Comments welcome.
RFC PATCH v2 1/11 ptwrite uprobes: Add infrastructure for ptwrite uprobes
uprobes currently always require entering the kernel to log anything. While that works well, it is rather slow.
Modern Intel CPUs have the ptwrite instruction, which can log data to the Processor Trace buffer. Add support in uprobes for patching PTWRITE instead of kernel entries. When a user collects Processor Trace with perf the logged data will appear in the PT log, otherwise the instructions will be nops.
PTWRITE provides much faster logging, but it is missing various features that the full featured probes have.
The instrumentation is similar to optimized uprobes. Add a trampoline page. Replace the original instruction (5 byte nop) with a jump to the trampoline. The nop restriction will be relaxed in a later patch. The trampoline does ptwrites and then jumps back.
Build the high-level infrastructure without any x86-64-specific parts (except for one data structure). Add register/unregister, basic data structures and high level hooks. Add weak stubs to handle the no uprobes or different architectures case.
--- arch/Kconfig | 3 + include/linux/uprobes.h | 77 +++++++++++++++++++- kernel/events/uprobes.c | 151 ++++++++++++++++++++++++++++++++++++++++ kernel/fork.c | 1 + 4 files changed, 230 insertions(+), 2 deletions(-)
arch/Kconfig +3 -0
@@ -208,6 +208,9 @@ config UPROBES managed by the kernel and kept transparent to the probed application. ) +config ARCH_HAS_UPROBES_PTWRITE + bool + config HAVE_64BIT_ALIGNED_ACCESS def_bool 64BIT && !HAVE_EFFICIENT_UNALIGNED_ACCESS help
include/linux/uprobes.h +75 -2
116 lines not on this page · raw message
kernel/events/uprobes.c +151 -0
187 lines not on this page · raw message
kernel/fork.c +1 -0
@@ -1076,6 +1076,7 @@ static void mm_init_uprobes_state(struct mm_struct *mm) {#ifdef CONFIG_UPROBES mm->uprobes_state.xol_area =NULL ; +arch_uprobe_init_state (mm);#endif }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 01/11] ptwrite uprobes: Add infrastructure for ptwrite uprobes
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 17 lines
uprobes currently always require entering the kernel to log anything. While that works well, it is rather slow.
Modern Intel CPUs have the ptwrite instruction, which can log data to the Processor Trace buffer. Add support in uprobes for patching PTWRITE instead of kernel entries. When a user collects Processor Trace with perf the logged data will appear in the PT log, otherwise the instructions will be nops.
PTWRITE provides much faster logging, but it is missing various features that the full featured probes have.
The instrumentation is similar to optimized uprobes. Add a trampoline page. Replace the original instruction (5 byte nop) with a jump to the trampoline. The nop restriction will be relaxed in a later patch. The trampoline does ptwrites and then jumps back.
Quoted 7 lines
Build the high-level infrastructure without any x86-64-specific parts (except for one data structure). Add register/unregister, basic data structures and high level hooks. Add weak stubs to handle the no uprobes or different architectures case.
Assisted-by omp:gpt-5.6-lunaSigned-off-by Andi Kleen <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
RFC PATCH v2 2/11 ptwrite uprobes: Add minimal low level support for x86
In reply to Andi KleenAdd more data structures and the x86 machinery to generate the PTWRITE instructions for a ptwrite uprobe. The probe executes PTWRITEs and then jumps back to the original code. In this variant only patching 5 byte nops is supported.
The instructions are pre-generated to templates and then patched when setting up the final user page.
The patching code uses 3 phase patching similar to int3_update.
The ptwrite stub emits a header with a magic value and the number of arguments, and then the actual probed values.
There is no separate config option for ptwrite uprobes, it is just tied to the main uprobes config.
Some limitations in the current implementation:
- The probed 5 byte area cannot cross a page.
- The allocated stubs in the user program are only freed on exit.
--- arch/x86/Kconfig | 1 + arch/x86/include/asm/mmu_context.h | 17 +- arch/x86/include/asm/uprobes.h | 26 ++ arch/x86/kernel/uprobes.c | 654 +++++++++++++++++++++++++++++ 4 files changed, 697 insertions(+), 1 deletion(-)
arch/x86/Kconfig +1 -0
@@ -102,6 +102,7 @@ config X86 select ARCH_HAS_HW_PTE_YOUNG select ARCH_HAS_NONLEAF_PMD_YOUNG if PGTABLE_LEVELS > 2 select ARCH_HAS_UACCESS_FLUSHCACHE if X86_64 + select ARCH_HAS_UPROBES_PTWRITE if X86_64 select ARCH_HAS_COPY_MC if X86_64 select ARCH_HAS_SET_MEMORY select ARCH_HAS_SET_DIRECT_MAP
arch/x86/include/asm/mmu_context.h +16 -1
@@ -215,12 +215,27 @@ static inline void arch_dup_pkeys(struct mm_struct *oldmm,#endif } +/* Put here to avoid asm/uprobes.h's dependencies */ +extern int uprobe_ptwrite_dup_mmap (struct mm_struct *oldmm, +struct mm_struct *newmm); +static inline int arch_dup_mmap (struct mm_struct *oldmm,struct mm_struct *mm) { +int ret; +arch_dup_pkeys (oldmm, mm);paravirt_enter_mmap (mm);dup_lam (oldmm, mm); -return ldt_dup_context (oldmm, mm); + + ret =ldt_dup_context (oldmm, mm); +if (ret) +return ret; +#ifdef CONFIG_UPROBES + ret =uprobe_ptwrite_dup_mmap (oldmm, mm); +if (ret) +return ret; +#endif +return 0 ; }static inline void arch_exit_mmap (struct mm_struct *mm)
arch/x86/include/asm/uprobes.h +26 -0
@@ -11,6 +11,7 @@*/ #include <linux/notifier.h> +#include <linux/rcupdate.h> typedef u8 uprobe_opcode_t ;
@@ -23,10 +24,34 @@ typedef u8 uprobe_opcode_t;enum {ARCH_UPROBE_FLAG_CAN_OPTIMIZE =0 ,ARCH_UPROBE_FLAG_OPTIMIZE_FAIL =1 , +ARCH_UPROBE_FLAG_PTWRITE =2 , };struct uprobe_xol_ops ; +/* +* ptwrite probe state. The stub template (code + data slots) is built +* once at registration (mm-independent except the final jmp's rel32, patched +* per-mm at install). Block layout: +* [ptwriteq hdr(%rip)] [arg emissions] [jmp probe+5] [u64 slots: header, imms] +*/ +struct uprobe_ptwrite_arch { +u8 stub[256 ]; +u8 stub_len;/* code + data, whole block */ +u8 jmp_off;/* offset of the final jmp's rel32 field */ +u8 ndata;/* number of u64 data slots */ +u8 orig[MAX_UINSN_BYTES ];/* pristine file bytes, before generic analysis */ +}; + +/* Per-mm page holding generated ptwrite stub blocks, like tramp_mapping. */ +struct uprobe_ptwrite_page { +struct hlist_node node; +struct rcu_head rcu; +struct page *page;/* stub blocks written via kmap */ +unsigned long vaddr;/* mapping base */ +u16 cursor;/* next free block offset */ +}; + struct arch_uprobe { union { u8 insn[MAX_UINSN_BYTES];
@@ -51,6 +76,7 @@ struct arch_uprobe { } push; }; +struct uprobe_ptwrite_arch ptwrite;unsigned long flags; };
arch/x86/kernel/uprobes.c +654 -0
700 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 02/11] ptwrite uprobes: Add minimal low level support for x86
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] x86/uprobes: Uninitialized variable first_phase_done causes invalid fallback - [High] x86/uprobes…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] x86/uprobes: Uninitialized variable first_phase_done causes invalid fallback
- [High] x86/uprobes: Missing __GFP_ACCOUNT bypasses memcg and GFP_KERNEL deadlocks
- [Medium] x86/uprobes: GFP_HIGHUSER allocation pins unmigratable pages in movable zones --
commit 692de39e6024ec893235089efa2253699ad076bf
Author: Andi Kleen <[email protected]>
ptwrite uprobes: Add minimal low level support for x86
Add more data structures and the x86 machinery to generate the PTWRITE instructions for a ptwrite uprobe. The probe executes PTWRITEs and then jumps back to the original code. In this variant only patching 5 byte nops is supported.
Quoted 4 lines
arch/x86/kernel/uprobes.c +0
-0
[ ... ]
Quoted 1 line
arch/x86/kernel/uprobes.c +0
-0@@ -719,6 +723,134 @@ static struct vm_area_struct *get_uprobe_trampoline(struct mm_struct *mm, unsign
[ ... ]
Quoted 11 lines
arch/x86/kernel/uprobes.c +11
-0+int uprobe_ptwrite_dup_mmap (struct mm_struct *oldmm,struct mm_struct *newmm) +{ +struct uprobes_state *old_state = &oldmm->uprobes_state; +struct uprobes_state *new_state = &newmm->uprobes_state; +struct uprobe_ptwrite_page *ptw, *new; +struct vm_area_struct *vma; +struct hlist_node *n; + +mmap_assert_write_locked (oldmm); +mmap_assert_write_locked (newmm); +hlist_for_each_entry (ptw, &old_state->head_ptwrite, node) {
arch/x86/kernel/uprobes.c static struct vm_area_struct *get_uprobe_trampoline(struct mm_struct *mm, unsign · line 818
Quoted 10 lines
arch/x86/kernel/uprobes.c +10
-0+void *src, *dst; + +/* +* Not using __GFP_ACCOUNT here because it triggered +* a deadlock. +*/ + new =kzalloc_obj (*new,GFP_KERNEL ); +if (!new) + goto fail; + new->page =alloc_page (GFP_KERNEL | __GFP_ZERO);
[Severity: High]
Does stripping __GFP_ACCOUNT here allow containers to bypass memory cgroup limits? By repeatedly forking processes with active ptwrite uprobes, a local user could potentially consume unbounded kernel memory without being charged.
Also, since this is called under the mmap_write_lock of both the old and new mm_structs, is it safe to use GFP_KERNEL allocations? GFP_KERNEL can enter direct reclaim, which might attempt to reacquire the same or other locks via page writeback or swap-out, leading to deadlocks.
[ ... ]
Quoted 1 line
arch/x86/kernel/uprobes.c +0
-0@@ -1102,6 +1287,475 @@ static int copy_from_vaddr(struct mm_struct *mm, unsigned long vaddr, void *dst,
[ ... ]
Quoted 8 lines
arch/x86/kernel/uprobes.c +8
-0+static struct uprobe_ptwrite_page * +create_uprobe_ptwrite_page (struct mm_struct *mm,unsigned long vaddr) +{ +struct uprobe_ptwrite_page *ptw; +struct vm_area_struct *vma; +unsigned long area; + + area =find_ptwrite_page_area (mm, vaddr);
arch/x86/kernel/uprobes.c static int copy_from_vaddr(struct mm_struct *mm, unsigned long vaddr, void *dst, · line 1555
Quoted 10 lines
arch/x86/kernel/uprobes.c +10
-0+if (IS_ERR_VALUE (area)) +return NULL ; + +mmap_assert_write_locked (mm); + + ptw =kzalloc_obj (*ptw,GFP_KERNEL ); +if (!ptw) +return NULL ; + + ptw->page =alloc_page (GFP_HIGHUSER | __GFP_ZERO);
[Severity: Medium]
Will this allocation pin an unmigratable page in a movable zone?
The GFP_HIGHUSER mask includes the __GFP_MOVABLE flag, but the returned page is a raw page mapped via _install_special_mapping(). Since it lacks movable_ops or LRU linkage, it is fundamentally unmigratable. This breaks the page allocator's mobility contract and can cause permanent memory fragmentation.
[ ... ]
Quoted 7 lines
arch/x86/kernel/uprobes.c +7
-0+static int ptwrite_text_poke (struct arch_uprobe *auprobe, +struct vm_area_struct *vma,unsigned long vaddr, +unsigned long stub_addr) +{ +u8 jmp5[5 ] = {0xe9 ,0 ,0 ,0 ,0 }; +bool first_phase_done; +s32 rel;
arch/x86/kernel/uprobes.c static int copy_from_vaddr(struct mm_struct *mm, unsigned long vaddr, void *dst, · line 1677
Quoted 10 lines
arch/x86/kernel/uprobes.c +10
-0+int err; + +if (!ptwrite_rel32 (vaddr +5 , stub_addr, &rel)) +return -ERANGE ; +memcpy (jmp5 +1 , &rel,4 ); + + err =text_poke_5byte (auprobe, vma, vaddr, jmp5, + auprobe->ptwrite.orig[0 ], false, true, true, + false, &first_phase_done); +if (err && first_phase_done) {
[Severity: High]
Can this evaluate uninitialized memory on the error path?
If text_poke_5byte() fails during its first uprobe_write() call (when setting the INT3 breakpoint), it returns the error immediately without initializing the first_phase_done out-parameter:
arch/x86/kernel/uprobes.c:text_poke_5byte() {
...
if (!skip_int3) {
err = uprobe_write(auprobe, vma, vaddr, &int3, 1, verify_insn,
is_register, false, &ctx);
if (err)
return err;
}
if (first_phase_done)
*first_phase_done = true;
...
}If the uninitialized first_phase_done variable happens to be non-zero (true), ptwrite_text_poke() will attempt a rollback by calling text_poke_5byte() again to remove an INT3 breakpoint that was never successfully installed, which could further fail or corrupt the instruction stream.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
RFC PATCH v2 3/11 ptwrite uprobes: Add a sample module to exercise interface
In reply to Andi KleenAdd a basic test module and a test program for uprobes ptwrite.
The module allows to configure and register a ptwrite uprobe in a executable.
Use this for testing. It is not intended as a production interface.
--- samples/Kconfig | 9 ++ samples/Makefile | 1 + samples/uprobe-ptwrite/Makefile | 9 ++ samples/uprobe-ptwrite/test_prog.c | 38 +++++ samples/uprobe-ptwrite/uprobe_ptwrite_test.c | 153 +++++++++++++++++++ 5 files changed, 210 insertions(+) create mode 100644 samples/uprobe-ptwrite/Makefile create mode 100644 samples/uprobe-ptwrite/test_prog.c create mode 100644 samples/uprobe-ptwrite/uprobe_ptwrite_test.c
samples/Kconfig +9 -0
@@ -322,6 +322,15 @@ config SAMPLE_HUNG_TASK Reading these files with multiple processes triggers hung task detection by holding locks for a long time (256 seconds). +config SAMPLE_UPROBE_PTWRITE + tristate "Build ptwrite uprobe test module -- loadable module only" + depends on UPROBES && X86_64 && m + help + Builds a prototype ptwrite uprobe driver for testing Intel PTWRITE + support. Use the module parameters to select a file, offset, arguments, + and event ID. This interface is for testing and is not intended for + production use. + source "samples/rust/Kconfig" source "samples/damon/Kconfig"
samples/Makefile +1 -0
@@ -44,4 +44,5 @@ obj-$(CONFIG_SAMPLE_DAMON_WSSE) += damon/ obj-$(CONFIG_SAMPLE_DAMON_PRCL) += damon/ obj-$(CONFIG_SAMPLE_DAMON_MTIER) += damon/ obj-$(CONFIG_SAMPLE_HUNG_TASK) += hung_task/ +obj-$(CONFIG_SAMPLE_UPROBE_PTWRITE) += uprobe-ptwrite/ obj-$(CONFIG_SAMPLE_TSM_MR) += tsm-mr/
samples/uprobe-ptwrite/Makefile new file +9 -0
@@ -0,0 +1,9 @@ +# SPDX-License-Identifier: GPL-2.0-only +# +# ptwrite uprobe prototype sample. +# +# Module build (in-tree or via make M=samples/uprobe-ptwrite). +# The userspace test target is built by the in-tree selftest harness in +# tools/testing/selftests/uprobes. + +obj-$(CONFIG_SAMPLE_UPROBE_PTWRITE) += uprobe_ptwrite_test.o
samples/uprobe-ptwrite/test_prog.c new file +38 -0
@@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* test_prog - userspace target for the ptwrite uprobe test. +* +* target() carries a 5-byte NOP (nopl 0(%rax,%rax,1) = 0f 1f 44 00 00) at +* its entry. A probe installed at that file offset emits rdi/rsi (a, b) +* via PTWRITE. In the test loop a == i and b == i + 1. +*/ +#include <stdio.h> + +#ifndef noinline +#define noinline __attribute__((noinline)) +#endif + +static noinline unsigned long +target (unsigned long a,unsigned long b) +{ +/* +* 5-byte NOP: nopl 0(%rax,%rax,1) = 0f 1f 44 00 00. +* Emitted as raw bytes: the assembler would otherwise shrink +* "nopl (%rax,%rax,1)" to the 4-byte form (0f 1f 04 00), which +* the probe site validation rejects (jmp rel32 needs 5 bytes). +*/ + asmvolatile (".globl target_site\n\t" +"target_site:\n\t" +".byte 0x0f, 0x1f, 0x44, 0x00, 0x00" ); +return a *31 + b; +} + +int main (void ) +{ +unsigned long i, acc =0 ; + +for (i =0 ; i <2000 ; i++) + acc +=target (i, i +1 ); +printf ("acc=%lu\n" , acc); +return 0 ; +}
samples/uprobe-ptwrite/uprobe_ptwrite_test.c new file +153 -0
153 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 03/11] ptwrite uprobes: Add a sample module to exercise interface
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] samples/uprobe: dead code in parse_probe_args due to loop invariants --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] samples/uprobe: dead code in parse_probe_args due to loop invariants --
commit 77dc8c84b5d7c061149ad9471b13f1d9dabd7049
Author: Andi Kleen <[email protected]>
ptwrite uprobes: Add a sample module to exercise interface
This adds a test module and userspace target program for uprobes ptwrite. The module can be configured via parameters to register a ptwrite uprobe at a specified offset and emit live registers or immediates into an Intel PT stream. It is intended strictly for testing the interface.
Quoted 4 lines
samples/uprobe-ptwrite/uprobe_ptwrite_test.c new file +0
-0
[ ... ]
Quoted 12 lines
samples/uprobe-ptwrite/uprobe_ptwrite_test.c new file +12
-0+static int parse_probe_args (void ) +{ +char *s, *p, *tok; +unsigned int n =0 ; + + s =kstrdup (args,GFP_KERNEL ); +if (!s) +return -ENOMEM ; + + p = s; +while ((tok =strsep (&p,"," )) !=NULL ) { +struct uprobe_ptwrite_arg *a;
[ ... ]
Quoted 1 line
samples/uprobe-ptwrite/uprobe_ptwrite_test.c new file +1
-0+if (tok[0 ] =='r' ) {
[ ... ]
Quoted 1 line
samples/uprobe-ptwrite/uprobe_ptwrite_test.c new file +1
-0+ }else if (tok[0 ] =='i' ) {
[ ... ]
samples/uprobe-ptwrite/uprobe_ptwrite_test.c line 94
Quoted 10 lines
samples/uprobe-ptwrite/uprobe_ptwrite_test.c new file +10
-0+ }else { +pr_err ("bad arg '%s'\n" , tok); + goto err; + } + n++; + } +if (!n) { +pr_err ("need 1..%d args\n" ,UPROBE_PTWRITE_MAX_ARGS ); + goto err; + }
[Severity: Low]
Is this zero-argument check reachable?
Because p is initialized to a non-NULL string returned by kstrdup(), the strsep() loop will always execute at least once. Inside the loop, any invalid token triggers a goto err, skipping this check entirely. If the token is valid, n is incremented.
Normal termination of the loop seems to guarantee that n >= 1, making this condition structurally dead code.
Quoted 7 lines
samples/uprobe-ptwrite/uprobe_ptwrite_test.c new file +7
-0+ desc.nargs = n; +kfree (s); +return 0 ; +err: +kfree (s); +return -EINVAL ; +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
RFC PATCH v2 4/11 ptwrite uprobes: Add support to tracing infrastructure
In reply to Andi KleenHook up the low level x86 ptwrite uprobes code to the generic trace uprobes events parser, so that the new probes can be set up. The interface is similar to classic probes, but there is new ptw: syntax and various restrictions.
Add minimal docs.
Architectures without the ptwrite backend are handled by weak stubs.
--- Documentation/trace/uprobetracer.rst | 46 +++++- arch/x86/Kconfig | 1 + arch/x86/include/asm/uprobes.h | 12 +- include/linux/uprobes.h | 4 + kernel/trace/Kconfig | 6 + kernel/trace/trace_uprobe.c | 219 +++++++++++++++++++++++++-- 6 files changed, 272 insertions(+), 16 deletions(-)
Documentation/trace/uprobetracer.rst +44 -2
@@ -19,8 +19,8 @@ However unlike kprobe-event tracer, the uprobe event interface expects the user to calculate the offset of the probepoint in the object. You can also use /sys/kernel/tracing/dynamic_events instead of -uprobe_events. That interface will provide unified access to other -dynamic events too. +uprobe_events. That interface provides unified access to other event types +too. Synopsis of uprobe_tracer -------------------------
@@ -29,6 +29,7 @@ Synopsis of uprobe_tracer p[:[GRP/][EVENT]] PATH:OFFSET [FETCHARGS] : Set a uprobe r[:[GRP/][EVENT]] PATH:OFFSET [FETCHARGS] : Set a return uprobe (uretprobe) p[:[GRP/][EVENT]] PATH:OFFSET%return [FETCHARGS] : Set a return uprobe (uretprobe) + ptw[:[GRP/][EVENT]] PATH:OFFSET [FETCHARGS] : Set a trap-free ptwrite uprobe -:[GRP/][EVENT] : Clear uprobe or uretprobe event GRP : Group name. If omitted, "uprobes" is the default value.
@@ -76,6 +77,47 @@ offset, and container-size (usually 32). The syntax is:: For $comm, the default type is "string"; any other type is invalid. +ptwrite uprobes (ptw:) +---------------------- + +See ptwrite-uprobes.rst for more details. + +A ``ptw:`` probe emits values into an Intel Processor Trace data stream. +It is faster than standard uprobes, but has restrictions. The Intel Processor +Trace recording must be configured separately. + +Requirements and restrictions: + +- Intel CPU with PTWRITE support (``/sys/devices/intel_pt/format/ptw`` must exist) +- Entry probes only: ``r:``/``%return`` and the SDT reference counter + ``(REF)`` are rejected. +- The probe site must be a 5-byte NOP or a punnable instruction (see + ptwrite-uprobes.rst). For five ``0x90`` bytes from GCC's + ``-fpatchable-function-entry=5``, append ``%multinop`` to the offset. +- The event does not produce ring-buffer records. It provides a type registry + (``events/GRP/EVENT/format``) and the wire ``event_id`` + (``events/GRP/EVENT/id``) for an external decoder. Filters and perf + attach are rejected because filtering would need kernel entry. + +Wire format: each probe hit emits a 64-bit header word ``event_id<<48 | +nargs<<40 | 0x5054525731`` followed by ``nargs`` PTWRITE payloads. Perf +exposes each payload through its existing ``u64`` field. Decode with +``perf script`` and ``tools/perf/scripts/python/uprobe-ptwrite-decode.py``: + +:: + + perf record -e intel_pt/ptw=1,fup_on_ptw=1/u -o perf.data -- ./app + perf script --itrace=qwe -s uprobe-ptwrite-decode.py + +``fup_on_ptw=1`` increases the overhead, but improves decoding reliability +because the exact IP of each probe is logged. + +Example:: + + echo 'ptw:t /bin/app:0x1234 %rdi %rsi \0x42' > /sys/kernel/tracing/uprobe_events + echo 1 > /sys/kernel/tracing/events/uprobes/t/enable + + Event Profiling --------------- You can check the total number of probe hits per event via
arch/x86/Kconfig +1 -0
@@ -423,6 +423,7 @@ config HAVE_INTEL_TXT config ARCH_SUPPORTS_UPROBES def_bool y + select UPROBE_EVENTS_PTWRITE if X86_64 && UPROBE_EVENTS config FIX_EARLYCON_MEM def_bool y
arch/x86/include/asm/uprobes.h +10 -2
@@ -29,6 +29,14 @@ enum {struct uprobe_xol_ops ; +/* +* Stub block array size. Worst case = 250 B (8 MEM args, rsp bases, fault +* table); 288 leaves 38 B slack. A file-scope static_assert in +* arch/x86/kernel/uprobes.c re-derives the worst case; prepare() also +* enforces it with -E2BIG at runtime. +*/ +#define UPROBE_PTWRITE_STUB_SIZE 288 +/* * ptwrite probe state. The stub template (code + data slots) is built * once at registration (mm-independent except the final jmp's rel32, patched
@@ -36,8 +44,8 @@ struct uprobe_xol_ops;* [ptwriteq hdr(%rip)] [arg emissions] [jmp probe+5] [u64 slots: header, imms] */ struct uprobe_ptwrite_arch { -u8 stub[256 ]; -u8 stub_len;/* code + data, whole block */ +u8 stub[UPROBE_PTWRITE_STUB_SIZE ]; +u16 stub_len;/* code + data + fault table, whole block */ u8 jmp_off;/* offset of the final jmp's rel32 field */ u8 ndata;/* number of u64 data slots */ u8 orig[MAX_UINSN_BYTES ];/* pristine file bytes, before generic analysis */
include/linux/uprobes.h +4 -0
@@ -205,8 +205,12 @@ struct uprobes_state {enum uprobe_ptwrite_src {UPROBE_PTW_SRC_REG ,/* value = live GPR (index in .reg) */ UPROBE_PTW_SRC_IMM ,/* value = constant (.val), stored in stub data slot */ +UPROBE_PTW_SRC_MEM ,/* value = [.reg + disp32] (v2); requires ALLOW_MEM */ }; +/* uprobe_ptwrite_desc.flags */ +#define UPROBE_PTWRITE_FL_ALLOW_MEM BIT(0)/* SRC_MEM args enabled */ +struct uprobe_ptwrite_arg {u8 src;/* enum uprobe_ptwrite_src */ u8 reg;/* x86-64 GPR index (0=rax..15=r15) for SRC_REG */
kernel/trace/Kconfig +6 -0
@@ -848,6 +848,12 @@ config UPROBE_EVENTS This option is required if you plan to use perf-probe subcommand of perf tools on user space applications. +config UPROBE_EVENTS_PTWRITE + bool + depends on UPROBE_EVENTS + help + ptwrite uprobes ("ptw:" tracefs event type). + config EPROBE_EVENTS bool "Enable event-based dynamic events" depends on TRACING
kernel/trace/trace_uprobe.c +207 -12
341 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 04/11] ptwrite uprobes: Add support to tracing infrastructure
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] trace: AA deadlock on event_mutex in trace_uprobe_enable() --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] trace: AA deadlock on event_mutex in trace_uprobe_enable()
--
commit 18294b1032dd2887acf440ab9d7029011a171000
Author: Andi Kleen <[email protected]>
ptwrite uprobes: Add support to tracing infrastructure
This commit hooks up the low-level x86 ptwrite uprobes code to the generic trace uprobes events parser. It introduces a new ptw: syntax to set up trap-free ptwrite uprobes and handles architectures without the backend via weak stubs.
Quoted 3 lines
kernel/trace/trace_uprobe.c +0
-0
[ ... ]
Quoted 4 lines
kernel/trace/trace_uprobe.c +0
-0@@ -1107,9 +1241,26 @@ static int trace_uprobe_enable(struct trace_uprobe *tu, filter_func_t filter) {struct inode *inode =d_real_inode (tu->path.dentry);struct uprobe *uprobe;
kernel/trace/trace_uprobe.c static int trace_uprobe_enable(struct trace_uprobe *tu, filter_func_t filter) · line 1251
Quoted 10 lines
kernel/trace/trace_uprobe.c +7
-2+struct file *file; - tu->consumer.filter = filter; - uprobe =uprobe_register (inode, tu->offset, tu->ref_ctr_offset, &tu->consumer); +if (tu->is_ptwrite) { +if (filter) { +/* PTWRITE probes have no kernel entry to evaluate a filter. */ +return -EINVAL ; + } + file =dentry_open (&tu->path,O_RDONLY ,current_cred ());
[Severity: High]
Can this dentry_open() call cause an AA deadlock on event_mutex?
If a user creates a ptwrite uprobe targeting a tracefs file (like events/sched/sched_switch/enable) and then writes 1 to the uprobe's enable file, event_enable_write() acquires event_mutex before calling trace_uprobe_enable().
When dentry_open() is called synchronously on that tracefs path, its f_op->open (e.g. tracing_open_file_tr()) will attempt to acquire event_mutex again, leading to a system hang.
Quoted 8 lines
kernel/trace/trace_uprobe.c +8
-0+if (IS_ERR (file)) +return PTR_ERR (file); + tu->ptwrite_desc.event_id = +trace_probe_event_call (&tu->tp)->event.type; + uprobe =uprobe_register_ptwrite (inode, file, tu->offset, + &tu->consumer, &tu->ptwrite_desc); +fput (file); + }else {
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
RFC PATCH v2 5/11 ptwrite uprobes: Factor file-backed instruction reads
In reply to Andi KleenRefactor copy_insn into a more generic uprobe_copy_from_file. The existing copy_insn is still there, but uses the generic version now. The generic version will be used in later patches.
No semantic change intended.
--- include/linux/uprobes.h | 2 ++ kernel/events/uprobes.c | 59 +++++++++++++++++++++++++++++------------ 2 files changed, 44 insertions(+), 17 deletions(-)
include/linux/uprobes.h +2 -0
@@ -304,6 +304,8 @@ extern void uprobe_handle_trampoline(struct pt_regs *regs);extern void *arch_uretprobe_trampoline (unsigned long *psize);extern unsigned long uprobe_get_trampoline_vaddr (void );extern void uprobe_copy_from_page (struct page *page,unsigned long vaddr,void *dst,int len); +extern int uprobe_copy_from_file (struct inode *inode,struct file *file, +loff_t offset,void *buf,int size);extern void arch_uprobe_clear_state (struct mm_struct *mm);extern void arch_uprobe_init_state (struct mm_struct *mm);extern void handle_syscall_uprobe (struct pt_regs *regs,unsigned long bp_vaddr);
kernel/events/uprobes.c +42 -17
72 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 05/11] ptwrite uprobes: Factor file-backed instruction reads
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 8 lines
Refactor
copy_insninto a more genericuprobe_copy_from_file. The existingcopy_insnis still there, but uses the generic version now. The generic version will be used in later patches.No semantic change intended.
Assisted-by omp:gpt-5.6-lunaSigned-off-by Andi Kleen <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
RFC PATCH v2 6/11 ptwrite uprobes: Add basic memory references
In reply to Andi KleenAdd support for memory references. Currently this is only simple cases, no indirect memory references or strings, that would require saving/restoring registers. Only 8 and 4 byte memory references are supported.
This doesn't have any fault handling yet, so a bad reference in the probe could result in crashing the application.
It increases the kernel memory overhead of each probe to roughly 1 KB.
--- Documentation/trace/uprobetracer.rst | 7 ++ arch/x86/include/asm/uprobes.h | 2 +- arch/x86/kernel/uprobes.c | 90 +++++++++++++++++--- include/linux/uprobes.h | 4 +- samples/uprobe-ptwrite/uprobe_ptwrite_test.c | 40 ++++++++- 5 files changed, 128 insertions(+), 15 deletions(-)
Documentation/trace/uprobetracer.rst +7 -0
@@ -94,6 +94,13 @@ Requirements and restrictions: - The probe site must be a 5-byte NOP or a punnable instruction (see ptwrite-uprobes.rst). For five ``0x90`` bytes from GCC's ``-fpatchable-function-entry=5``, append ``%multinop`` to the offset. +- FETCHARGS: register names (``%di``, ``%r8``, ...), ``$stack`` (the + stack pointer value), immediates (``\IMM``), and memory sources: + ``$stackN`` (the Nth stack slot, ``[%rsp + 8N]``) and ``+off(FETCHARG)`` + dereferences (for example, ``+8(%di)`` = ``[%rdi + 8]``). ``u64`` sources + use ``ptwriteq``; ``u32``/``s32``/``x32`` sources use ``ptwritel`` and read + four bytes. Strings, bitfields, and indirect dereferences are not supported. +- Memory accesses can fault. - The event does not produce ring-buffer records. It provides a type registry (``events/GRP/EVENT/format``) and the wire ``event_id`` (``events/GRP/EVENT/id``) for an external decoder. Filters and perf
arch/x86/include/asm/uprobes.h +1 -1
@@ -45,7 +45,7 @@ struct uprobe_xol_ops;*/ struct uprobe_ptwrite_arch {u8 stub[UPROBE_PTWRITE_STUB_SIZE ]; -u16 stub_len;/* code + data + fault table, whole block */ +u16 stub_len;/* code + data, whole block */ u8 jmp_off;/* offset of the final jmp's rel32 field */ u8 ndata;/* number of u64 data slots */ u8 orig[MAX_UINSN_BYTES ];/* pristine file bytes, before generic analysis */
arch/x86/kernel/uprobes.c +80 -10
159 lines not on this page · raw message
include/linux/uprobes.h +2 -2
@@ -213,10 +213,10 @@ enum uprobe_ptwrite_src {struct uprobe_ptwrite_arg {u8 src;/* enum uprobe_ptwrite_src */ -u8 reg;/* x86-64 GPR index (0=rax..15=r15) for SRC_REG */ +u8 reg;/* x86-64 GPR index (0=rax..15=r15) for SRC_REG/SRC_MEM */ u8 size;/* declared type size 1/2/4/8 (decoder hint) */ u8 reserved; -u64 val;/* SRC_IMM: constant; SRC_REG: unused */ +u64 val;/* SRC_IMM: constant, SRC_MEM: disp32 (low 32 bits) */ };struct uprobe_ptwrite_desc {
samples/uprobe-ptwrite/uprobe_ptwrite_test.c +38 -2
@@ -11,9 +11,11 @@* Usage (module params): * path=/path/to/prog file to probe * offset=0xADDR file offset of the probe site -* args="r0,r1,i0x42" comma-separated; +* args="r0,r1,i0x42,m3,m2:0x8,m4:0x10:4" comma-separated; * r<N> = x86-64 GPR index 0..15, * i<hex> = immediate constant, +* m<N>[:<disp>][:<size>] = memory arg [reg + disp32], +* size 4 (u32 load) or 8 (u64 load, default) * event_id=0x1234 identifier carried in the PTW header word */ #include <linux/module.h>
@@ -81,7 +83,41 @@ static int parse_probe_args(void) } a->src =UPROBE_PTW_SRC_IMM ; a->val = v; - + }else if (tok[0 ] =='m' ) { +/* +* m<R>[:<disp>][:<size>]: memory arg [reg + disp32], +* size 4 (u32 load) or 8 (u64 load, default) +*/ +char *colon =strchr (tok,':' ); +char *szs =NULL ; +unsigned long reg; +long long disp =0 ; +unsigned long size =8 ; + +if (colon) { + *colon ='\0' ; + szs =strchr (colon +1 ,':' ); +if (szs) + *szs++ ='\0' ; + } +if (kstrtoul (tok +1 ,10 , ®) || reg >15 ) { +pr_err ("bad mem reg '%s'\n" , tok); + goto err; + } +if (colon &&kstrtoll (colon +1 ,0 , &disp)) { +pr_err ("bad mem disp '%s'\n" , colon +1 ); + goto err; + } +if (szs && (kstrtoul (szs,10 , &size) || + (size !=4 && size !=8 ))) { +pr_err ("bad mem size '%s'\n" , szs); + goto err; + } + a->src =UPROBE_PTW_SRC_MEM ; + a->reg = reg; + a->val = (u64 )(s32 )disp; + a->size = size; + desc.flags |=UPROBE_PTWRITE_FL_ALLOW_MEM ; }else {pr_err ("bad arg '%s'\n" , tok); goto err;
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 06/11] ptwrite uprobes: Add basic memory references
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] x86/uprobes: missing disp32 emission for memory args causes invalid reads --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] x86/uprobes: missing disp32 emission for memory args causes invalid reads --
commit a6d11e7a0c907a2ea16451bbea72e2f4d6ed70e8
Author: Andi Kleen <[email protected]>
ptwrite uprobes: Add basic memory references
Add support for memory references. Currently this is only simple cases, no indirect memory references or strings, that would require saving/restoring registers. Only 8 and 4 byte memory references are supported.
Quoted 3 lines
arch/x86/kernel/uprobes.c +0
-0
[ ... ]
Quoted 1 line
arch/x86/kernel/uprobes.c +0
-0@@ -1431,24 +1463,62 @@ int arch_uprobe_ptwrite_prepare(struct arch_uprobe *auprobe,
[ ... ]
Quoted 3 lines
arch/x86/kernel/uprobes.c +1
-1for (i =0 ; i < desc->nargs; i++) { -if (desc->args[i].src ==UPROBE_PTW_SRC_REG ) { +switch (desc->args[i].src) {
[ ... ]
Quoted 8 lines
arch/x86/kernel/uprobes.c +8
-0+case UPROBE_PTW_SRC_MEM : { +u8 reg = desc->args[i].reg; +bool wide = desc->args[i].size ==8 ; +unsigned int arg_len = (wide ?9 :8 ) + + ((reg &7 ) ==4 ) + (!wide && (reg &8 )); + +PTW_NEED (arg_len); + *p++ =0xf3 ;
arch/x86/kernel/uprobes.c int arch_uprobe_ptwrite_prepare(struct arch_uprobe *auprobe, · line 1514
Quoted 10 lines
arch/x86/kernel/uprobes.c +10
-0+if (wide) + *p++ = (reg &8 ) ?0x49 :0x48 ;/* REX.W */ +else if (reg &8 ) + *p++ =0x41 ;/* REX.B only (32-bit operand) */ + *p++ =0x0f ; + *p++ =0xae ; + *p++ =0xa0 | (reg &7 );/* mod 10, reg /4, rm reg */ +if ((reg &7 ) ==4 )/* SIB escape: base rsp/esp/r12 */ + *p++ =0x24 ; + p +=4 ;
[Severity: High]
Does this code miss copying the displacement value for the memory access?
The stub generator in arch_uprobe_ptwrite_prepare() for memory fetch arguments (UPROBE_PTW_SRC_MEM) configures the ptwrite instruction to use a 32-bit displacement (mod=10) and advances the instruction pointer p by 4 bytes. However, it appears to fail to write the requested user displacement (desc->args[i].val) into those 4 bytes, leaving them as uninitialized zeroes.
Will the generated uprobe stub execute a memory fetch with a displacement of 0 (e.g., reading [reg + 0] instead of [reg + disp32])? This could cause the traced application to read incorrect memory, which can lead to capturing garbage data in the trace or crashing the application with an unintended SIGSEGV.
Quoted 4 lines
arch/x86/kernel/uprobes.c +2
-0+break ; + } } }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
RFC PATCH v2 7/11 ptwrite uprobes: Add multinop support
In reply to Andi KleenGCC's -fpatchable-function-entry=5 may emit five one-byte NOPs. Normally that's not safe to patch because some might jump into a later nop. But for the gcc case it's safe because nobody jumps into the nops. Add a %multinop that allows the user opting into patching these sites. This way patching for the gcc instrumentation works.
--- arch/x86/include/asm/uprobes.h | 24 ++++++-- arch/x86/kernel/uprobes.c | 63 +++++++++++++++++--- include/linux/uprobes.h | 2 + kernel/trace/trace_uprobe.c | 58 +++++++++++++----- samples/uprobe-ptwrite/uprobe_ptwrite_test.c | 6 ++ 5 files changed, 126 insertions(+), 27 deletions(-)
arch/x86/include/asm/uprobes.h +19 -5
@@ -30,12 +30,23 @@ enum {struct uprobe_xol_ops ;/* -* Stub block array size. Worst case = 250 B (8 MEM args, rsp bases, fault -* table); 288 leaves 38 B slack. A file-scope static_assert in -* arch/x86/kernel/uprobes.c re-derives the worst case; prepare() also -* enforces it with -E2BIG at runtime. +* Stub block size. Conservative worst case is 298 bytes: 9-byte header, +* one lead fence, eight 21-byte memory forms with one 3-byte fence each, +* a 16-byte original-instruction copy, a 5-byte return jump, alignment, +* and 66 bytes of data/fault metadata. 384 leaves room. A static_assert in +* arch/x86/kernel/uprobes.c checks the bound; prepare() also checks it with +* -E2BIG. */ -#define UPROBE_PTWRITE_STUB_SIZE 288 +#define UPROBE_PTWRITE_STUB_SIZE 384 + + +/* +* Word pacing: insert this many LFENCEs between emitted ptwrite words and +* before the first word, unless UPROBE_PTWRITE_FL_NO_LEAD_PACE is requested. +*/ +#define UPROBE_PTWRITE_SERIALIZE_LFENCES 1/* LFENCEs per word gap */ +/* The encoded LFENCE instruction occupies three bytes. */ +#define UPROBE_PTWRITE_LFENCE_SIZE 3/* * ptwrite probe state. The stub template (code + data slots) is built
@@ -49,6 +60,9 @@ struct uprobe_ptwrite_arch {u8 jmp_off;/* offset of the final jmp's rel32 field */ u8 ndata;/* number of u64 data slots */ u8 orig[MAX_UINSN_BYTES ];/* pristine file bytes, before generic analysis */ +u16 ft_off;/* fault table offset within the block (0 if none) */ +u8 nft;/* number of fault entries */ +bool allow_nop_run;/* accept a five-byte run of 0x90 */ };/* Per-mm page holding generated ptwrite stub blocks, like tramp_mapping. */
arch/x86/kernel/uprobes.c +55 -8
111 lines not on this page · raw message
include/linux/uprobes.h +2 -0
@@ -210,6 +210,8 @@ enum uprobe_ptwrite_src {/* uprobe_ptwrite_desc.flags */ #define UPROBE_PTWRITE_FL_ALLOW_MEM BIT(0)/* SRC_MEM args enabled */ +#define UPROBE_PTWRITE_FL_NO_LEAD_PACE BIT(1)/* don't slow down probes */ +#define UPROBE_PTWRITE_FL_ALLOW_NOP_RUN BIT(2)/* accept five 1-byte NOPs */ struct uprobe_ptwrite_arg {u8 src;/* enum uprobe_ptwrite_src */
kernel/trace/trace_uprobe.c +44 -14
106 lines not on this page · raw message
samples/uprobe-ptwrite/uprobe_ptwrite_test.c +6 -0
@@ -17,6 +17,7 @@* m<N>[:<disp>][:<size>] = memory arg [reg + disp32], * size 4 (u32 load) or 8 (u64 load, default) * event_id=0x1234 identifier carried in the PTW header word +* allow_nop_run=1 accept five one-byte NOPs at the site */ #include <linux/module.h> #include <linux/uprobes.h>
@@ -36,6 +37,10 @@ static ushort event_id = 0x1234;module_param (event_id, ushort,0444 );MODULE_PARM_DESC (event_id,"event id carried in the PTW header word" ); +static bool allow_nop_run; +module_param (allow_nop_run, bool,0444 ); +MODULE_PARM_DESC (allow_nop_run,"accept five one-byte NOPs at the site" ); +static char *args ="r0" ;module_param (args, charp,0444 );MODULE_PARM_DESC (args,"comma-separated args: r<N> GPR, i<hex> immediate, m<N>[:disp][:4|8] memory" );
@@ -142,6 +147,7 @@ static int __init uprobe_ptwrite_test_init(void)int ret; desc.event_id = event_id; + desc.flags = allow_nop_run ?UPROBE_PTWRITE_FL_ALLOW_NOP_RUN :0 ; ret =parse_probe_args ();if (ret)return ret;
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 07/11] ptwrite uprobes: Add multinop support
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] uprobes: unused ft_off and nft fields in uprobe_ptwrite_arch --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] uprobes: unused ft_off and nft fields in uprobe_ptwrite_arch
--
commit 45ecb87404a0455ddedb4d1415f99bbe867523b6
Author: Andi Kleen <[email protected]>
ptwrite uprobes: Add multinop support
This commit introduces support for a %multinop feature in ptwrite uprobes, which allows users to opt into patching five one-byte NOPs emitted by GCC. It updates the ptwrite stub generation and the trace_uprobe parser to handle this new argument.
Quoted 4 lines
arch/x86/include/asm/uprobes.h +0
-0
[ ... ]
arch/x86/include/asm/uprobes.h struct uprobe_ptwrite_arch { · line 64
Quoted 6 lines
arch/x86/include/asm/uprobes.h +2
-0@@ -49,6 +60,9 @@ struct uprobe_ptwrite_arch {u8 jmp_off;/* offset of the final jmp's rel32 field */ u8 ndata;/* number of u64 data slots */ u8 orig[MAX_UINSN_BYTES ];/* pristine file bytes, before generic analysis */ +u16 ft_off;/* fault table offset within the block (0 if none) */ +u8 nft;/* number of fault entries */
[Severity: Low]
Are the ft_off and nft fields necessary? They appear to be completely unused throughout the entire patch series after being added to struct uprobe_ptwrite_arch here.
Quoted 2 lines
arch/x86/include/asm/uprobes.h +1
-0+bool allow_nop_run;/* accept a five-byte run of 0x90 */ };
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
RFC PATCH v2 8/11 ptwrite uprobes: Support instruction punning
In reply to Andi KleenThe previous ptwrite instrumentation only worked on 5 byte+ nops because it needs to patch in a 5 byte branch.
However that is somewhat limiting because it means most code cannot be probed. Use a simplified variant of the instruction punning technique from Chamith et al. "Instruction Punning: Lightweight instrumentation for x86-64". Patch only the one-byte branch opcode and reuse the existing 4 following bytes in the code as the branch target.
If someone branches to the remaining bytes they are still executed in the original way because they didn't change.
This requires placing a target trampoline page at the right address. If the area is not available or points to kernel space it doesn't work.
In general it is somewhat unreliable for non PIE executables because the target is often negative and ends up in kernel space. However on modern Linux distributions near all binaries are PIE and high up in the address space with ample gaps around them, which makes punning much more successful.
Testing every instruction in a PIE-linked Debian 13 /bin/bash:
- bash has around 210k instructions
- of which around 10k are directly patchable 5 byte nops
- running bash for 100 times with ASLR 76.4% of the instructions are always pun probeable
- with 23% of the instruction never being punnable
- the rest sometimes depending on ASLR luck.
So punning is not perfect, but it works most of the time for these kind of binaries, and is much better than just nops.
If the probing fails it's possible for the harness to move the probe around until it finds a better target. Sometimes you're just lucky on rerun with ASLR. Or alternatively just use a classic uprobe.
Return unique errnos for all instruction error cases so the harness can make informed decisions.
Add the low-level machinery for punning. Classify
the instruction, poke the target and map trampolines to the right place. Various special cases are not supported to simplify the code.
One difference to the nop probing is that the previous instruction needs to be copied and fixed up (analogous to classic uprobes)
The punning technique could be also used with optimized uprobes, but this patch only applies it to ptwrite probes.
--- arch/x86/include/asm/uprobes.h | 24 +- arch/x86/kernel/uprobes.c | 460 ++++++++++++++++++++++++++++++--- include/linux/uprobes.h | 4 +- kernel/events/uprobes.c | 18 +- 4 files changed, 461 insertions(+), 45 deletions(-)
arch/x86/include/asm/uprobes.h +21 -3
@@ -39,6 +39,8 @@ struct uprobe_xol_ops;*/ #define UPROBE_PTWRITE_STUB_SIZE 384 +/* the out-of-line original-instruction copy slot (x86 max insn length) */ +#define UPROBE_PTWRITE_COPY_SIZE MAX_UINSN_BYTES/* * Word pacing: insert this many LFENCEs between emitted ptwrite words and
@@ -50,14 +52,19 @@ struct uprobe_xol_ops;/* * ptwrite probe state. The stub template (code + data slots) is built -* once at registration (mm-independent except the final jmp's rel32, patched -* per-mm at install). Block layout: -* [ptwriteq hdr(%rip)] [arg emissions] [jmp probe+5] [u64 slots: header, imms] +* once at registration. Only the final jmp's rel32 and the copy's +* disp/rel fields are patched per-mm at install. Block layout: +* [ptwriteq hdr(%rip)] [arg emissions] [orig-insn copy] +* [jmp probe+len] [u64 slots: header, imms] */ struct uprobe_ptwrite_arch {u8 stub[UPROBE_PTWRITE_STUB_SIZE ];u16 stub_len;/* code + data, whole block */ u8 jmp_off;/* offset of the final jmp's rel32 field */ +u8 copy_off;/* offset of the out-of-line instruction copy */ +u8 len;/* copy length (0 = drop); back-jmp = vaddr+len */ +u8 disp_off;/* rip-relative disp32 offset in the copy (0 = none) */ +s32 disp;/* original disp32 (delta-patched per-mm) */ u8 ndata;/* number of u64 data slots */ u8 orig[MAX_UINSN_BYTES ];/* pristine file bytes, before generic analysis */ u16 ft_off;/* fault table offset within the block (0 if none) */
@@ -72,6 +79,17 @@ struct uprobe_ptwrite_page {struct page *page;/* stub blocks written via kmap */ unsigned long vaddr;/* mapping base */ u16 cursor;/* next free block offset */ +u16 nblocks; +struct { +u16 off;/* block offset in the page */ +u16 len;/* generated block length */ +u8 orig0;/* original site byte 0 (pun restore) */ +u8 pun;/* instruction-pun mechanism (single-byte poke) */ +u8 site_len;/* original instruction length (pun identity) */ +s32 site_off;/* probe site - page base (idempotent reinstall) */ +u8 site_insn[MAX_UINSN_BYTES ];/* original bytes (pun identity) */ + } index[PAGE_SIZE /32 ];/* exact: min block = 32 B (nargs >= 1), */ +/* so <= 128 blocks fit a page */ };struct arch_uprobe {
arch/x86/kernel/uprobes.c +424 -36
565 lines not on this page · raw message
include/linux/uprobes.h +3 -1
@@ -250,7 +250,9 @@ extern struct uprobe *uprobe_register_ptwrite(struct inode *inode, const struct uprobe_ptwrite_desc *desc);extern bool arch_uprobe_ptwrite_supported (void );extern int arch_uprobe_ptwrite_prepare (struct arch_uprobe *auprobe, -const struct uprobe_ptwrite_desc *desc); +struct inode *inode,struct file *file, +loff_t offset, +const struct uprobe_ptwrite_desc *desc);extern int arch_uprobe_install_ptwrite (struct arch_uprobe *auprobe,struct vm_area_struct *vma,unsigned long vaddr);
kernel/events/uprobes.c +13 -5
@@ -1509,6 +1509,8 @@ bool __weak arch_uprobe_ptwrite_supported(void) }int __weak arch_uprobe_ptwrite_prepare (struct arch_uprobe *auprobe, +struct inode *inode,struct file *file, +loff_t offset,const struct uprobe_ptwrite_desc *desc) {return -EOPNOTSUPP ;
@@ -1586,13 +1588,19 @@ struct uprobe *uprobe_register_ptwrite(struct inode *inode, struct file *file, ret = -EBUSY ; goto out; } - -/* Build the mm-independent stub template once, at registration. */ - ret =arch_uprobe_ptwrite_prepare (&uprobe->arch, desc); +/* +* Prepare the immutable PTWRITE stub before exposing the uprobe. The +* copy-instruction flag also keeps the normal XOL preparation path out. +*/ + ret =copy_insn (uprobe, file);if (ret) goto out; - - + ret =arch_uprobe_ptwrite_prepare (&uprobe->arch, inode, file, offset, + desc); +if (ret) + goto out; +smp_wmb (); +set_bit (UPROBE_COPY_INSN , &uprobe->flags);set_bit (UPROBE_PTWRITE , &uprobe->flags);consumer_add (uprobe, uc); ret =register_for_each_vma (uprobe, uc);
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 08/11] ptwrite uprobes: Support instruction punning
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 15 lines
The previous ptwrite instrumentation only worked on 5 byte+ nops because it needs to patch in a 5 byte branch.
However that is somewhat limiting because it means most code cannot be probed. Use a simplified variant of the instruction punning technique from Chamith et al. "Instruction Punning: Lightweight instrumentation for x86-64". Patch only the one-byte branch opcode and reuse the existing 4 following bytes in the code as the branch target.
If someone branches to the remaining bytes they are still executed in the original way because they didn't change.
This requires placing a target trampoline page at the right address. If the area is not available or points to kernel space it doesn't work.
Quoted 6 lines
[ ... ]
The punning technique could be also used with optimized uprobes, but this patch only applies it to ptwrite probes.Assisted-by omp:gpt-5.6-lunaSigned-off-by Andi Kleen <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
RFC PATCH v2 9/11 ptwrite uprobes: Use atomic patching for multinop sites
In reply to Andi KleenThe earlier multinop patching is not quite safe because the cross modified CPU could be already executing on a later nop when the cross patching occurs. The Intel SDM allows cross modification by larger stores as long as they are aligned. AMD has a similar guarantee.
Support GCC function-entry patch sites is the main motivation for multinop, and these sites are always aligned.
So enforce 8 bytes alignment of the multinop and use a safe RMW 8 byte store to overwrite the 5 byte sequence. This assumes that the code is not changing in parallel, but if that happens cross modification safety is probably the smallest of the issues.
--- arch/x86/kernel/uprobes.c | 183 +++++++++++++++++++++++--------------- kernel/events/uprobes.c | 15 +++- 2 files changed, 123 insertions(+), 75 deletions(-)
arch/x86/kernel/uprobes.c +109 -74
@@ -17,6 +17,7 @@#include <linux/kdebug.h> #include <linux/highmem.h> #include <linux/mm.h> +#include <linux/security.h> #include <asm/processor.h> #include <asm/insn.h> #include <asm/insn-eval.h>
@@ -828,6 +829,8 @@ int uprobe_ptwrite_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)kunmap_local (src); new->vaddr = ptw->vaddr; new->cursor = ptw->cursor; + new->nblocks = ptw->nblocks; +memcpy (new->index, ptw->index,sizeof (new->index)); vma =install_uprobe_ptwrite_vma (newmm, new->vaddr);if (IS_ERR (vma)) {
@@ -1448,7 +1451,7 @@ static_assert((((9 + UPROBE_PTWRITE_SERIALIZE_LFENCES *UPROBE_PTWRITE_MAX_ARGS * (10 +UPROBE_PTWRITE_SERIALIZE_LFENCES *UPROBE_PTWRITE_LFENCE_SIZE ) + - 5 + 7) & ~7) + + UPROBE_PTWRITE_COPY_SIZE + 5 + 7) & ~7) + 8 * (1 + UPROBE_PTWRITE_MAX_ARGS)) <=UPROBE_PTWRITE_STUB_SIZE , "worst-case ptwrite stub block exceeds UPROBE_PTWRITE_STUB_SIZE");
@@ -1460,6 +1463,7 @@ static bool ptwrite_has_room(const u8 *base, const u8 *p, size_t len) }static bool pun_site_is_nop (const u8 *orig,bool allow_nop_run); +static bool ptwrite_site_is_multinop (const u8 *orig,bool allow_nop_run);static int pun_classify_insn (struct insn *insn,u8 *disp_off,s32 *disp); static int pun_decode_site(struct inode *inode, struct file *file, loff_t offset, u8 *copy,
@@ -1494,7 +1498,18 @@ int arch_uprobe_ptwrite_prepare(struct arch_uprobe *auprobe,return -EINVAL ;/* The generic registration path copied these bytes before this hook. */ + ptw->allow_nop_run = + desc->flags &UPROBE_PTWRITE_FL_ALLOW_NOP_RUN ;memcpy (ptw->orig, auprobe->insn,sizeof (ptw->orig)); +/* +* File mappings preserve page offsets, so an unaligned file offset +* cannot become an aligned runtime address. Reject it before the probe +* is exposed; install-time failures for a future mapping are otherwise +* not observable through the tracefs enable operation. +*/ +if (ptwrite_site_is_multinop (ptw->orig, ptw->allow_nop_run) && + !IS_ALIGNED (offset,sizeof (u64))) +return -EINVAL ;for (i =0 ; i < desc->nargs; i++) {switch (desc->args[i].src) {
@@ -1618,7 +1633,7 @@ int arch_uprobe_ptwrite_prepare(struct arch_uprobe *auprobe, ptw->stub_len = data_off +8 * (1 + n_imm); ptw->ndata =1 + n_imm; - ptw->allow_nop_run = desc->flags &UPROBE_PTWRITE_FL_ALLOW_NOP_RUN ; + ret = pun_decode_site(inode, file, offset, code + ptw->copy_off, &ptw->disp_off, &ptw->disp,
@@ -1753,8 +1768,9 @@ get_uprobe_ptwrite_page(struct mm_struct *mm, unsigned long vaddr, }/* -* A run of short NOPs is accepted only when requested. This validation does -* not make the three-phase poke safe for threads that already passed byte 0. +* A run of short NOPs is accepted only when requested. It is patched with +* an aligned eight-byte read-modify-write, preserving the following bytes; +* code is not expected to change concurrently. */ static bool ptwrite_is_nop_run (const u8 *orig) {
@@ -1940,6 +1956,42 @@ static int ptwrite_text_poke(struct arch_uprobe *auprobe,return err; } +/* +* Replace an aligned five-byte NOP run with a JMP in one eight-byte store. +* The trailing three bytes are read from the existing text. We assume +* nobody else is changing it. This is covered by the Intel/AMD "aligned store" +* cross modifying guarantee. +*/ +static int ptwrite_multinop_text_poke (struct arch_uprobe *auprobe, +struct vm_area_struct *vma, +unsigned long vaddr, +unsigned long stub_addr) +{ +struct mm_struct *mm = vma->vm_mm; +struct write_opcode_ctx ctx = { + .base = vaddr, + .expect =EXPECT_BYTE , + .expect_byte =0x90 , + }; +u8 patch[sizeof (u64)]; +s32 rel; +int err; + +if (!IS_ALIGNED (vaddr,sizeof (u64))) +return -EINVAL ; +if (!ptwrite_rel32 (vaddr +5 , stub_addr, &rel)) +return -ERANGE ; + err =copy_from_vaddr (mm, vaddr, patch,sizeof (patch)); +if (err) +return err; + patch[0 ] =0xe9 ; +memcpy (&patch[1 ], &rel,sizeof (rel)); + err =uprobe_write (auprobe, vma, vaddr, patch,sizeof (patch), + verify_insn, true, false, &ctx); +if (!err) +smp_text_poke_sync_each_cpu (); +return err; +} static int pun_text_poke(struct arch_uprobe *auprobe, struct vm_area_struct *vma, unsigned long vaddr, u8 e9,
@@ -1971,65 +2023,40 @@ static int pun_install(struct arch_uprobe *auprobe,unsigned long t, page_base, block_off, stub_addr;s64 site_delta, target;s32 jump_rel, disp32, orig_rel; -u8 site_len;bool found = false; -bool nop_fallback =ptwrite_site_is_multinop (orig, - ptw_a->allow_nop_run) && - (vaddr &7 );u8 *kaddr;int b, ret;mmap_assert_write_locked (mm); -if (nop_fallback) { -hlist_for_each_entry (ptw, &state->head_ptwrite, node) { - site_delta = (s64 )vaddr - (s64 )ptw->vaddr; -if (site_delta <INT_MIN || site_delta >INT_MAX ) -continue ; -for (b =0 ; b <smp_load_acquire (&ptw->nblocks); b++) -if (!ptw->index[b].pun && - ptw->index[b].site_off == (s32 )site_delta && - ptw->index[b].site_len ==5 && - !memcmp (ptw->index[b].site_insn, orig,5 )) -break ; -if (b >=smp_load_acquire (&ptw->nblocks)) -continue ; -if (!__in_uprobe_ptwrite (mm, ptw->vaddr)) -continue ; -return ptwrite_text_poke (auprobe, vma, vaddr, - ptw->vaddr + ptw->index[b].off); +memcpy (&orig_rel, orig +1 ,sizeof (orig_rel)); + target = (s64 )vaddr +5 + (s64 )orig_rel; +if (target <PAGE_SIZE || target >=TASK_SIZE_MAX ) +return -EADDRNOTAVAIL ; + t = (unsigned long )target; + page_base = t &PAGE_MASK ; + ret =security_mmap_addr (page_base); +if (ret) +return ret; + block_off = t & (PAGE_SIZE -1 ); +if (block_off + ptw_a->stub_len >PAGE_SIZE ) +return -ENOSPC ; + +/* Reuse an existing ptwrite page at the target, else map a new one. */ +hlist_for_each_entry (ptw, &state->head_ptwrite, node) { +if (ptw->vaddr == page_base) { + found = true; +break ; } - ptw =get_uprobe_ptwrite_page (mm, vaddr, ptw_a->stub_len); + } +if (!found) { +if (vma_lookup (mm, page_base)) +return -EADDRNOTAVAIL ; + ptw =create_uprobe_ptwrite_page_at (mm, page_base);if (!ptw)return -ENOMEM ; - block_off = ptw->cursor; - }else { -memcpy (&orig_rel, orig +1 ,sizeof (orig_rel)); - target = (s64 )vaddr +5 + (s64 )orig_rel; -if (target <PAGE_SIZE || target >=TASK_SIZE_MAX ) -return -EADDRNOTAVAIL ; - t = (unsigned long )target; - page_base = t &PAGE_MASK ; - block_off = t & (PAGE_SIZE -1 ); -if (block_off + ptw_a->stub_len >PAGE_SIZE ) -return -ENOSPC ; - -/* reuse an existing ptwrite page at the target, else map a new one */ -hlist_for_each_entry (ptw, &state->head_ptwrite, node) { -if (ptw->vaddr == page_base) { - found = true; -break ; - } - } -if (!found) { -if (vma_lookup (mm, page_base)) -return -EADDRNOTAVAIL ;/* target page occupied */ - ptw =create_uprobe_ptwrite_page_at (mm, page_base); -if (!ptw) -return -ENOMEM ; -/* Order page initialization before publishing it to fault readers. */ -smp_wmb (); -hlist_add_head_rcu (&ptw->node, &state->head_ptwrite); - } +/* Publish initialized page fields before fault readers find it. */ +smp_wmb (); +hlist_add_head_rcu (&ptw->node, &state->head_ptwrite); } site_delta = (s64 )vaddr - (s64 )ptw->vaddr;
@@ -2068,19 +2095,13 @@ static int pun_install(struct arch_uprobe *auprobe, disp32 = (s32 )d; } -/* -* A NOP fallback needs a synthetic rel32 at the site, so it uses -* the full five-byte poke and restore path rather than punning. -*/ - site_len = nop_fallback ?5 : ptw_a->len; ptw->index[ptw->nblocks].off = block_off; ptw->index[ptw->nblocks].len = ptw_a->stub_len; - ptw->index[ptw->nblocks].pun = !nop_fallback; + ptw->index[ptw->nblocks].pun =1 ; ptw->index[ptw->nblocks].orig0 = orig[0 ]; - ptw->index[ptw->nblocks].site_len = site_len; + ptw->index[ptw->nblocks].site_len = ptw_a->len; ptw->index[ptw->nblocks].site_off = (s32 )site_delta; -memcpy (ptw->index[ptw->nblocks].site_insn, ptw_a->orig, site_len); -smp_store_release (&ptw->nblocks, ptw->nblocks +1 ); +memcpy (ptw->index[ptw->nblocks].site_insn, ptw_a->orig, ptw_a->len); kaddr =kmap_local_page (ptw->page);memcpy (kaddr + block_off, ptw_a->stub, ptw_a->stub_len);
@@ -2089,11 +2110,10 @@ static int pun_install(struct arch_uprobe *auprobe,memcpy (kaddr + block_off + ptw_a->copy_off + ptw_a->disp_off, &disp32,sizeof (disp32));kunmap_local (kaddr); +/* Publish initialized metadata before exposing the probe jump. */ +smp_store_release (&ptw->nblocks, ptw->nblocks +1 ); -if (nop_fallback) - ret =ptwrite_text_poke (auprobe, vma, vaddr, stub_addr); -else - ret =pun_text_poke (auprobe, vma, vaddr,0xe9 , &ctx); + ret =pun_text_poke (auprobe, vma, vaddr,0xe9 , &ctx);if (ret) {/* Publish rollback before readers observe the reduced block count. */ smp_store_release (&ptw->nblocks, ptw->nblocks -1 );
@@ -2129,6 +2149,9 @@ int arch_uprobe_install_ptwrite(struct arch_uprobe *auprobe, ret =copy_from_vaddr (mm, vaddr, orig,sizeof (orig));if (ret)return ret; +if (ptwrite_site_is_multinop (orig, ptw_a->allow_nop_run) && + !IS_ALIGNED (vaddr,sizeof (u64))) +return -EINVAL ;if (ptwrite_is_installed (mm, vaddr, orig))return 0 ;
@@ -2151,8 +2174,13 @@ int arch_uprobe_install_ptwrite(struct arch_uprobe *auprobe,continue ;if (!__in_uprobe_ptwrite (mm, ptw->vaddr))continue ; -return ptwrite_text_poke (auprobe, vma, vaddr, - ptw->vaddr + ptw->index[b].off); +if (ptwrite_site_is_multinop (orig, ptw_a->allow_nop_run)) + ret =ptwrite_multinop_text_poke (auprobe, vma, vaddr, + ptw->vaddr + ptw->index[b].off); +else + ret =ptwrite_text_poke (auprobe, vma, vaddr, + ptw->vaddr + ptw->index[b].off); +return ret; } ptw =get_uprobe_ptwrite_page (mm, vaddr, ptw_a->stub_len);if (!ptw)
@@ -2186,10 +2214,17 @@ int arch_uprobe_install_ptwrite(struct arch_uprobe *auprobe,memcpy (kaddr + block_off + ptw_a->jmp_off, &rel,sizeof (rel));kunmap_local (kaddr); - ret =ptwrite_text_poke (auprobe, vma, vaddr, stub_addr); -if (!ret) - ptw->cursor = block_off + ptw_a->stub_len; -return ret; +if (ptwrite_site_is_multinop (orig, ptw_a->allow_nop_run)) + ret =ptwrite_multinop_text_poke (auprobe, vma, vaddr, stub_addr); +else + ret =ptwrite_text_poke (auprobe, vma, vaddr, stub_addr); +if (ret) { +/* Publish rollback before readers use the reduced block count. */ +smp_store_release (&ptw->nblocks, ptw->nblocks -1 ); +return ret; + } + ptw->cursor = block_off + ptw_a->stub_len; +return 0 ; } int arch_uprobe_uninstall_ptwrite(struct arch_uprobe *auprobe,
kernel/events/uprobes.c +14 -1
@@ -192,7 +192,20 @@ void uprobe_copy_from_page(struct page *page, unsigned long vaddr, void *dst, instatic void copy_to_page (struct page *page,unsigned long vaddr,const void *src,int len) {void *kaddr =kmap_local_page (page); -memcpy (kaddr + (vaddr & ~PAGE_MASK ), src, len); +void *dst = kaddr + (vaddr & ~PAGE_MASK ); + +/* +* Atomic eight-byte stores are required for safe cross-modification of +* live user text; other writes use the ordinary byte-copy path. +*/ +if (len ==sizeof (u64) &&IS_ALIGNED (vaddr,sizeof (u64))) { +u64 value; + +memcpy (&value, src,sizeof (value)); +WRITE_ONCE (*(u64 *)dst, value); + }else { +memcpy (dst, src, len); + }kunmap_local (kaddr); }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 09/11] ptwrite uprobes: Use atomic patching for multinop sites
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
The earlier multinop patching is not quite safe because the cross modified CPU could be already executing on a later nop when the cross patching occurs. The Intel SDM allows cross modification by larger stores as long as they are aligned. AMD has a similar guarantee.
Support GCC function-entry patch sites is the main motivation for multinop, and these sites are always aligned.
Quoted 7 lines
So enforce 8 bytes alignment of the multinop and use a safe RMW 8 byte store to overwrite the 5 byte sequence. This assumes that the code is not changing in parallel, but if that happens cross modification safety is probably the smallest of the issues.
Assisted-by omp:gpt-5.6-lunaSigned-off-by Andi Kleen <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
RFC PATCH v2 10/11 ptwrite uprobes: Add a tutorial and overview documentation
In reply to Andi KleenDocument the PTWRITE uprobe interface, syntax, requirements, limitations, and usage examples.
--- Documentation/trace/index.rst | 1 + Documentation/trace/ptwrite-uprobes.rst | 387 ++++++++++++++++++++++++ 2 files changed, 388 insertions(+) create mode 100644 Documentation/trace/ptwrite-uprobes.rst
Documentation/trace/index.rst +1 -0
@@ -90,6 +90,7 @@ interactions. .. toctree:: :maxdepth: 1 + ptwrite-uprobes user_events uprobetracer
Documentation/trace/ptwrite-uprobes.rst new file +387 -0
387 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 10/11] ptwrite uprobes: Add a tutorial and overview documentation
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines
Document the PTWRITE uprobe interface, syntax, requirements, limitations, and usage examples.
Assisted-by omp:gpt-5.6-lunaSigned-off-by Andi Kleen <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
RFC PATCH v2 11/11 ptwrite uprobes: Add kernel self tests
In reply to Andi KleenAdd kernel selftests for PTWRITE uprobes. Exercise instruction punning, multinop patching, fork/exec, and removal of probes.
--- tools/testing/selftests/Makefile | 1 + .../test.d/kprobe/uprobe_syntax_errors.tc | 40 ++++ tools/testing/selftests/uprobes/Makefile | 14 ++ tools/testing/selftests/uprobes/ptw_probe.c | 156 +++++++++++++ tools/testing/selftests/uprobes/run_ptw.sh | 219 ++++++++++++++++++ 5 files changed, 430 insertions(+) create mode 100644 tools/testing/selftests/uprobes/Makefile create mode 100644 tools/testing/selftests/uprobes/ptw_probe.c create mode 100755 tools/testing/selftests/uprobes/run_ptw.sh
tools/testing/selftests/Makefile +1 -0
@@ -135,6 +135,7 @@ TARGETS += tpm2 TARGETS += tty TARGETS += ublk TARGETS += uevent +TARGETS += uprobes TARGETS += user_events TARGETS += vDSO TARGETS += mm
tools/testing/selftests/ftrace/test.d/kprobe/uprobe_syntax_errors.tc +40 -0
@@ -33,4 +33,44 @@ if grep -q "\$current.*" README; then check_error 'p /bin/sh:10 ^$current:u8' # BAD_VAR fi +# ptwrite options may be written as an offset suffix or as separate tokens. +# Use /bin/sh's executable entry so registration reaches the parser options. +ptw_off= +if command -v readelf >/dev/null 2>&1; then + ptw_entry=$(readelf -hW /bin/sh | + awk '/Entry point address:/{print $NF; exit}') + ptw_load_off=$(readelf -lW /bin/sh | + awk '$1 == "LOAD" && $0 ~ / R E/ {print $2; exit}') + ptw_load_vaddr=$(readelf -lW /bin/sh | + awk '$1 == "LOAD" && $0 ~ / R E/ {print $3; exit}') + if [ -n "$ptw_entry" ] && [ -n "$ptw_load_off" ] && + [ -n "$ptw_load_vaddr" ]; then + ptw_off=$(( $(printf "%d" "$ptw_load_off") + + $(printf "%d" "$ptw_entry") - + $(printf "%d" "$ptw_load_vaddr") )) + fi +fi +if [ "$(uname -m)" = x86_64 ] && + [ -e /sys/devices/intel_pt/format/ptw ] && [ -n "$ptw_off" ]; then +check_good_ptw() { + echo > uprobe_events # Clear any probe left by an earlier case. + echo "$1" > uprobe_events + grep -q 'ptw:uprobes/ptw_parser' uprobe_events + local ret=$? + echo "-:ptw_parser" > uprobe_events + return "$ret" +} + +check_good_ptw "ptw:ptw_parser /bin/sh:$ptw_off%multinop %di" || exit 1 +check_good_ptw "ptw:ptw_parser /bin/sh:$ptw_off%nopace %multinop %di" || exit 1 +check_good_ptw "ptw:ptw_parser /bin/sh:$ptw_off %multinop %nopace %di" || exit 1 + +check_error "ptw:ptw_parser /bin/sh:$ptw_off^%return %di" # BAD_ADDR_SUFFIX +check_error "ptw:ptw_parser /bin/sh:$ptw_off^%unknown %di" # BAD_ADDR_SUFFIX +if grep -q '\$comm' README; then + check_error "ptw:ptw_parser /bin/sh:$ptw_off %multinop %di ^\$comm" # BAD_FETCH_ARG +fi +echo > uprobe_events +fi + exit 0
tools/testing/selftests/uprobes/Makefile new file +14 -0
@@ -0,0 +1,14 @@ +# SPDX-License-Identifier: GPL-2.0 +# ptwrite uprobe selftests (x86-64). +ARCH ?= $(shell uname -m 2>/dev/null || echo not) +CFLAGS += -O2 -Wall -no-pie + +TEST_PROGS := run_ptw.sh + +ifneq ($(filter x86 x86_64,$(ARCH)),) +TEST_GEN_FILES := ptw_probe +else +TEST_GEN_FILES := +endif + +include ../lib.mk
tools/testing/selftests/uprobes/ptw_probe.c new file +156 -0
156 lines not on this page · raw message
tools/testing/selftests/uprobes/run_ptw.sh new file +219 -0
219 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [RFC PATCH v2 11/11] ptwrite uprobes: Add kernel self tests
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Medium] kselftests/uprobes: test unconditionally skips due to undefined FLT_V variable - [Medium]…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Medium] kselftests/uprobes: test unconditionally skips due to undefined FLT_V variable
- [Medium] kselftests/uprobes: unaligned_nopfn site does not cross 8-byte boundary, invalidating test
- [Low] kselftests/uprobes: 64-bit inline assembly causes build failure on 32-bit x86 --
commit af4e3ff18548d1ab18ec7d6c2b846c7b5c15b34e
Author: Andi Kleen <[email protected]>
Subject: ptwrite uprobes: Add kernel self tests
This commit adds selftests for PTWRITE uprobes to exercise instruction punning, multinop patching, and probe lifecycle on x86 architectures.
Quoted 6 lines
tools/testing/selftests/uprobes/Makefile new file +0
-0@@ -0,0 +1,14 @@
[ ... ]
tools/testing/selftests/uprobes/Makefile line 10
Quoted 5 lines
tools/testing/selftests/uprobes/Makefile new file +5
-0+TEST_PROGS := run_ptw.sh + +ifneq ($(filter x86 x86_64,$(ARCH)),) +TEST_GEN_FILES := ptw_probe +else
[Severity: Low]
Will this fail to build on 32-bit x86 architectures? The Makefile enables test compilation for the x86 architecture filter, which includes 32-bit builds. However, ptw_probe.c uses strict 64-bit inline assembly like movabs, %rax, and %rsp. When compiled with a 32-bit toolchain, won't the assembler reject these instructions?
Quoted 6 lines
tools/testing/selftests/uprobes/ptw_probe.c new file +0
-0@@ -0,0 +1,156 @@
[ ... ]
tools/testing/selftests/uprobes/ptw_probe.c line 51
Quoted 10 lines
tools/testing/selftests/uprobes/ptw_probe.c new file +10
-0+static __attribute__((noipa))uint64_t +unaligned_nopfn (uint64_t a) +{ + asmvolatile (".p2align 3, 0x90\n\t" +"nop\n\t" +".globl nopfn_unaligned_site\n\t" +"nopfn_unaligned_site:\n\t" +"nop\n\tnop\n\tnop\n\tnop\n\tnop" :::"memory" ); +return a *13 +5 ; +}
[Severity: Medium]
Does this actually create an unaligned sequence that crosses an 8-byte boundary?
The assembly code aligns to 8 bytes with .p2align 3 and adds a 1-byte nop, placing the start of the 5-byte target sequence at offset 1. Since offsets 1 through 5 fit perfectly within a single 8-byte word, the kernel's atomic patch path can handle it safely.
Won't the kernel accept this probe instead of rejecting it, causing test 11 in run_ptw.sh to incorrectly report a failure when it expects the kernel to reject the probe?
Quoted 6 lines
tools/testing/selftests/uprobes/run_ptw.sh new file +0
-0@@ -0,0 +1,219 @@
[ ... ]
Quoted 5 lines
tools/testing/selftests/uprobes/run_ptw.sh new file +5
-0+PUN_V=$(objdump -d "$BIN" | awk '/^[0-9a-f]+ <punfn>:/{print $1;exit}' | tr -d ':') +JCC_V=$(objdump -d "$BIN" | + awk '/^[0-9a-f]+ <jcc8>:/ {f=1; next} f&&/jne/{print $1; exit}' | + tr -d ':') +NOP_V=$(objdump -d "$BIN" | awk '/^[0-9a-f]+ <nopfn_site>:/{print $1;exit}' | tr -d ':')
tools/testing/selftests/uprobes/run_ptw.sh line 53
Quoted 10 lines
tools/testing/selftests/uprobes/run_ptw.sh new file +10
-0+NOP5_V=$(objdump -d "$BIN" | awk '/^[0-9a-f]+ <nop5>:/{print $1;exit}' | tr -d ':') +UNOP_V=$(objdump -d "$BIN" | + awk '/^[0-9a-f]+ <nopfn_unaligned_site>:/{print $1;exit}' | tr -d ':') +RZ_V=$(objdump -d "$BIN" | awk '/^[0-9a-f]+ <rz_probe_site>:/{print $1;exit}' | tr -d ':') +if [ -z "$PUN_V" ] || [ -z "$JCC_V" ] || [ -z "$FLT_V" ] || + [ -z "$NOP_V" ] || [ -z "$NOP5_V" ] || [ -z "$UNOP_V" ] || + [ -z "$RZ_V" ]; then + echo "1..0 # SKIP unable to resolve ptw_probe symbols" + exit 0 +fi
[Severity: Medium]
Is the FLT_V variable supposed to be defined or populated before this check?
The script tests for the existence of an undefined variable FLT_V, which causes this condition to always evaluate to true. Doesn't this mean the entire ptwrite uprobe selftest unconditionally skips execution and reports 'unable to resolve ptw_probe symbols' on every run, resulting in no test coverage?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11