LibC: Fix overflow error in `fread` and `fwrite`

This commit is contained in:
Bananymous 2025-04-19 18:42:12 +03:00
parent 3d34e6e6d9
commit 12d47858c1
1 changed files with 19 additions and 18 deletions

View File

@ -382,25 +382,22 @@ int fputs(const char* str, FILE* file)
size_t fread(void* buffer, size_t size, size_t nitems, FILE* file) size_t fread(void* buffer, size_t size, size_t nitems, FILE* file)
{ {
ScopeLock _(file); ScopeLock _(file);
if (file->eof || nitems * size == 0) if (file->eof || size == 0 || nitems == 0)
return 0; return 0;
size_t target = size * nitems; auto* ubuffer = static_cast<unsigned char*>(buffer);
size_t nread = 0; for (size_t item = 0; item < nitems; item++)
if (target == 0)
return 0;
unsigned char* ubuffer = static_cast<unsigned char*>(buffer);
while (nread < target)
{ {
int ch = getc_unlocked(file); for (size_t byte = 0; byte < size; byte++)
if (ch == EOF) {
break; int ch = getc_unlocked(file);
ubuffer[nread++] = ch; if (ch == EOF)
return item;
*ubuffer++ = ch;
}
} }
return nread / size; return nitems;
} }
FILE* freopen(const char* pathname, const char* mode_str, FILE* file) FILE* freopen(const char* pathname, const char* mode_str, FILE* file)
@ -507,10 +504,14 @@ void funlockfile(FILE* fp)
size_t fwrite(const void* buffer, size_t size, size_t nitems, FILE* file) size_t fwrite(const void* buffer, size_t size, size_t nitems, FILE* file)
{ {
ScopeLock _(file); ScopeLock _(file);
unsigned char* ubuffer = (unsigned char*)buffer; if (size == 0 || nitems == 0)
for (size_t byte = 0; byte < nitems * size; byte++) return 0;
if (putc_unlocked(ubuffer[byte], file) == EOF)
return byte / size; const auto* ubuffer = static_cast<const unsigned char*>(buffer);
for (size_t item = 0; item < nitems; item++)
for (size_t byte = 0; byte < size; byte++)
if (putc_unlocked(*ubuffer++, file) == EOF)
return item;
return nitems; return nitems;
} }