diff options
author | khali <khali> | 2015-04-21 07:04:27 +0000 |
---|---|---|
committer | khali <khali> | 2015-04-21 07:04:27 +0000 |
commit | b4f32bd3341060d1ee2b3424e9e73b679299a98b (patch) | |
tree | e5c017f41376702cd5f8e2b7ca8dd4b2e175c3e1 | |
parent | ad44e864c38f2a1d32c9b2ab1c633067d003333e (diff) | |
download | dmidecode-b4f32bd3341060d1ee2b3424e9e73b679299a98b.tar.gz |
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.
-rw-r--r-- | CHANGELOG | 5 | ||||
-rw-r--r-- | util.c | 55 | ||||
-rw-r--r-- | util.h | 1 |
3 files changed, 61 insertions, 0 deletions
@@ -1,3 +1,8 @@ +2015-04-21 Roy Franz <roy.franz@linaro.org> + + * util.c, util.h: Add utility function read_file, which reads an + entire binary file into a buffer. + 2015-04-20 Jean Delvare <jdelvare@suse.de> * biosdecode.c: Add support for the _SM3_ entry point, as defined in @@ -89,6 +89,61 @@ int checksum(const u8 *buf, size_t len) } /* + * 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. */ @@ -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); |