aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAndre Przywara <andre.przywara@arm.com>2015-10-30 18:26:55 +0000
committerWill Deacon <will.deacon@arm.com>2015-11-18 10:50:02 +0000
commit649f9515e623adf982c4e9a9922cfce173fd9de8 (patch)
tree9d332c8ca403e357bdaf6f14f50ceab962e5cd23
parent004f76848ebf121ad444c48a46b4f3ab7c14784f (diff)
downloadkvmtool-649f9515e623adf982c4e9a9922cfce173fd9de8.tar.gz
provide generic read_file() implementation
In various parts of kvmtool we simply try to read files into memory, but fail to do so in a safe way. The read(2) syscall can return early having only parts of the file read, or it may return -1 due to being interrupted by a signal (in which case we should simply retry). The ARM code seems to provide the only safe implementation, so take that as an inspiration to provide a generic read_file() function usable by every part of kvmtool. Signed-off-by: Andre Przywara <andre.przywara@arm.com> Signed-off-by: Will Deacon <will.deacon@arm.com>
-rw-r--r--include/kvm/read-write.h2
-rw-r--r--util/read-write.c21
2 files changed, 23 insertions, 0 deletions
diff --git a/include/kvm/read-write.h b/include/kvm/read-write.h
index 67571f96..acbd6f0b 100644
--- a/include/kvm/read-write.h
+++ b/include/kvm/read-write.h
@@ -12,6 +12,8 @@
ssize_t xread(int fd, void *buf, size_t count);
ssize_t xwrite(int fd, const void *buf, size_t count);
+ssize_t read_file(int fd, char *buf, size_t max_size);
+
ssize_t read_in_full(int fd, void *buf, size_t count);
ssize_t write_in_full(int fd, const void *buf, size_t count);
diff --git a/util/read-write.c b/util/read-write.c
index 44709dfd..bf6fb2fc 100644
--- a/util/read-write.c
+++ b/util/read-write.c
@@ -32,6 +32,27 @@ restart:
return nr;
}
+/*
+ * Read in the whole file while not exceeding max_size bytes of the buffer.
+ * Returns -1 (with errno set) in case of an error (ENOMEM if buffer was
+ * too small) or the filesize if the whole file could be read.
+ */
+ssize_t read_file(int fd, char *buf, size_t max_size)
+{
+ ssize_t ret;
+ char dummy;
+
+ errno = 0;
+ ret = read_in_full(fd, buf, max_size);
+
+ /* Probe whether we reached EOF. */
+ if (xread(fd, &dummy, 1) == 0)
+ return ret;
+
+ errno = ENOMEM;
+ return -1;
+}
+
ssize_t read_in_full(int fd, void *buf, size_t count)
{
ssize_t total = 0;