[libc-commits] [libc] [libc] Add tmpnam implementation (PR #204901)
Shubh Pachchigar via libc-commits
libc-commits at lists.llvm.org
Sun Jul 12 18:26:57 PDT 2026
https://github.com/shubhe25p updated https://github.com/llvm/llvm-project/pull/204901
>From 20b42998316da62fdd53168494d899ccd51dc9d9 Mon Sep 17 00:00:00 2001
From: shubhe25p <33875085+shubhe25p at users.noreply.github.com>
Date: Tue, 7 Jul 2026 23:57:04 -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 | 87 +++++++++++
libc/include/stdio.yaml | 6 +
libc/src/stdio/CMakeLists.txt | 7 +
libc/src/stdio/linux/CMakeLists.txt | 16 +++
libc/src/stdio/linux/tmpnam.cpp | 96 +++++++++++++
libc/src/stdio/tmpnam.h | 28 ++++
libc/test/src/stdio/CMakeLists.txt | 12 ++
libc/test/src/stdio/tmpnam_test.cpp | 143 +++++++++++++++++++
11 files changed, 398 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 97625b28a2555..4773c95ce5a22 100644
--- a/libc/config/linux/aarch64/entrypoints.txt
+++ b/libc/config/linux/aarch64/entrypoints.txt
@@ -1193,6 +1193,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 90a93715b5d1e..ea58cd16fcc03 100644
--- a/libc/config/linux/riscv/entrypoints.txt
+++ b/libc/config/linux/riscv/entrypoints.txt
@@ -1322,6 +1322,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 bac62464a6c45..4f1ffaf5395d8 100644
--- a/libc/config/linux/x86_64/entrypoints.txt
+++ b/libc/config/linux/x86_64/entrypoints.txt
@@ -1388,6 +1388,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..b1d9b92694484 100644
--- a/libc/include/llvm-libc-macros/stdio-macros.h
+++ b/libc/include/llvm-libc-macros/stdio-macros.h
@@ -54,5 +54,92 @@ extern FILE *stderr;
#ifndef SEEK_END
#define SEEK_END 2
#endif
+/*
+ * Derivation of L_tmpnam
+ * ------------------------------------------------------------
+ *
+ * Generated pathnames have the form: /tmp/XXXXXXXXXXXXXX
+ * - "/tmp/" is a 5-byte prefix.
+ * - N random characters follow, drawn independently and uniformly from
+ * a 65-character alphabet (the POSIX portable filename character set)
+ * - 1 byte for the NULL terminator.
+ * So: L_tmpnam = 5 + N + 1.
+ *
+ * Choosing N: we want the probability of two independently generated
+ * suffixes colliding to stay below a target threshold P, even after up to
+ * k calls to tmpnam() over the lifetime of a process.
+ *
+ * Let M = 65^N be the keyspace which is the total number of distinct
+ * N-character suffixes that can be generated (NOT the number actually
+ * generated; M is the size of the space they are drawn from).
+ *
+ * Among k calls, the number of distinct pairs of calls is:
+ * C(k, 2) = k(k-1)/2 ~= k^2 / 2 (approximation valid for large k)
+ *
+ * Each individual pair collides (picks the identical suffix) with
+ * probability 1/M, since each call draws independently and uniformly from
+ * the M possible suffixes.
+ *
+ * Treating pairwise collisions as approximately independent low-probability
+ * events, the probability that AT LEAST ONE collision occurs among all
+ * pairs is approximately the sum over all pairs of the per-pair probability:
+ *
+ * P ~= (k^2 / 2) * (1 / M) = k^2 / (2M)
+ *
+ * This is the standard birthday-bound approximation.
+ *
+ * Solving for the keyspace required to keep P under a chosen target, given
+ * an assumed call-volume ceiling k:
+ *
+ * M >= k^2 / (2P)
+ *
+ * Design inputs (stated, not borrowed):
+ * k = 10^6 (one million calls: a generous upper bound on how many
+ * times a single long-running process could realistically
+ * call tmpnam() in its lifetime)
+ * P = 10^-12 (one-in-a-trillion target collision probability)
+ *
+ * Required keyspace:
+ * M >= (10^6)^2 / (2 * 10^-12) = 5 x 10^23
+ *
+ * Solving 65^N >= 5x10^23 for N:
+ * N >= log_65(5x10^23) ~= 14 (round up)
+ *
+ * Therefore:
+ * N = 14
+ * L_tmpnam = 5 (prefix) + 14 (suffix) + 1 (NULL) = 20
+ */
+#ifndef L_tmpnam
+#define L_tmpnam 20
+#endif
+/*
+ * TMP_MAX:
+ * ---------
+ * TMP_MAX is a separate policy decision, that states the call-volume ceiling
+ * for which we are willing to stand behind the P = 10^-12 collision-probability
+ * guarantee derived above. Per POSIX, behavior beyond TMP_MAX calls in a single
+ * process is implementation-defined; we simply decline to make any guarantee
+ * past this point, even though the keyspace could technically support more.
+ *
+ * TMP_MAX = 1,000,000
+ *
+ * This is chosen as a round, easily-reasoned-about figure equal to the k
+ * used in the derivation above.
+ *
+ * Note on glibc's TMP_MAX = 238328: this value has no documented derivation.
+ * A glibc/gnulib contributor publicly stated in 2001 that the figure's
+ * origin is unknown and "as good as any other number larger than a couple
+ * of thousand" (bug-textutils mailing list, Oct 26 2001:
+ * https://lists.gnu.org/archive/html/bug-textutils/2001-10/msg00032.html).
+ * We do not inherit this value; the derivation above is independent and
+ * stated in full above.
+ */
+#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 4b12698e2484d..aaa1fec8eac61 100644
--- a/libc/include/stdio.yaml
+++ b/libc/include/stdio.yaml
@@ -396,6 +396,12 @@ functions:
- type: const char *__restrict
- type: const char *__restrict
- type: '...'
+ - 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 feee8d60d1c60..b1109b4409a32 100644
--- a/libc/src/stdio/CMakeLists.txt
+++ b/libc/src/stdio/CMakeLists.txt
@@ -243,6 +243,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 1552060c52550..f7d90470d99c9 100644
--- a/libc/src/stdio/linux/CMakeLists.txt
+++ b/libc/src/stdio/linux/CMakeLists.txt
@@ -66,3 +66,19 @@ add_entrypoint_object(
libc.hdr.types.FILE
libc.src.__support.File.platform_file
)
+
+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
+)
diff --git a/libc/src/stdio/linux/tmpnam.cpp b/libc/src/stdio/linux/tmpnam.cpp
new file mode 100644
index 0000000000000..d70cf7b52c262
--- /dev/null
+++ b/libc/src/stdio/linux/tmpnam.cpp
@@ -0,0 +1,96 @@
+//===----------------------------------------------------------------------===//
+//
+// 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;
+
+// Partially thread-safe:
+// - When null is handed it is not thread-safe.
+// - We do some work to ensure that cases where we need to use tmpnam_budget
+// that we lock around it.
+LLVM_LIBC_FUNCTION(char *, tmpnam, (char *s)) {
+ if (s == nullptr)
+ s = tmpbuf;
+
+ // here if the s is null then use tmpbuf and if sizeof
+ // POSIX portable filename character set, sorted by ASCII value.
+ // See
+ // https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap03.html#tag_03_265
+ const char charset[] = "-.0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "_"
+ "abcdefghijklmnopqrstuvwxyz";
+
+ // 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()) {
+ /* return nullptr when getrandom fails but consume tmpnam budget */
+ return nullptr;
+ }
+
+ for (size_t i = 0; i < SUFFIX_SIZE; i++) {
+ s[PREFIX_SIZE + i] = charset[rand_bytes[i] % (sizeof(charset) - 1)];
+ }
+ 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 5f586238dc1e9..1eb3535a27a46 100644
--- a/libc/test/src/stdio/CMakeLists.txt
+++ b/libc/test/src/stdio/CMakeLists.txt
@@ -600,6 +600,18 @@ add_libc_test(
libc.src.stdio.setvbuf
)
+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..e96d185889c09
--- /dev/null
+++ b/libc/test/src/stdio/tmpnam_test.cpp
@@ -0,0 +1,143 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 kAllowed[] = "-./"
+ "0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "_"
+ "abcdefghijklmnopqrstuvwxyz";
+
+bool only_allowed_chars(string_view sv) {
+ for (char c : sv) {
+ if (!string_view(kAllowed).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