| 1 | //===-- Linux implementation of recvfrom ----------------------------------===// |
| 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/sys/socket/recvfrom.h" |
| 10 | |
| 11 | #include <linux/net.h> // For SYS_SOCKET socketcall number. |
| 12 | #include <sys/syscall.h> // For syscall numbers. |
| 13 | |
| 14 | #include "hdr/types/socklen_t.h" |
| 15 | #include "hdr/types/ssize_t.h" |
| 16 | #include "hdr/types/struct_sockaddr.h" |
| 17 | #include "src/__support/OSUtil/syscall.h" // For internal syscall function. |
| 18 | #include "src/__support/common.h" |
| 19 | #include "src/__support/libc_errno.h" |
| 20 | #include "src/__support/macros/sanitizer.h" |
| 21 | |
| 22 | namespace LIBC_NAMESPACE_DECL { |
| 23 | |
| 24 | LLVM_LIBC_FUNCTION(ssize_t, recvfrom, |
| 25 | (int sockfd, void *buf, size_t len, int flags, |
| 26 | sockaddr *__restrict src_addr, |
| 27 | socklen_t *__restrict addrlen)) { |
| 28 | // addrlen is a value-result argument. If it's not null, it passes the max |
| 29 | // size of the buffer src_addr to the syscall. After the syscall, it's updated |
| 30 | // to the actual size of the source address. This may be larger than the |
| 31 | // buffer, in which case the buffer contains a truncated result. |
| 32 | size_t srcaddr_sz; |
| 33 | if (src_addr) |
| 34 | srcaddr_sz = *addrlen; |
| 35 | (void)srcaddr_sz; // prevent "set but not used" warning |
| 36 | |
| 37 | #ifdef SYS_recvfrom |
| 38 | ssize_t ret = LIBC_NAMESPACE::syscall_impl<ssize_t>( |
| 39 | SYS_recvfrom, sockfd, buf, len, flags, src_addr, addrlen); |
| 40 | #elif defined(SYS_socketcall) |
| 41 | unsigned long sockcall_args[6] = {static_cast<unsigned long>(sockfd), |
| 42 | reinterpret_cast<unsigned long>(buf), |
| 43 | static_cast<unsigned long>(len), |
| 44 | static_cast<unsigned long>(flags), |
| 45 | reinterpret_cast<unsigned long>(src_addr), |
| 46 | static_cast<unsigned long>(addrlen)}; |
| 47 | ssize_t ret = LIBC_NAMESPACE::syscall_impl<ssize_t>( |
| 48 | SYS_socketcall, SYS_RECVFROM, sockcall_args); |
| 49 | #else |
| 50 | #error "socket and socketcall syscalls unavailable for this platform." |
| 51 | #endif |
| 52 | if (ret < 0) { |
| 53 | libc_errno = static_cast<int>(-ret); |
| 54 | return -1; |
| 55 | } |
| 56 | |
| 57 | MSAN_UNPOISON(buf, ret); |
| 58 | |
| 59 | if (src_addr) { |
| 60 | size_t min_src_addr_size = (*addrlen < srcaddr_sz) ? *addrlen : srcaddr_sz; |
| 61 | (void)min_src_addr_size; // prevent "set but not used" warning |
| 62 | |
| 63 | MSAN_UNPOISON(src_addr, min_src_addr_size); |
| 64 | } |
| 65 | return ret; |
| 66 | } |
| 67 | |
| 68 | } // namespace LIBC_NAMESPACE_DECL |
| 69 | |