[libc-commits] [libc] [libc] Implement clone(2) and use it in thread spawning (PR #224257)
Pavel Labath via libc-commits
libc-commits at lists.llvm.org
Fri Sep 18 01:14:34 PDT 2026
================
@@ -0,0 +1,57 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Implementation of x86_64 clone.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_OSUTIL_LINUX_SYSCALL_WRAPPERS_X86_64_CLONE_H
+#define LLVM_LIBC_SRC___SUPPORT_OSUTIL_LINUX_SYSCALL_WRAPPERS_X86_64_CLONE_H
+
+#include "hdr/types/pid_t.h"
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+#include <sys/syscall.h> // For SYS_clone, SYS_exit
+
+namespace LIBC_NAMESPACE_DECL {
+namespace linux_syscalls {
+namespace detail {
+
+constexpr uintptr_t STACK_ADJUSTMENT = 16;
+
+LIBC_INLINE long clone_impl(int flags, void *child_stack, pid_t *parent_tid,
+ void *tls, pid_t *child_tid) {
+ long ret;
+ register pid_t *r10 __asm__("r10") = child_tid;
+ register void *r8 __asm__("r8") = tls;
+
+ LIBC_INLINE_ASM("syscall\n\t"
+ "testq %%rax, %%rax\n\t"
+ "jnz 1f\n\t"
+ // Child execution:
+ // Zero frame pointer to terminate call stack unwinding.
+ "xorl %%ebp, %%ebp\n\t"
+ "popq %%rax\n\t"
+ "popq %%rdi\n\t"
+ "call *%%rax\n\t"
+ "movl %%eax, %%edi\n\t"
+ "movl %[sys_exit], %%eax\n\t"
+ "syscall\n\t"
+ "hlt\n\t"
----------------
labath wrote:
Why is that better? `hlt` is nice because it stands for "halt", but `ud2` matches both __builtin_trap() and asm for other architectures (where I've put their versions of permanently unimplemented opcodes). And the intent can be clarified with a comment.
https://github.com/llvm/llvm-project/pull/224257
More information about the libc-commits
mailing list