[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) {
+    strncpy(name, unameData.nodename, len);
----------------
michaelrj-google wrote:

you're doing the same copy in both branches, you can move it up before the `if`. Also the [posix standard](https://pubs.opengroup.org/onlinepubs/9799919799/functions/gethostname.html) says that if the name is too long "it is unspecified whether the returned name is null-terminated". I think guaranteeing that the name will be null terminated would be a good idea, could you add code to do that?

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


More information about the libc-commits mailing list