[libc-commits] [libc] [libc][POSIX][unistd] Implement gethostname (PR #128142)

Michael Jones via libc-commits libc-commits at lists.llvm.org
Fri Feb 21 12:41:03 PST 2025


================
@@ -0,0 +1,60 @@
+//===-- Linux implementation of gethostname -------------------------------===//
+//
+// 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/unistd/gethostname.h"
+
+#include "hdr/types/size_t.h"
+#include "src/__support/OSUtil/syscall.h" // For internal syscall function.
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+
+#include "src/errno/libc_errno.h"
+#include "src/string/strlen.h"
+#include "src/string/strncpy.h"
+
+#include <sys/syscall.h> // For syscall numbers.
+#include <sys/utsname.h>
+
+namespace LIBC_NAMESPACE_DECL {
+
+// Matching the behavior of glibc version 2.2 and later.
+// Copies up to len bytes from the returned nodename field into name.
+LLVM_LIBC_FUNCTION(int, gethostname, (char *name, size_t len)) {
+  // Check for invalid pointer
+  if (name == nullptr) {
+    libc_errno = EFAULT;
+    return -1;
+  }
+
+  struct utsname unameData;
+  int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_uname, &unameData);
+
+  // Checks if the length of the nodename was greater than or equal to len, and
+  // if it is, then the function returns -1 with errno set to ENAMETOOLONG. In
+  // this case, a terminating null byte is not included in the returned name.
+  if (strlen(unameData.nodename) >= len) {
----------------
michaelrj-google wrote:

LLVM-libc doesn't allow to calling other libc functions within libc functions so that each entrypoint is independent of all the others. The intended way to use these specific functions is to call their internal implementations from `/src/string/string_utils.h`.

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


More information about the libc-commits mailing list