Re: [PATCH 1/2] tools/nolibc: Add fread() to stdio.h

From: David Laight
Date: Sun Jan 04 2026 - 13:35:02 EST


On Sun, 4 Jan 2026 17:38:36 +0900
Daniel Palmer <daniel@xxxxxxxxx> wrote:

> Add a very basic version of fread() like we already have for fwrite().
>
> Signed-off-by: Daniel Palmer <daniel@xxxxxxxxx>
> ---
> tools/include/nolibc/stdio.h | 35 ++++++++++++++++++++++++++++++++++-
> 1 file changed, 34 insertions(+), 1 deletion(-)
>
> diff --git a/tools/include/nolibc/stdio.h b/tools/include/nolibc/stdio.h
> index 1f16dab2ac88..21569ebae824 100644
> --- a/tools/include/nolibc/stdio.h
> +++ b/tools/include/nolibc/stdio.h
> @@ -170,7 +170,7 @@ int putchar(int c)
> }
>
>
> -/* fwrite(), puts(), fputs(). Note that puts() emits '\n' but not fputs(). */
> +/* fwrite(), fread(), puts(), fputs(). Note that puts() emits '\n' but not fputs(). */
>
> /* internal fwrite()-like function which only takes a size and returns 0 on
> * success or EOF on error. It automatically retries on short writes.
> @@ -204,6 +204,39 @@ size_t fwrite(const void *s, size_t size, size_t nmemb, FILE *stream)
> return written;
> }
>
> +/* internal fread()-like function which only takes a size and returns 0 on
> + * success or EOF on error. It automatically retries on short reads.
> + */
> +static __attribute__((unused))
> +int _fread(void *buf, size_t size, FILE *stream)
> +{
> + ssize_t ret;
> + int fd = fileno(stream);
> +
> + while (size) {
> + ret = read(fd, buf, size);
> + if (ret <= 0)
> + return EOF;

You need to return a partial length if some data was read before EOF.

> + size -= ret;
> + buf += ret;
> + }
> + return 0;
> +}
> +
> +
> +static __attribute__((unused))
> +size_t fread(void *s, size_t size, size_t nmemb, FILE *stream)
> +{
> + size_t readed;

Isn't it enough to just multiply 'size' and 'nmemb' together
and then do a single long read() (maybe with retries for short reads).
The multiply can't overflow (for a valid request) because the buffer
size is also limited to 'size_t'.

OTOH Linux limits the maximum return from read() to INT_MAX - PAGE_SIZE
(even on 64bit).

David


> +
> + for (readed = 0; readed < nmemb; readed++) {
> + if (_fread(s, size, stream) != 0)
> + break;
> + s += size;
> + }
> + return readed;
> +}
> +
> static __attribute__((unused))
> int fputs(const char *s, FILE *stream)
> {