Re: [PATCH] fixdep: handle short reads in read_file

From: Masahiro Yamada
Date: Fri Sep 06 2024 - 22:03:28 EST


On Sat, Sep 7, 2024 at 12:29 AM Sam James <sam@xxxxxxxxxx> wrote:
>
> 50% or so of kernel builds within our package manager fail for me with
> 'fixdep: read: success' because read(), for some reason - possibly ptrace,
> only read a short amount, not the full size.
>
> Unfortunately, this didn't trigger a -Wunused-result warning because
> we _are_ checking the return value, but with a bad comparison (it's completely
> fine for read() to not read the whole file in one gulp).
>
> Fixes: 01b5cbe7012fb1eeffc5c143865569835bcd405e


Fixes: 01b5cbe7012f ("fixdep: use malloc() and read() to load dep_file
to buffer")


I guess, another approach would be to use fread() instead of read().

Does the attached diff fix the issue too?





> Signed-off-by: Sam James <sam@xxxxxxxxxx>
> ---
> scripts/basic/fixdep.c | 12 +++++++++---
> 1 file changed, 9 insertions(+), 3 deletions(-)
>
> diff --git a/scripts/basic/fixdep.c b/scripts/basic/fixdep.c
> index 84b6efa849f4d..04d7742c99ac2 100644
> --- a/scripts/basic/fixdep.c
> +++ b/scripts/basic/fixdep.c
> @@ -233,9 +233,15 @@ static void *read_file(const char *filename)
> perror("fixdep: malloc");
> exit(2);
> }
> - if (read(fd, buf, st.st_size) != st.st_size) {
> - perror("fixdep: read");
> - exit(2);
> + ssize_t bytes = 0;
> + while (bytes < st.st_size) {
> + ssize_t cur = read(fd, buf + bytes, st.st_size - bytes);
> + if (cur == -1) {
> + perror("fixdep: read");
> + exit(2);
> + } else {
> + bytes += cur;
> + }
> }
> buf[st.st_size] = '\0';
> close(fd);
> --
> 2.46.0
>


--
Best Regards
Masahiro Yamada
diff --git a/scripts/basic/fixdep.c b/scripts/basic/fixdep.c
index cdd5da7e009b..7a0ca9f0fbbe 100644
--- a/scripts/basic/fixdep.c
+++ b/scripts/basic/fixdep.c
@@ -89,10 +89,7 @@
* but I don't think the added complexity is worth it)
*/

-#include <sys/types.h>
#include <sys/stat.h>
-#include <unistd.h>
-#include <fcntl.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
@@ -213,27 +210,28 @@ static void parse_config_file(const char *p)
static void *read_file(const char *filename)
{
struct stat st;
- int fd;
+ FILE *file;
char *buf;

- fd = open(filename, O_RDONLY);
- if (fd < 0) {
+ file = fopen(filename, "rb");
+ if (!file) {
fprintf(stderr, "fixdep: error opening file: ");
perror(filename);
exit(2);
}
- if (fstat(fd, &st) < 0) {
- fprintf(stderr, "fixdep: error fstat'ing file: ");
+ if (stat(filename, &st) < 0) {
+ fprintf(stderr, "fixdep: error stat'ing file: ");
perror(filename);
exit(2);
}
+
buf = xmalloc(st.st_size + 1);
- if (read(fd, buf, st.st_size) != st.st_size) {
+ if (fread(buf, 1, st.st_size, file) != st.st_size) {
perror("fixdep: read");
exit(2);
}
buf[st.st_size] = '\0';
- close(fd);
+ fclose(file);

return buf;
}