Skip to content

Commit a5f00be

Browse files
fifteenhext-8ch
authored andcommitted
tools/nolibc: Add a simple test for writing to a FILE and reading it back
Add a test that exercises create->write->seek->read to check that using the stream functions (fwrite() etc) is not totally broken. The only edge cases this is testing for are: - Reading the file after writing but without rewinding reads nothing. - Trying to read more items than the file contains returns the count of fully read items. Signed-off-by: Daniel Palmer <daniel@thingy.jp> Link: https://patch.msgid.link/20260105023629.1502801-4-daniel@thingy.jp Signed-off-by: Thomas Weißschuh <linux@weissschuh.net>
1 parent 109770c commit a5f00be

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

tools/testing/selftests/nolibc/nolibc-test.c

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,58 @@ int test_file_stream(void)
878878
return 0;
879879
}
880880

881+
int test_file_stream_wsr(void)
882+
{
883+
const char dataout[] = "foo";
884+
const size_t datasz = sizeof(dataout);
885+
char datain[datasz];
886+
int fd, r;
887+
FILE *f;
888+
889+
fd = open("/tmp", O_TMPFILE | O_RDWR, 0644);
890+
if (fd == -1)
891+
return -1;
892+
893+
f = fdopen(fd, "w+");
894+
if (!f)
895+
return -1;
896+
897+
errno = 0;
898+
r = fwrite(dataout, 1, datasz, f);
899+
if (r != datasz)
900+
return -1;
901+
902+
/* Attempt to read from the file without rewinding,
903+
* we should read 0 items.
904+
*/
905+
r = fread(datain, 1, datasz, f);
906+
if (r)
907+
return -1;
908+
909+
/* Rewind the file to the start */
910+
r = fseek(f, 0, SEEK_SET);
911+
if (r)
912+
return -1;
913+
914+
/* Attempt to read back more than was written to
915+
* make sure we handle short reads properly.
916+
* fread() should return the number of complete items.
917+
*/
918+
r = fread(datain, 1, datasz + 1, f);
919+
if (r != datasz)
920+
return -1;
921+
922+
/* Data we read should match the data we just wrote */
923+
if (memcmp(datain, dataout, datasz) != 0)
924+
return -1;
925+
926+
r = fclose(f);
927+
if (r)
928+
return -1;
929+
930+
return 0;
931+
}
932+
881933
enum fork_type {
882934
FORK_STANDARD,
883935
FORK_VFORK,
@@ -1352,6 +1404,7 @@ int run_syscall(int min, int max)
13521404
CASE_TEST(fchdir_stdin); EXPECT_SYSER(1, fchdir(STDIN_FILENO), -1, ENOTDIR); break;
13531405
CASE_TEST(fchdir_badfd); EXPECT_SYSER(1, fchdir(-1), -1, EBADF); break;
13541406
CASE_TEST(file_stream); EXPECT_SYSZR(1, test_file_stream()); break;
1407+
CASE_TEST(file_stream_wsr); EXPECT_SYSZR(1, test_file_stream_wsr()); break;
13551408
CASE_TEST(fork); EXPECT_SYSZR(1, test_fork(FORK_STANDARD)); break;
13561409
CASE_TEST(getdents64_root); EXPECT_SYSNE(1, test_getdents64("/"), -1); break;
13571410
CASE_TEST(getdents64_null); EXPECT_SYSER(1, test_getdents64("/dev/null"), -1, ENOTDIR); break;

0 commit comments

Comments
 (0)