|
| 1 | +//===-- Linux implementation of gethostname -------------------------------===// |
| 2 | +// |
| 3 | +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | +// See https://llvm.org/LICENSE.txt for license information. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | +// |
| 7 | +//===----------------------------------------------------------------------===// |
| 8 | + |
| 9 | +#include "src/unistd/gethostname.h" |
| 10 | + |
| 11 | +#include "hdr/types/size_t.h" |
| 12 | +#include "src/__support/OSUtil/syscall.h" // For internal syscall function. |
| 13 | +#include "src/__support/common.h" |
| 14 | +#include "src/__support/macros/config.h" |
| 15 | + |
| 16 | +#include "src/string/strlen.h" |
| 17 | +#include "src/string/strncpy.h" |
| 18 | +#include "src/errno/libc_errno.h" |
| 19 | + |
| 20 | +#include <sys/syscall.h> // For syscall numbers. |
| 21 | +#include <sys/utsname.h> |
| 22 | + |
| 23 | +namespace LIBC_NAMESPACE_DECL { |
| 24 | + |
| 25 | +// Matching the behavior of glibc version 2.2 and later. |
| 26 | +// Copies up to len bytes from the returned nodename field into name. |
| 27 | +LLVM_LIBC_FUNCTION(int, gethostname, (char *name, size_t len)) { |
| 28 | + |
| 29 | + // Check for invalid pointer |
| 30 | + if (name == nullptr) { |
| 31 | + libc_errno = EFAULT; |
| 32 | + return -1; |
| 33 | + } |
| 34 | + |
| 35 | + struct utsname unameData; |
| 36 | + int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_uname, &unameData); |
| 37 | + |
| 38 | + // Checks if the length of the nodename was greater than or equal to len, and if it is, |
| 39 | + // then the function returns -1 with errno set to ENAMETOOLONG. |
| 40 | + // In this case, a terminating null byte is not included in the returned name. |
| 41 | + if (strlen(unameData.nodename) >= len) |
| 42 | + { |
| 43 | + strncpy(name, unameData.nodename, len); |
| 44 | + libc_errno = ENAMETOOLONG; |
| 45 | + return -1; |
| 46 | + } |
| 47 | + |
| 48 | + // If the size of the array name is not large enough (less than the size of nodename with null termination), then anything might happen. |
| 49 | + // In this case, what happens to the array name will be determined by the implementation of LIBC_NAMESPACE_DECL::strncpy |
| 50 | + strncpy(name, unameData.nodename, len); |
| 51 | + |
| 52 | + if (ret < 0) { |
| 53 | + libc_errno = static_cast<int>(-ret); |
| 54 | + return -1; |
| 55 | + } |
| 56 | + |
| 57 | + return 0; |
| 58 | +} |
| 59 | + |
| 60 | +} // namespace LIBC_NAMESPACE_DECL |
| 61 | + |
| 62 | + |
0 commit comments