[PATCH 2/3] scripts: bareboximd: Use mmap when possible

Sascha Hauer s.hauer at pengutronix.de
Fri Feb 11 01:42:29 PST 2022


Using mmap() in read_file_2 was dropped in the last patch, bring it back
in a bareboximd specific function here.

Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 common/imd.c         |  7 ++++++-
 scripts/bareboximd.c | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)

diff --git a/common/imd.c b/common/imd.c
index 0295d84d34..9ca0248523 100644
--- a/common/imd.c
+++ b/common/imd.c
@@ -21,6 +21,11 @@ static inline void read_file_2_free(void *buf)
 {
 	free(buf);
 }
+
+static int imd_read_file(const char *filename, size_t *size, void **outbuf)
+{
+	return read_file_2(filename, size, outbuf, 0x100000);
+}
 #endif
 
 /*
@@ -473,7 +478,7 @@ int imd_command(int argc, char *argv[])
 
 	filename = argv[optind];
 
-	ret = read_file_2(filename, &size, &buf, 0x100000);
+	ret = imd_read_file(filename, &size, &buf);
 	if (ret && ret != -EFBIG)
 		return -errno;
 
diff --git a/scripts/bareboximd.c b/scripts/bareboximd.c
index a734399aa5..2d4750d7fb 100644
--- a/scripts/bareboximd.c
+++ b/scripts/bareboximd.c
@@ -55,6 +55,40 @@ static unsigned long simple_strtoul(const char *cp, char **endp, unsigned int ba
 	return strtoul(cp, endp, base);
 }
 
+static int imd_read_file(const char *filename, size_t *size, void **outbuf)
+{
+	void *buf;
+	int fd, ret;
+	size_t fsize;
+
+	fd = open(filename, O_RDONLY);
+	if (fd < 0) {
+		fprintf(stderr, "Cannot open %s: %s\n", filename, strerror(errno));
+		return -errno;
+	}
+
+	fsize = lseek(fd, 0, SEEK_END);
+	if (fsize == -1) {
+		fprintf(stderr, "Cannot get size %s: %s\n", filename, strerror(errno));
+		ret = -errno;
+		goto close;
+	}
+
+	buf = mmap(NULL, fsize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
+	if (buf == MAP_FAILED) {
+		close(fd);
+		return read_file_2(filename, size, outbuf, 0x100000);
+	}
+
+	*outbuf = buf;
+	*size = fsize;
+
+	return 0;
+close:
+	close(fd);
+	return ret;
+}
+
 #include "../include/xfuncs.h"
 #include "../crypto/crc32.c"
 #include "../common/imd.c"
-- 
2.30.2




More information about the barebox mailing list