[libc-commits] [libc] [libc] Add getpwent, setpwent, and endpwent entrypoints (PR #213076)

Alexey Samsonov via libc-commits libc-commits at lists.llvm.org
Thu Jul 30 20:56:12 PDT 2026


================
@@ -0,0 +1,170 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 getpwent.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/pwd/getpwent.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/File/file.h"
+#include "src/__support/common.h"
+#include "src/__support/libc_errno.h"
+#include "src/__support/macros/config.h"
+#include "src/pwd/pwd_utils.h"
+
+#include "hdr/stdio_macros.h"
+
+#ifndef LIBC_COPT_PWD_FILE_PATH
+#define LIBC_COPT_PWD_FILE_PATH "/etc/passwd"
+#endif
+
+namespace LIBC_NAMESPACE_DECL {
+
+static File *pwd_file = nullptr;
+static const char *pwd_file_path = LIBC_COPT_PWD_FILE_PATH;
+// Note: These static buffers are process-global and NOT protected by a mutex
+// at this stage. POSIX getpwent is non-reentrant.
+static char line_buffer[1024];
+static struct passwd pwd_entry;
+
+namespace internal {
+void set_passwd_path(const char *path) {
+  if (!path)
+    return;
+  if (pwd_file) {
+    pwd_file->close();
+    pwd_file = nullptr;
+  }
+  pwd_file_path = path;
+}
+} // namespace internal
+
+ErrorOr<int> setpwent_impl() {
+  if (!pwd_file) {
+    auto result = openfile(pwd_file_path, "r");
+    if (!result.has_value())
+      return Error(result.error());
+    pwd_file = result.value();
+  } else {
+    auto result = pwd_file->seek(0, SEEK_SET);
+    if (!result.has_value())
+      return Error(result.error());
+  }
+  return 0;
+}
+
+ErrorOr<int> endpwent_impl() {
+  if (pwd_file) {
+    int result = pwd_file->close();
+    pwd_file = nullptr;
+    if (result != 0)
+      return Error(result);
+  }
+  return 0;
+}
+
+struct ReadLineResult {
----------------
vonosmas wrote:

See above - I think you can also implement all these under `namespace pwd`, then having this type would unlikely cause conflicts

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


More information about the libc-commits mailing list