[libc-commits] [libc] [libc][stdlib] Add EnvironmentManager (PR #195260)

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Tue May 5 12:01:44 PDT 2026


================
@@ -0,0 +1,179 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 internal environment management utilities.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/stdlib/environ_internal.h"
+#include "config/app.h"
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/alloc-checker.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace internal {
+
+// Minimum initial capacity for the environment array when first allocated.
+// This avoids frequent reallocations for small environments.
+constexpr size_t MIN_ENVIRON_CAPACITY = 32;
+
+// Growth factor for environment array capacity when expanding.
+// When capacity is exceeded, new_capacity = old_capacity *
+// ENVIRON_GROWTH_FACTOR.
+constexpr size_t ENVIRON_GROWTH_FACTOR = 2;
+
+void EnvironmentManager::init_once() {
----------------
kaladron wrote:

Correct - not intended to be thread safe at the moment.  POSIX explicitly says that it "need not be thread safe", although in practice glibc does make it work.

I submitted this originally last October in https://github.com/llvm/llvm-project/pull/163018 as part of implementing setenv and the conversation there was largely around thread safety.  The problem is one of layering:

 * setenv calls malloc/realloc
 * malloc changes behaviour from environment variables, so calls getenv

I do want to add thread safety after, but I'd also like to get this landed for now

For the init_once call, one possibly solution is to initialise it in _start as well.

Does that make sense?  I'm happy to consider other approaches.

https://github.com/llvm/llvm-project/pull/195260


More information about the libc-commits mailing list