[PATCH v2 2/3] libfile: implement read_fd counterpart to read_file

Ahmad Fatoum a.fatoum at pengutronix.de
Wed Nov 22 09:03:22 PST 2023


Files opened with O_TMPFILE have no name, so read_file can't be used
with them. Therefore add a read_fd function, which slurps all a file's
contents into a buffer.

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
v1 -> v2:
  - Justify why the buffer is three bytes longer than the file's content
    (Yann)
  - Check for malloc failure (Yann)
  - Don't close file descriptor on failure as it's opened outside
    the function
  - set errno to indicate why the function failed
  - use fstat and pread_full (Sascha)
---
 include/libfile.h |  2 ++
 lib/libfile.c     | 50 +++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+)

diff --git a/include/libfile.h b/include/libfile.h
index a353ccfa9ea9..423e7ffec5b7 100644
--- a/include/libfile.h
+++ b/include/libfile.h
@@ -12,6 +12,8 @@ char *read_file_line(const char *fmt, ...);
 
 void *read_file(const char *filename, size_t *size);
 
+void *read_fd(int fd, size_t *size);
+
 int read_file_2(const char *filename, size_t *size, void **outbuf,
 		loff_t max_size);
 
diff --git a/lib/libfile.c b/lib/libfile.c
index e53ba08415a2..72a2fc79c721 100644
--- a/lib/libfile.c
+++ b/lib/libfile.c
@@ -306,6 +306,56 @@ void *read_file(const char *filename, size_t *size)
 }
 EXPORT_SYMBOL(read_file);
 
+/**
+ * read_fd - read from a file descriptor to an allocated buffer
+ * @filename:  The file descriptor to read
+ * @size:      After successful return contains the size of the file
+ *
+ * This function reads a file descriptor from offset 0 until EOF to an
+ * allocated buffer.
+ *
+ * Return: On success, returns a nul-terminated buffer with the file's
+ * contents that should be deallocated with free().
+ * On error, NULL is returned and errno is set to an error code.
+ */
+void *read_fd(int fd, size_t *out_size)
+{
+	struct stat st;
+	ssize_t ret;
+	void *buf;
+
+	ret = fstat(fd, &st);
+	if (ret < 0)
+		return NULL;
+
+	if (st.st_size == FILE_SIZE_STREAM) {
+		errno = EINVAL;
+		return NULL;
+	}
+
+	/* For user convenience, we always nul-terminate the buffer in
+	 * case it contains a string. As we don't want to assume the string
+	 * to be either an array of char or wchar_t, we just unconditionally
+	 * add 2 bytes as terminator. As the two byte terminator needs to be
+	 * aligned, we just make it three bytes
+	 */
+	buf = malloc(st.st_size + 3);
+	if (!buf)
+		return NULL;
+
+	ret = pread_full(fd, buf, st.st_size, 0);
+	if (ret < 0) {
+		free(buf);
+		return NULL;
+	}
+
+	memset(buf + st.st_size, '\0', 3);
+	*out_size = st.st_size;
+
+	return buf;
+}
+EXPORT_SYMBOL(read_fd);
+
 /**
  * write_file - write a buffer to a file
  * @filename:    The filename to write
-- 
2.39.2




More information about the barebox mailing list