From: Michael Tremer Date: Sat, 11 Jan 2025 13:20:22 +0000 (+0000) Subject: util: Create a convenience function to map files into memory X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=01709cf0df33b3246cf90b632de54d75c447ec1a;p=people%2Fric9%2Fpakfire.git util: Create a convenience function to map files into memory Signed-off-by: Michael Tremer --- diff --git a/src/pakfire/file.c b/src/pakfire/file.c index 6e1be494e..13b34f53c 100644 --- a/src/pakfire/file.c +++ b/src/pakfire/file.c @@ -1131,8 +1131,6 @@ FILE* pakfire_file_fopen(struct pakfire_file* file, const char* mode) { Opens the file and returns a mapping of the payload in memory */ static int pakfire_file_mmap(struct pakfire_file* file, char** data, size_t* length) { - struct stat st = {}; - char* buffer = NULL; int fd = -EBADF; int r; @@ -1141,26 +1139,13 @@ static int pakfire_file_mmap(struct pakfire_file* file, char** data, size_t* len if (fd < 0) goto ERROR; - // Stat the file - r = fstat(fd, &st); + // Map the file + r = pakfire_mmap(fd, data, length); if (r < 0) { - ERROR(file->ctx, "Could not stat %s: %m\n", pakfire_file_get_path(file)); - r = -errno; - goto ERROR; - } - - // Map the data - buffer = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); - if (buffer == MAP_FAILED) { - ERROR(file->ctx, "Could not map %s: %m\n", pakfire_file_get_path(file)); - r = -errno; + ERROR(file->ctx, "Could not map %s: %s\n", pakfire_file_get_path(file), strerror(-r)); goto ERROR; } - // Return the values - *data = buffer; - *length = st.st_size; - ERROR: if (fd >= 0) close(fd); diff --git a/src/pakfire/util.c b/src/pakfire/util.c index 943b80826..634c45f0c 100644 --- a/src/pakfire/util.c +++ b/src/pakfire/util.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -132,6 +133,37 @@ int pakfire_read_file_into_buffer(FILE* f, char** buffer, size_t* len) { return 0; } +/* + Maps a file descriptor into memory +*/ +int pakfire_mmap(int fd, char** data, size_t* length) { + char* buffer = NULL; + struct stat st = {}; + int r; + + // Check inputs + if (fd < 0) + return -EBADF; + else if (!data || !length) + return -EINVAL; + + // Stat the file + r = fstat(fd, &st); + if (r < 0) + return -errno; + + // Map the data + buffer = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (buffer == MAP_FAILED) + return -errno; + + // Return the values + *data = buffer; + *length = st.st_size; + + return 0; +} + char* pakfire_generate_uuid(void) { uuid_t uuid; diff --git a/src/pakfire/util.h b/src/pakfire/util.h index b2cdf80f1..6310face7 100644 --- a/src/pakfire/util.h +++ b/src/pakfire/util.h @@ -43,6 +43,7 @@ static inline void* pakfire_realloc(void* p, size_t size) { } int pakfire_read_file_into_buffer(FILE* f, char** buffer, size_t* len); +int pakfire_mmap(int fd, char** data, size_t* length); const char* pakfire_path_relpath(const char* root, const char* path);