From b4f32bd3341060d1ee2b3424e9e73b679299a98b Mon Sep 17 00:00:00 2001 From: khali Date: Tue, 21 Apr 2015 07:04:27 +0000 Subject: util: Add read_file() function for reading sysfs files Add a function that can read a complete, unknown size file for reading entry point files from sysfs. This function models its signature on the mem_chunk() funtion, so it also allocates memory that the caller needs to free. The files that we are interested in reading are very small, and have a known upper bound on the size. The EINTR handling is based on the myread() function. Contributed by Roy Franz. --- CHANGELOG | 5 +++++ util.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ util.h | 1 + 3 files changed, 61 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 0a9396a..3fc9573 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,8 @@ +2015-04-21 Roy Franz + + * util.c, util.h: Add utility function read_file, which reads an + entire binary file into a buffer. + 2015-04-20 Jean Delvare * biosdecode.c: Add support for the _SM3_ entry point, as defined in diff --git a/util.c b/util.c index 2ab4915..c8ce365 100644 --- a/util.c +++ b/util.c @@ -88,6 +88,61 @@ int checksum(const u8 *buf, size_t len) return (sum == 0); } +/* + * Reads all of file, up to max_len bytes. + * A buffer of max_len bytes is allocated by this function, and + * needs to be freed by the caller. + * This provides a similar usage model to mem_chunk() + * + * Returns pointer to buffer of max_len bytes, or NULL on error + * + */ +void *read_file(size_t max_len, const char *filename) +{ + int fd; + size_t r2 = 0; + ssize_t r; + u8 *p; + + /* + * Don't print error message on missing file, as we will try to read + * files that may or may not be present. + */ + if ((fd = open(filename, O_RDONLY)) == -1) + { + if (errno != ENOENT) + perror(filename); + return(NULL); + } + + if ((p = malloc(max_len)) == NULL) + { + perror("malloc"); + return NULL; + } + + do + { + r = read(fd, p + r2, max_len - r2); + if (r == -1) + { + if (errno != EINTR) + { + close(fd); + perror(filename); + free(p); + return NULL; + } + } + else + r2 += r; + } + while (r != 0); + + close(fd); + return p; +} + /* * Copy a physical memory chunk into a memory buffer. * This function allocates memory. diff --git a/util.h b/util.h index e564292..2f0af51 100644 --- a/util.h +++ b/util.h @@ -25,6 +25,7 @@ #define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0])) int checksum(const u8 *buf, size_t len); +void *read_file(size_t len, const char *filename); void *mem_chunk(size_t base, size_t len, const char *devmem); int write_dump(size_t base, size_t len, const void *data, const char *dumpfile, int add); u64 u64_range(u64 start, u64 end); -- cgit v1.2.1