|
| 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/libc_errno.h" |
| 15 | +#include "src/__support/macros/config.h" |
| 16 | +#include "src/string/string_utils.h" |
| 17 | + |
| 18 | +#include <sys/syscall.h> // For syscall numbers. |
| 19 | +#include <sys/utsname.h> |
| 20 | + |
| 21 | +namespace LIBC_NAMESPACE_DECL { |
| 22 | + |
| 23 | +LLVM_LIBC_FUNCTION(int, gethostname, (char *name, size_t size)) { |
| 24 | + // Check for invalid pointer |
| 25 | + if (name == nullptr) { |
| 26 | + libc_errno = EFAULT; |
| 27 | + return -1; |
| 28 | + } |
| 29 | + |
| 30 | + // Because there is no SYS_gethostname syscall, we use uname to get the |
| 31 | + // hostname. |
| 32 | + utsname unameData; |
| 33 | + int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_uname, &unameData); |
| 34 | + if (ret < 0) { |
| 35 | + libc_errno = static_cast<int>(-ret); |
| 36 | + return -1; |
| 37 | + } |
| 38 | + |
| 39 | + // Guarantee that the name will be null terminated. |
| 40 | + // The amount of bytes copied is min(size + 1, strlen(nodename) + 1) |
| 41 | + // +1 to account for the null terminator (the last copied byte is a NULL). |
| 42 | + internal::strlcpy(name, unameData.nodename, size + 1); |
| 43 | + |
| 44 | + // Checks if the length of the hostname was greater than or equal to size |
| 45 | + if (internal::string_length(unameData.nodename) >= size) { |
| 46 | + libc_errno = ENAMETOOLONG; |
| 47 | + return -1; |
| 48 | + } |
| 49 | + |
| 50 | + return 0; |
| 51 | +} |
| 52 | + |
| 53 | +} // namespace LIBC_NAMESPACE_DECL |
0 commit comments