1 //===-- Unittests for f operations like fopen, flcose etc --------------===// 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/stdio/clearerr_unlocked.h" 10 #include "src/stdio/fclose.h" 11 #include "src/stdio/feof_unlocked.h" 12 #include "src/stdio/ferror_unlocked.h" 13 #include "src/stdio/flockfile.h" 14 #include "src/stdio/fopen.h" 15 #include "src/stdio/fread_unlocked.h" 16 #include "src/stdio/funlockfile.h" 17 #include "src/stdio/fwrite_unlocked.h" 18 #include "utils/UnitTest/Test.h" 19 20 #include <errno.h> 21 #include <stdio.h> 22 23 TEST(LlvmLibcFILETest, UnlockedReadAndWrite) { 24 constexpr char fNAME[] = "testdata/unlocked_read_and_write.test"; 25 ::FILE *f = __llvm_libc::fopen(fNAME, "w"); 26 ASSERT_FALSE(f == nullptr); 27 constexpr char CONTENT[] = "1234567890987654321"; 28 __llvm_libc::flockfile(f); 29 ASSERT_EQ(sizeof(CONTENT) - 1, 30 __llvm_libc::fwrite_unlocked(CONTENT, 1, sizeof(CONTENT) - 1, f)); 31 // Should be an error to read. 32 constexpr size_t READ_SIZE = 5; 33 char data[READ_SIZE * 2 + 1]; 34 data[READ_SIZE * 2] = '\0'; 35 36 ASSERT_EQ(size_t(0), 37 __llvm_libc::fread_unlocked(data, 1, sizeof(READ_SIZE), f)); 38 ASSERT_NE(__llvm_libc::ferror_unlocked(f), 0); 39 ASSERT_NE(errno, 0); 40 errno = 0; 41 42 __llvm_libc::clearerr_unlocked(f); 43 ASSERT_EQ(__llvm_libc::ferror_unlocked(f), 0); 44 45 __llvm_libc::funlockfile(f); 46 ASSERT_EQ(0, __llvm_libc::fclose(f)); 47 48 f = __llvm_libc::fopen(fNAME, "r"); 49 ASSERT_FALSE(f == nullptr); 50 51 __llvm_libc::flockfile(f); 52 ASSERT_EQ(__llvm_libc::fread_unlocked(data, 1, READ_SIZE, f), READ_SIZE); 53 ASSERT_EQ(__llvm_libc::fread_unlocked(data + READ_SIZE, 1, READ_SIZE, f), 54 READ_SIZE); 55 56 // Should be an error to write. 57 ASSERT_EQ(size_t(0), 58 __llvm_libc::fwrite_unlocked(CONTENT, 1, sizeof(CONTENT), f)); 59 ASSERT_NE(__llvm_libc::ferror_unlocked(f), 0); 60 ASSERT_NE(errno, 0); 61 errno = 0; 62 63 __llvm_libc::clearerr_unlocked(f); 64 ASSERT_EQ(__llvm_libc::ferror_unlocked(f), 0); 65 66 // Reading more should trigger eof. 67 char large_data[sizeof(CONTENT)]; 68 ASSERT_NE(sizeof(CONTENT), 69 __llvm_libc::fread_unlocked(large_data, 1, sizeof(CONTENT), f)); 70 ASSERT_NE(__llvm_libc::feof_unlocked(f), 0); 71 72 __llvm_libc::funlockfile(f); 73 ASSERT_STREQ(data, "1234567890"); 74 75 ASSERT_EQ(__llvm_libc::fclose(f), 0); 76 } 77