This is an automated email from the ASF dual-hosted git repository.

GUIDINGLI pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git


The following commit(s) were added to refs/heads/master by this push:
     new 3d7754f7644 arch/risc-v: Read the thread pointer of a fork() child 
before the copy.
3d7754f7644 is described below

commit 3d7754f7644aa20ddc7558eba5892c9134a48e09
Author: Marco Casaroli <[email protected]>
AuthorDate: Wed Nov 25 10:01:19 2026 +0100

    arch/risc-v: Read the thread pointer of a fork() child before the copy.
    
    riscv_fork() of a build with system calls read the thread pointer of the
    child (REG_TP of its initial context) after it copied the stack of the
    parent to the child.  Without a kernel stack (ARCH_KERNEL_STACK=n, for
    example a protected build), up_initial_state() puts the initial context
    at the top of the stack of the child, and the copy of the stack
    overwrites it.  So a vfork() child, and a fork() child with its own
    stack, got a word of the stack of the parent as its thread pointer.
    
    Read the thread pointer before the copy of the stack.
    
    Assisted-by: Claude Code:claude-opus-5-5
    Signed-off-by: Marco Casaroli <[email protected]>
---
 arch/risc-v/src/common/riscv_fork.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/arch/risc-v/src/common/riscv_fork.c 
b/arch/risc-v/src/common/riscv_fork.c
index e1a09d5cb27..71cc190ace0 100644
--- a/arch/risc-v/src/common/riscv_fork.c
+++ b/arch/risc-v/src/common/riscv_fork.c
@@ -121,6 +121,15 @@ pid_t riscv_fork(bool vfork, const struct fork_s *context)
       return (pid_t)ERROR;
     }
 
+#ifdef CONFIG_SCHED_THREAD_LOCAL
+  /* Save child's thread pointer.  Read it before the copy of the stack:
+   * without a kernel stack the initial context is at the top of the stack
+   * of the child, and the copy overwrites it.
+   */
+
+  tp = child->xcp.regs[REG_TP];
+#endif
+
   if (child->stack_base_ptr == parent->stack_base_ptr)
     {
       /* A fork() child inherits the parent's stack address:  its copy of the
@@ -149,12 +158,6 @@ pid_t riscv_fork(bool vfork, const struct fork_s *context)
              stackutil);
     }
 
-#ifdef CONFIG_SCHED_THREAD_LOCAL
-  /* Save child's thread pointer */
-
-  tp = child->xcp.regs[REG_TP];
-#endif
-
   /* Determine the integer context save area */
 
 #ifdef CONFIG_ARCH_KERNEL_STACK

Reply via email to