74 lines · cpp
1//===-- Unittests for ioctl -----------------------------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/fcntl/open.h"10#include "src/sys/ioctl/ioctl.h"11#include "src/unistd/close.h"12#include "src/unistd/read.h"13#include "src/unistd/write.h"14#include "test/UnitTest/ErrnoCheckingTest.h"15#include "test/UnitTest/ErrnoSetterMatcher.h"16#include "test/UnitTest/Test.h"17 18#include "hdr/sys_stat_macros.h"19 20#include "hdr/sys_ioctl_macros.h"21 22using LlvmLibcSysIoctlTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;23using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;24 25TEST_F(LlvmLibcSysIoctlTest, InvalidCommandAndFIONREAD) {26 // Setup the test file27 constexpr const char *TEST_FILE_NAME = "ioctl.test";28 constexpr const char TEST_MSG[] = "ioctl test";29 constexpr int TEST_MSG_SIZE = sizeof(TEST_MSG) - 1;30 auto TEST_FILE = libc_make_test_file_path(TEST_FILE_NAME);31 int new_test_file_fd = LIBC_NAMESPACE::open(32 TEST_FILE, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);33 ASSERT_THAT(34 (int)LIBC_NAMESPACE::write(new_test_file_fd, TEST_MSG, TEST_MSG_SIZE),35 Succeeds(TEST_MSG_SIZE));36 ASSERT_ERRNO_SUCCESS();37 ASSERT_THAT(LIBC_NAMESPACE::close(new_test_file_fd), Succeeds(0));38 ASSERT_ERRNO_SUCCESS();39 40 // Reopen the file for testing41 int fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY);42 ASSERT_ERRNO_SUCCESS();43 ASSERT_GT(fd, 0);44 45 // FIONREAD reports the number of available bytes to read for the passed fd46 // This will report the full size of the file, as we haven't read anything yet47 int n = -1;48 int ret = LIBC_NAMESPACE::ioctl(fd, FIONREAD, &n);49 ASSERT_ERRNO_SUCCESS();50 ASSERT_GT(ret, -1);51 ASSERT_EQ(n, TEST_MSG_SIZE);52 53 // But if we read some bytes...54 constexpr int READ_COUNT = 5;55 char read_buffer[READ_COUNT];56 ASSERT_THAT((int)LIBC_NAMESPACE::read(fd, read_buffer, READ_COUNT),57 Succeeds(READ_COUNT));58 59 // ... n should have decreased by the number of bytes we've read60 int n_after_reading = -1;61 ret = LIBC_NAMESPACE::ioctl(fd, FIONREAD, &n_after_reading);62 ASSERT_ERRNO_SUCCESS();63 ASSERT_GT(ret, -1);64 ASSERT_EQ(n - READ_COUNT, n_after_reading);65 66 // 0xDEADBEEF is just a random nonexistent command;67 // calling this should always fail with ENOTTY68 ret = LIBC_NAMESPACE::ioctl(fd, 0xDEADBEEF, NULL);69 ASSERT_ERRNO_EQ(ENOTTY);70 ASSERT_EQ(ret, -1);71 72 ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));73}74