[libc-commits] [libc] [libc][stdlib] Add setenv (PR #163018)
Jeff Bailey via libc-commits
libc-commits at lists.llvm.org
Fri May 8 05:19:31 PDT 2026
https://github.com/kaladron updated https://github.com/llvm/llvm-project/pull/163018
>From 98493f157620cf08165303d251e21569722bdaae Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Thu, 7 May 2026 17:58:45 +0100
Subject: [PATCH 1/2] [libc][stdlib] Add setenv
Add the POSIX setenv() function, with EnvironmentManager::set()
handling environment array management and ownership tracking.
Registered for x86_64, aarch64, and riscv architectures. Integration
tests cover overwrite/no-overwrite semantics, empty/invalid names,
empty values, and repeated replacement.
Assisted-by: Automated tooling, human reviewed.
---
libc/config/linux/aarch64/entrypoints.txt | 1 +
libc/config/linux/riscv/entrypoints.txt | 1 +
libc/config/linux/x86_64/entrypoints.txt | 1 +
libc/include/stdlib.yaml | 8 +
libc/src/stdlib/CMakeLists.txt | 8 +
libc/src/stdlib/environ_internal.cpp | 50 ++++++
libc/src/stdlib/environ_internal.h | 7 +
libc/src/stdlib/linux/CMakeLists.txt | 15 ++
libc/src/stdlib/linux/setenv.cpp | 48 ++++++
libc/src/stdlib/setenv.h | 25 +++
.../integration/src/stdlib/CMakeLists.txt | 12 ++
.../integration/src/stdlib/setenv_test.cpp | 153 ++++++++++++++++++
12 files changed, 329 insertions(+)
create mode 100644 libc/src/stdlib/linux/setenv.cpp
create mode 100644 libc/src/stdlib/setenv.h
create mode 100644 libc/test/integration/src/stdlib/setenv_test.cpp
diff --git a/libc/config/linux/aarch64/entrypoints.txt b/libc/config/linux/aarch64/entrypoints.txt
index ea3f4cd8f51a0..0d9fa0b132d44 100644
--- a/libc/config/linux/aarch64/entrypoints.txt
+++ b/libc/config/linux/aarch64/entrypoints.txt
@@ -1148,6 +1148,7 @@ if(LLVM_LIBC_FULL_BUILD)
libc.src.stdlib.atexit
libc.src.stdlib.exit
libc.src.stdlib.getenv
+ libc.src.stdlib.setenv
libc.src.stdlib.quick_exit
# signal.h entrypoints
diff --git a/libc/config/linux/riscv/entrypoints.txt b/libc/config/linux/riscv/entrypoints.txt
index d8d520c6d4236..4363ead81c3c2 100644
--- a/libc/config/linux/riscv/entrypoints.txt
+++ b/libc/config/linux/riscv/entrypoints.txt
@@ -1277,6 +1277,7 @@ if(LLVM_LIBC_FULL_BUILD)
libc.src.stdlib.atexit
libc.src.stdlib.exit
libc.src.stdlib.getenv
+ libc.src.stdlib.setenv
libc.src.stdlib.quick_exit
# signal.h entrypoints
diff --git a/libc/config/linux/x86_64/entrypoints.txt b/libc/config/linux/x86_64/entrypoints.txt
index dfd6064951d52..a32ac2b36e142 100644
--- a/libc/config/linux/x86_64/entrypoints.txt
+++ b/libc/config/linux/x86_64/entrypoints.txt
@@ -1341,6 +1341,7 @@ if(LLVM_LIBC_FULL_BUILD)
libc.src.stdlib.atexit
libc.src.stdlib.exit
libc.src.stdlib.getenv
+ libc.src.stdlib.setenv
libc.src.stdlib.mbstowcs
libc.src.stdlib.mbtowc
libc.src.stdlib.quick_exit
diff --git a/libc/include/stdlib.yaml b/libc/include/stdlib.yaml
index a751f8306be24..4c958cd9d28ad 100644
--- a/libc/include/stdlib.yaml
+++ b/libc/include/stdlib.yaml
@@ -209,6 +209,14 @@ functions:
return_type: void
arguments:
- type: unsigned int
+ - name: setenv
+ standards:
+ - posix
+ return_type: int
+ arguments:
+ - type: const char *
+ - type: const char *
+ - type: int
- name: strfromd
standards:
- stdc
diff --git a/libc/src/stdlib/CMakeLists.txt b/libc/src/stdlib/CMakeLists.txt
index 1185f1a0fa461..4cce7021d0586 100644
--- a/libc/src/stdlib/CMakeLists.txt
+++ b/libc/src/stdlib/CMakeLists.txt
@@ -81,6 +81,7 @@ add_object_library(
libc.src.__support.CPP.string_view
libc.src.__support.macros.attributes
libc.src.__support.macros.config
+ libc.src.string.memory_utils.inline_memcpy
)
add_entrypoint_object(
@@ -625,6 +626,13 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${LIBC_TARGET_OS})
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${LIBC_TARGET_OS})
endif()
+add_entrypoint_object(
+ setenv
+ ALIAS
+ DEPENDS
+ .${LIBC_TARGET_OS}.setenv
+)
+
if(LIBC_TARGET_OS_IS_BAREMETAL OR LIBC_TARGET_OS_IS_GPU)
add_entrypoint_object(
malloc
diff --git a/libc/src/stdlib/environ_internal.cpp b/libc/src/stdlib/environ_internal.cpp
index a6b630921f9f1..e9da17d028575 100644
--- a/libc/src/stdlib/environ_internal.cpp
+++ b/libc/src/stdlib/environ_internal.cpp
@@ -17,6 +17,7 @@
#include "src/__support/CPP/string_view.h"
#include "src/__support/alloc-checker.h"
#include "src/__support/macros/config.h"
+#include "src/string/memory_utils/inline_memcpy.h"
namespace LIBC_NAMESPACE_DECL {
namespace internal {
@@ -171,5 +172,54 @@ bool EnvironmentManager::ensure_capacity(size_t needed) {
return true;
}
+int EnvironmentManager::set(cpp::string_view name, cpp::string_view value,
+ bool overwrite) {
+ cpp::optional<size_t> idx = find_var(name);
+
+ // If the variable exists and we're not overwriting, do nothing.
+ if (idx && !overwrite)
+ return 0;
+
+ // Ensure we have capacity. If the variable doesn't exist, we need one
+ // more slot.
+ size_t needed = idx ? count : count + 1;
+ if (!ensure_capacity(needed))
+ return -1;
+
+ // Build the "name=value" string.
+ size_t name_len = name.size();
+ size_t value_len = value.size();
+ size_t total_len = name_len + 1 + value_len + 1; // name + '=' + value + '\0'
+
+ AllocChecker ac;
+ char *new_string = new (ac) char[total_len];
+ if (!ac)
+ return -1;
+
+ inline_memcpy(new_string, name.data(), name_len);
+ new_string[name_len] = '=';
+ inline_memcpy(new_string + name_len + 1, value.data(), value_len);
+ new_string[name_len + 1 + value_len] = '\0';
+
+ char **env_array = get_array();
+
+ if (idx) {
+ // Replace existing variable. Free old string if we own it.
+ if (ownership[*idx].can_free())
+ delete[] env_array[*idx];
+
+ env_array[*idx] = new_string;
+ ownership[*idx].allocated_by_us = true;
+ } else {
+ // Add new variable at the end.
+ env_array[count] = new_string;
+ ownership[count].allocated_by_us = true;
+ count++;
+ env_array[count] = nullptr; // Maintain null terminator.
+ }
+
+ return 0;
+}
+
} // namespace internal
} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/stdlib/environ_internal.h b/libc/src/stdlib/environ_internal.h
index 0ab75e200b968..d902354f421cf 100644
--- a/libc/src/stdlib/environ_internal.h
+++ b/libc/src/stdlib/environ_internal.h
@@ -122,6 +122,13 @@ class EnvironmentManager {
// Look up a variable by name. Returns a pointer to the value string
// (after the '='), or nullptr if not found.
char *get(cpp::string_view name);
+
+ // Set or update an environment variable. Builds a "name=value" string,
+ // manages ownership, and updates the environ array. If `overwrite` is
+ // false and the variable already exists, does nothing and returns 0.
+ // Returns 0 on success, -1 on allocation failure (caller should set
+ // errno to ENOMEM).
+ int set(cpp::string_view name, cpp::string_view value, bool overwrite);
};
} // namespace internal
diff --git a/libc/src/stdlib/linux/CMakeLists.txt b/libc/src/stdlib/linux/CMakeLists.txt
index 8a4b2bab1c53d..aedcd3f11bf38 100644
--- a/libc/src/stdlib/linux/CMakeLists.txt
+++ b/libc/src/stdlib/linux/CMakeLists.txt
@@ -8,3 +8,18 @@ add_header_library(
libc.src.signal.linux.__restore
libc.src.signal.linux.signal_utils
)
+
+add_entrypoint_object(
+ setenv
+ SRCS
+ setenv.cpp
+ HDRS
+ ../setenv.h
+ DEPENDS
+ libc.src.__support.CPP.string_view
+ libc.src.__support.common
+ libc.src.__support.libc_errno
+ libc.src.__support.macros.config
+ libc.src.__support.macros.null_check
+ libc.src.stdlib.environ_internal
+)
diff --git a/libc/src/stdlib/linux/setenv.cpp b/libc/src/stdlib/linux/setenv.cpp
new file mode 100644
index 0000000000000..40a3b985bf251
--- /dev/null
+++ b/libc/src/stdlib/linux/setenv.cpp
@@ -0,0 +1,48 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 the POSIX setenv function.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/stdlib/setenv.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/common.h"
+#include "src/__support/libc_errno.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/null_check.h"
+#include "src/stdlib/environ_internal.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(int, setenv,
+ (const char *name, const char *value, int overwrite)) {
+ // Passing nullptr for either argument is undefined behavior per POSIX,
+ // so crash rather than returning an error.
+ LIBC_CRASH_ON_NULLPTR(name);
+ LIBC_CRASH_ON_NULLPTR(value);
+
+ cpp::string_view name_view(name);
+
+ // POSIX: name must not be empty or contain '='.
+ if (name_view.empty() ||
+ name_view.find_first_of('=') != cpp::string_view::npos) {
+ libc_errno = EINVAL;
+ return -1;
+ }
+
+ int result = internal::EnvironmentManager::get_instance().set(
+ name_view, value, overwrite != 0);
+ if (result != 0)
+ libc_errno = ENOMEM;
+
+ return result;
+}
+
+} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/stdlib/setenv.h b/libc/src/stdlib/setenv.h
new file mode 100644
index 0000000000000..365d768cdd668
--- /dev/null
+++ b/libc/src/stdlib/setenv.h
@@ -0,0 +1,25 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 the POSIX setenv function.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STDLIB_SETENV_H
+#define LLVM_LIBC_SRC_STDLIB_SETENV_H
+
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+int setenv(const char *name, const char *value, int overwrite);
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_STDLIB_SETENV_H
diff --git a/libc/test/integration/src/stdlib/CMakeLists.txt b/libc/test/integration/src/stdlib/CMakeLists.txt
index cf39b7ceb2f87..2e0389f9a60d3 100644
--- a/libc/test/integration/src/stdlib/CMakeLists.txt
+++ b/libc/test/integration/src/stdlib/CMakeLists.txt
@@ -18,6 +18,18 @@ add_integration_test(
)
if(${LIBC_TARGET_OS} STREQUAL "linux")
+ add_integration_test(
+ setenv_test
+ SUITE
+ stdlib-integration-tests
+ SRCS
+ setenv_test.cpp
+ DEPENDS
+ libc.src.stdlib.getenv
+ libc.src.stdlib.setenv
+ libc.src.string.strcmp
+ )
+
add_integration_test(
abort_test
SUITE
diff --git a/libc/test/integration/src/stdlib/setenv_test.cpp b/libc/test/integration/src/stdlib/setenv_test.cpp
new file mode 100644
index 0000000000000..4f9cc683433ab
--- /dev/null
+++ b/libc/test/integration/src/stdlib/setenv_test.cpp
@@ -0,0 +1,153 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/stdlib/getenv.h"
+#include "src/stdlib/setenv.h"
+#include "src/string/strcmp.h"
+
+#include "test/IntegrationTest/test.h"
+
+#include <errno.h>
+
+TEST_MAIN([[maybe_unused]] int argc, [[maybe_unused]] char **argv,
+ [[maybe_unused]] char **envp) {
+ // Test: Basic
+ {
+ // Set a simple environment variable
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("SETENV_TEST_VAR", "test_value", 1), 0);
+
+ // Verify it was set
+ char *value = LIBC_NAMESPACE::getenv("SETENV_TEST_VAR");
+ ASSERT_TRUE(value != nullptr);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(value, "test_value"), 0);
+ }
+
+ // Test: OverwriteExisting
+ {
+ // Set initial value
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("OVERWRITE_VAR", "original", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("OVERWRITE_VAR"),
+ "original"),
+ 0);
+
+ // Overwrite with new value (overwrite = 1)
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("OVERWRITE_VAR", "replaced", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("OVERWRITE_VAR"),
+ "replaced"),
+ 0);
+ }
+
+ // Test: NoOverwriteFlag
+ {
+ // Set initial value
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("NO_OVERWRITE_VAR", "original", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("NO_OVERWRITE_VAR"),
+ "original"),
+ 0);
+
+ // Try to set with overwrite = 0 (should not change)
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("NO_OVERWRITE_VAR", "ignored", 0), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("NO_OVERWRITE_VAR"),
+ "original"),
+ 0);
+
+ // Verify it still works with overwrite = 1
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("NO_OVERWRITE_VAR", "changed", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("NO_OVERWRITE_VAR"),
+ "changed"),
+ 0);
+ }
+
+ // Note: passing nullptr for name or value is undefined behavior per POSIX.
+ // The implementation uses LIBC_CRASH_ON_NULLPTR for both, so there is no
+ // test for that case here.
+
+ // Test: EmptyName
+ {
+ errno = 0;
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("", "value", 1), -1);
+ ASSERT_ERRNO_EQ(EINVAL);
+ }
+
+ // Test: NameWithEquals
+ {
+ errno = 0;
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("BAD=NAME", "value", 1), -1);
+ ASSERT_ERRNO_EQ(EINVAL);
+ }
+
+ // Test: EmptyValue
+ {
+ // Empty value is valid - just means variable is set to empty string
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("EMPTY_VALUE_VAR", "", 1), 0);
+
+ char *value = LIBC_NAMESPACE::getenv("EMPTY_VALUE_VAR");
+ ASSERT_TRUE(value != nullptr);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(value, ""), 0);
+ }
+
+ // Test: MultipleVariables
+ {
+ // Set multiple different variables
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("VAR1", "value1", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("VAR2", "value2", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("VAR3", "value3", 1), 0);
+
+ // Verify all are set correctly
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("VAR1"), "value1"),
+ 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("VAR2"), "value2"),
+ 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("VAR3"), "value3"),
+ 0);
+ }
+
+ // Test: LongValues
+ {
+ // Test with longer strings
+ const char *long_name = "LONG_VAR_NAME_FOR_TESTING";
+ const char *long_value = "This is a fairly long value string to test that "
+ "setenv handles longer strings correctly without "
+ "any memory issues or truncation problems";
+
+ ASSERT_EQ(LIBC_NAMESPACE::setenv(long_name, long_value, 1), 0);
+ ASSERT_EQ(
+ LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv(long_name), long_value),
+ 0);
+ }
+
+ // Test: SpecialCharacters
+ {
+ // Test with special characters in value (but not in name)
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("SPECIAL_CHARS", "!@#$%^&*()", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("SPECIAL_CHARS"),
+ "!@#$%^&*()"),
+ 0);
+ }
+
+ // Test: ReplaceMultipleTimes
+ {
+ // Replace the same variable multiple times
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("MULTI_REPLACE", "value1", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("MULTI_REPLACE"),
+ "value1"),
+ 0);
+
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("MULTI_REPLACE", "value2", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("MULTI_REPLACE"),
+ "value2"),
+ 0);
+
+ ASSERT_EQ(LIBC_NAMESPACE::setenv("MULTI_REPLACE", "value3", 1), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::strcmp(LIBC_NAMESPACE::getenv("MULTI_REPLACE"),
+ "value3"),
+ 0);
+ }
+
+ return 0;
+}
>From 88a883dab44a04381b13a2f44b3fb1ae8c8b7056 Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Fri, 8 May 2026 13:19:21 +0100
Subject: [PATCH 2/2] Update libc/test/integration/src/stdlib/setenv_test.cpp
Co-authored-by: Michael Jones <michaelrj at google.com>
---
libc/test/integration/src/stdlib/setenv_test.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libc/test/integration/src/stdlib/setenv_test.cpp b/libc/test/integration/src/stdlib/setenv_test.cpp
index 4f9cc683433ab..e8d8ea861e642 100644
--- a/libc/test/integration/src/stdlib/setenv_test.cpp
+++ b/libc/test/integration/src/stdlib/setenv_test.cpp
@@ -23,7 +23,7 @@ TEST_MAIN([[maybe_unused]] int argc, [[maybe_unused]] char **argv,
// Verify it was set
char *value = LIBC_NAMESPACE::getenv("SETENV_TEST_VAR");
- ASSERT_TRUE(value != nullptr);
+ ASSERT_NE(value, nullptr);
ASSERT_EQ(LIBC_NAMESPACE::strcmp(value, "test_value"), 0);
}
More information about the libc-commits
mailing list