[libc-commits] [libc] [libc] Add tmpnam implementation (PR #204901)

via libc-commits libc-commits at lists.llvm.org
Wed Aug 26 22:12:35 PDT 2026


https://github.com/shubhe25p updated https://github.com/llvm/llvm-project/pull/204901

>From ec08aa32d015757c27c42b45f48c72a762164cd5 Mon Sep 17 00:00:00 2001
From: shubhe25p <33875085+shubhe25p at users.noreply.github.com>
Date: Wed, 26 Aug 2026 22:11:27 -0700
Subject: [PATCH] [libc] Add tmpnam implementation

Implements tmpnam per the POSIX specification and adds
unit tests.
---
 libc/config/linux/aarch64/entrypoints.txt    |   1 +
 libc/config/linux/riscv/entrypoints.txt      |   1 +
 libc/config/linux/x86_64/entrypoints.txt     |   1 +
 libc/include/llvm-libc-macros/stdio-macros.h |  20 +++
 libc/include/stdio.yaml                      |  12 ++
 libc/src/stdio/CMakeLists.txt                |   7 +
 libc/src/stdio/linux/CMakeLists.txt          |  18 +++
 libc/src/stdio/linux/tmpnam.cpp              | 103 ++++++++++++++
 libc/src/stdio/tmpnam.h                      |  28 ++++
 libc/test/src/stdio/CMakeLists.txt           |  12 ++
 libc/test/src/stdio/tmpnam_test.cpp          | 142 +++++++++++++++++++
 11 files changed, 345 insertions(+)
 create mode 100644 libc/src/stdio/linux/tmpnam.cpp
 create mode 100644 libc/src/stdio/tmpnam.h
 create mode 100644 libc/test/src/stdio/tmpnam_test.cpp

diff --git a/libc/config/linux/aarch64/entrypoints.txt b/libc/config/linux/aarch64/entrypoints.txt
index 68ce4dd591806..fc8d2843676ed 100644
--- a/libc/config/linux/aarch64/entrypoints.txt
+++ b/libc/config/linux/aarch64/entrypoints.txt
@@ -1244,6 +1244,7 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.stdio.stdin
     libc.src.stdio.stdout
     libc.src.stdio.ungetc
+    libc.src.stdio.tmpnam
 
     # stdlib.h entrypoints
     libc.src.stdlib._Exit
diff --git a/libc/config/linux/riscv/entrypoints.txt b/libc/config/linux/riscv/entrypoints.txt
index 40fef13470322..7ec2e27ac90d6 100644
--- a/libc/config/linux/riscv/entrypoints.txt
+++ b/libc/config/linux/riscv/entrypoints.txt
@@ -1431,6 +1431,7 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.stdio.stdin
     libc.src.stdio.stdout
     libc.src.stdio.ungetc
+    libc.src.stdio.tmpnam
 
     # stdlib.h entrypoints
     libc.src.stdlib._Exit
diff --git a/libc/config/linux/x86_64/entrypoints.txt b/libc/config/linux/x86_64/entrypoints.txt
index 99020a03ff3f7..74ffe219966eb 100644
--- a/libc/config/linux/x86_64/entrypoints.txt
+++ b/libc/config/linux/x86_64/entrypoints.txt
@@ -1444,6 +1444,7 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.stdio.stdin
     libc.src.stdio.stdout
     libc.src.stdio.ungetc
+    libc.src.stdio.tmpnam
 
     # stdlib.h entrypoints
     libc.src.stdlib._Exit
diff --git a/libc/include/llvm-libc-macros/stdio-macros.h b/libc/include/llvm-libc-macros/stdio-macros.h
index 96f0e6933ade6..aefbbcf80a9bb 100644
--- a/libc/include/llvm-libc-macros/stdio-macros.h
+++ b/libc/include/llvm-libc-macros/stdio-macros.h
@@ -54,5 +54,25 @@ extern FILE *stderr;
 #ifndef SEEK_END
 #define SEEK_END 2
 #endif
+/*
+ * L_tmpnam = 20 ("/tmp/" + 14 random chars + '\0').
+ * Suffix length 14 (base-64) ensures a < 10^-12 collision
+ * probability for up to 10^6 calls (via birthday bound).
+ */
+#ifndef L_tmpnam
+#define L_tmpnam 20
+#endif
+/*
+ * TMP_MAX = 1,000,000 (10^6 calls per process).
+ * Generous decimal call ceiling for the L_tmpnam guarantee;
+ * provides a 6x safety margin below the 6.2M limit (P ~= 2.6 x 10^-14).
+ */
+#ifndef TMP_MAX
+#define TMP_MAX 1000000
+#endif
+
+#ifndef P_tmpdir
+#define P_tmpdir "/tmp"
+#endif
 
 #endif // LLVM_LIBC_MACROS_STDIO_MACROS_H
diff --git a/libc/include/stdio.yaml b/libc/include/stdio.yaml
index ef725dd4fe619..54498586c6c2b 100644
--- a/libc/include/stdio.yaml
+++ b/libc/include/stdio.yaml
@@ -26,6 +26,12 @@ macros:
     macro_header: stdio-macros.h
   - macro_name: _IOFBF
     macro_header: stdio-macros.h
+  - macro_name: L_tmpnam
+    macro_header: stdio-macros.h
+  - macro_name: TMP_MAX
+    macro_header: stdio-macros.h
+  - macro_name: P_tmpdir
+    macro_header: stdio-macros.h
 types:
   - type_name: rsize_t
   - type_name: size_t
@@ -410,6 +416,12 @@ functions:
     return_type: FILE *
     arguments:
       - type: void
+  - name: tmpnam
+    standards:
+      - stdc
+    return_type: char *
+    arguments:
+      - type: char *
   - name: ungetc
     standards:
       - stdc
diff --git a/libc/src/stdio/CMakeLists.txt b/libc/src/stdio/CMakeLists.txt
index 3ef6e4f7b7d01..45488b1d4e244 100644
--- a/libc/src/stdio/CMakeLists.txt
+++ b/libc/src/stdio/CMakeLists.txt
@@ -242,6 +242,13 @@ add_entrypoint_object(
     .${LIBC_TARGET_OS}.remove
 )
 
+add_entrypoint_object(
+  tmpnam
+  ALIAS
+  DEPENDS
+    .${LIBC_TARGET_OS}.tmpnam
+)
+
 add_entrypoint_object(
   rename
   ALIAS
diff --git a/libc/src/stdio/linux/CMakeLists.txt b/libc/src/stdio/linux/CMakeLists.txt
index 6631f2ca4814a..8a58dd737ea5d 100644
--- a/libc/src/stdio/linux/CMakeLists.txt
+++ b/libc/src/stdio/linux/CMakeLists.txt
@@ -82,3 +82,21 @@ add_entrypoint_object(
     libc.src.__support.macros.config
     libc.src.__support.OSUtil.linux.syscall_wrappers.open
 )
+
+add_entrypoint_object(
+  tmpnam
+  SRCS
+    tmpnam.cpp
+  HDRS
+    ../tmpnam.h
+  DEPENDS
+    libc.hdr.stdio_macros
+    libc.hdr.errno_macros
+    libc.src.__support.CPP.string_view
+    libc.src.string.memory_utils.inline_memcpy
+    libc.src.__support.CPP.atomic
+    libc.hdr.unistd_macros
+    libc.src.__support.OSUtil.osutil
+    libc.src.__support.OSUtil.linux.syscall_wrappers.access
+    libc.src.__support.OSUtil.linux.syscall_wrappers.getrandom
+)
diff --git a/libc/src/stdio/linux/tmpnam.cpp b/libc/src/stdio/linux/tmpnam.cpp
new file mode 100644
index 0000000000000..0d18efd3e0bd5
--- /dev/null
+++ b/libc/src/stdio/linux/tmpnam.cpp
@@ -0,0 +1,103 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Declaration of tmpnam, a POSIX function that generate a string that is a
+/// valid pathname that does not name an existing file.
+/// See:
+/// https://pubs.opengroup.org/onlinepubs/9799919799/functions/tmpnam.html
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/stdio/tmpnam.h"
+#include "hdr/errno_macros.h"
+#include "hdr/stdio_macros.h"
+#include "hdr/unistd_macros.h"
+#include "src/__support/CPP/atomic.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/access.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/getrandom.h"
+#include "src/__support/macros/config.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+static char tmpbuf[L_tmpnam];
+static cpp::Atomic<size_t> tmpnam_budget = TMP_MAX;
+
+// Thread-safety guarantees per ISO C & POSIX:
+// - When 's' is nullptr, callers share internal static storage ('tmpbuf'),
+// which is not thread-safe per standard specification allowance.
+// - Process-wide call budget ('tmpnam_budget') is tracked atomically using a
+// lock-free compare-and-swap loop.
+LLVM_LIBC_FUNCTION(char *, tmpnam, (char *s)) {
+  if (s == nullptr)
+    s = tmpbuf;
+
+  // Subset of the POSIX portable filename character set.
+  // Deliberately sized to 64 (a power of 2, rather than the full set)
+  // to prevent slight modulo bias also helps in performance.
+  const char CHARSET[] = "0123456789"
+                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                         "abcdefghijklmnopqrstuvwxyz"
+                         "_.";
+  constexpr size_t CHARSET_SIZE = sizeof(CHARSET) - 1; // 64 (excluding '\0')
+  static_assert((CHARSET_SIZE & (CHARSET_SIZE - 1)) == 0,
+                "CHARSET_SIZE must be a power of 2");
+
+  constexpr size_t MASK = CHARSET_SIZE - 1;
+
+  // We want to construct: P_tmpdir / <14 random chars> \0
+  // P_tmpdir is "/tmp" (length 4).
+  // Total length must be L_tmpnam (20).
+  // /tmp/ is 5 chars.
+  // Random suffix is 14 chars.
+  // Null terminator is 1 char.
+  // Total: 5 + 14 + 1 = 20.
+  constexpr cpp::string_view PREFIX = P_tmpdir "/";
+  static_assert(PREFIX.size() + 14 + 1 == L_tmpnam, "L_tmpnam mismatch");
+  inline_memcpy(s, PREFIX.data(), PREFIX.size());
+  constexpr size_t PREFIX_SIZE = PREFIX.size();
+  constexpr size_t SUFFIX_SIZE = 14;
+
+  bool is_unique = false;
+  while (!is_unique) {
+    size_t curr_budget = tmpnam_budget.load(cpp::MemoryOrder::RELAXED);
+
+    do {
+      if (curr_budget == 0)
+        break;
+    } while (
+        !tmpnam_budget.compare_exchange_strong(curr_budget, curr_budget - 1));
+
+    if (curr_budget == 0)
+      break;
+
+    uint8_t rand_bytes[L_tmpnam];
+    auto ret = linux_syscalls::getrandom(rand_bytes, SUFFIX_SIZE, 0);
+    if (!ret.has_value() || ret.value() != SUFFIX_SIZE) {
+      /* return nullptr when getrandom fails but consume tmpnam budget */
+      return nullptr;
+    }
+
+    char *suffix = s + PREFIX_SIZE;
+    for (size_t i = 0; i < SUFFIX_SIZE; i++) {
+      suffix[i] = CHARSET[rand_bytes[i] & MASK];
+    }
+
+    s[L_tmpnam - 1] = '\0';
+    auto res = linux_syscalls::access(s, F_OK);
+    is_unique = (!res.has_value() && res.error() == ENOENT);
+  }
+
+  if (is_unique)
+    return s;
+  /* implementation-defined: if we exhaust budget we return nullptr */
+  return nullptr;
+}
+} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/stdio/tmpnam.h b/libc/src/stdio/tmpnam.h
new file mode 100644
index 0000000000000..38d40d17a8a55
--- /dev/null
+++ b/libc/src/stdio/tmpnam.h
@@ -0,0 +1,28 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Declaration of tmpnam, a POSIX function that generate a string that is a
+/// valid pathname that does not name an existing file.
+/// See:
+/// https://pubs.opengroup.org/onlinepubs/9799919799/functions/tmpnam.html
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STDIO_TMPNAM_H
+#define LLVM_LIBC_SRC_STDIO_TMPNAM_H
+
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+char *tmpnam(char *s);
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_STDIO_TMPNAM_H
diff --git a/libc/test/src/stdio/CMakeLists.txt b/libc/test/src/stdio/CMakeLists.txt
index b25219ef3ca03..7a7181a957c03 100644
--- a/libc/test/src/stdio/CMakeLists.txt
+++ b/libc/test/src/stdio/CMakeLists.txt
@@ -635,6 +635,18 @@ add_libc_test(
     libc.src.stdio.fwrite
 )
 
+add_libc_test(
+  tmpnam_test
+  SUITE
+    libc_stdio_unittests
+  SRCS
+    tmpnam_test.cpp
+  DEPENDS
+    libc.src.stdio.tmpnam
+    libc.src.__support.CPP.string_view
+    libc.hdr.stdio_macros
+)
+
 # Create an output directory for any temporary test files.
 file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/testdata)
 
diff --git a/libc/test/src/stdio/tmpnam_test.cpp b/libc/test/src/stdio/tmpnam_test.cpp
new file mode 100644
index 0000000000000..f15b16309a727
--- /dev/null
+++ b/libc/test/src/stdio/tmpnam_test.cpp
@@ -0,0 +1,142 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Tests for tmpnam
+/// See: https://pubs.opengroup.org/onlinepubs/9799919799/functions/tmpnam.html
+///
+//===----------------------------------------------------------------------===//
+#include "src/stdio/tmpnam.h"
+
+#include "hdr/stdio_macros.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/macros/config.h"
+#include "test/UnitTest/Test.h"
+
+#include "hdr/types/size_t.h"
+namespace {
+
+using LIBC_NAMESPACE::cpp::string_view;
+
+// The portable filename character set the implementation draws from, plus the
+// '/' that appears in the P_tmpdir prefix. Any byte in a returned name must be
+// one of these.
+constexpr char Allowed[] = "0123456789"
+                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                           "abcdefghijklmnopqrstuvwxyz"
+                           "_./";
+
+bool only_allowed_chars(string_view sv) {
+  for (char c : sv) {
+    if (!string_view(Allowed).contains(c))
+      return false;
+  }
+  return true;
+}
+
+} // namespace
+
+// Caller-supplied buffer: the spec requires the return value to be exactly the
+// argument pointer, the string to be null-terminated within L_tmpnam bytes,
+// and the result to begin with the temp-dir prefix.
+TEST(LlvmLibcTmpnamTest, NonNullBufferReturnsSamePointer) {
+  char buf[L_tmpnam];
+  char *result = LIBC_NAMESPACE::tmpnam(buf);
+  ASSERT_EQ(result, buf);
+}
+
+TEST(LlvmLibcTmpnamTest, NonNullBufferIsNullTerminated) {
+  char buf[L_tmpnam];
+  char *result = LIBC_NAMESPACE::tmpnam(buf);
+  ASSERT_NE(result, static_cast<char *>(nullptr));
+  // A NULL must appear within the buffer bounds.
+  bool terminated = false;
+  for (size_t i = 0; i < L_tmpnam; ++i) {
+    if (result[i] == '\0') {
+      terminated = true;
+      break;
+    }
+  }
+  ASSERT_TRUE(terminated);
+}
+
+TEST(LlvmLibcTmpnamTest, ResultHasTempDirPrefix) {
+  char buf[L_tmpnam];
+  char *result = LIBC_NAMESPACE::tmpnam(buf);
+  ASSERT_NE(result, static_cast<char *>(nullptr));
+  string_view sv(result);
+  string_view prefix(P_tmpdir);
+  // P_tmpdir may not carry a trailing slash; the implementation always
+  // emits one separator, so check the directory portion is present at the head.
+  ASSERT_TRUE(sv.starts_with(prefix));
+}
+
+TEST(LlvmLibcTmpnamTest, ResultUsesOnlyPortableChars) {
+  char buf[L_tmpnam];
+  char *result = LIBC_NAMESPACE::tmpnam(buf);
+  ASSERT_NE(result, static_cast<char *>(nullptr));
+  ASSERT_TRUE(only_allowed_chars(string_view(result)));
+}
+
+// Null argument: the result lives in an internal static object; the returned
+// pointer must be non-null and carry the same structural guarantees.
+TEST(LlvmLibcTmpnamTest, NullBufferReturnsInternalObject) {
+  char *result = LIBC_NAMESPACE::tmpnam(nullptr);
+  ASSERT_NE(result, static_cast<char *>(nullptr));
+  string_view sv(result);
+  ASSERT_TRUE(sv.starts_with(string_view(P_tmpdir)));
+  ASSERT_TRUE(only_allowed_chars(sv));
+}
+
+// Check that the generated path length is within bounds: strictly less than
+// L_tmpnam and strictly greater than the temporary directory prefix.
+TEST(LlvmLibcTmpnamTest, ResultLengthWithinBound) {
+  char buf[L_tmpnam];
+  char *result = LIBC_NAMESPACE::tmpnam(buf);
+  ASSERT_NE(result, static_cast<char *>(nullptr));
+  string_view sv(result);
+  ASSERT_LT(sv.size(), static_cast<size_t>(L_tmpnam));
+  // Must be strictly longer than the prefix: a prefix with no random suffix
+  // would mean the generator produced an empty suffix.
+  ASSERT_GT(sv.size(), string_view(P_tmpdir).size());
+}
+
+// Successive calls should produce distinct strings.
+TEST(LlvmLibcTmpnamTest, SuccessiveCallsDiffer) {
+  char a[L_tmpnam];
+  char b[L_tmpnam];
+  char *ra = LIBC_NAMESPACE::tmpnam(a);
+  char *rb = LIBC_NAMESPACE::tmpnam(b);
+  ASSERT_NE(ra, static_cast<char *>(nullptr));
+  ASSERT_NE(rb, static_cast<char *>(nullptr));
+  ASSERT_FALSE(string_view(ra) == string_view(rb));
+}
+
+// Two calls with a null argument must return the SAME pointer (the address of
+// the single internal static object) The contents, however, are overwritten by
+// the second call.
+TEST(LlvmLibcTmpnamTest, NullCallsShareObjectButDifferInContent) {
+  char *first = LIBC_NAMESPACE::tmpnam(nullptr);
+  ASSERT_NE(first, static_cast<char *>(nullptr));
+
+  // Snapshot the first result before it is overwritten.
+  char snapshot[L_tmpnam];
+  size_t i = 0;
+  for (; i < L_tmpnam && first[i] != '\0'; ++i)
+    snapshot[i] = first[i];
+  snapshot[i < L_tmpnam ? i : L_tmpnam - 1] = '\0';
+
+  char *second = LIBC_NAMESPACE::tmpnam(nullptr);
+  ASSERT_NE(second, static_cast<char *>(nullptr));
+
+  // Same backing object: identical address.
+  ASSERT_EQ(first, second);
+
+  // But the generated string changed
+  ASSERT_FALSE(string_view(snapshot) == string_view(second));
+}



More information about the libc-commits mailing list