diff mbox series

[v2,3/5] refactor load_image/load_image_size

Message ID 1542765966-20244-4-git-send-email-lizhijian@cn.fujitsu.com (mailing list archive)
State New, archived
Headers show
Series [v2,1/5] unify len and addr type for memory/address APIs | expand

Commit Message

Li Zhijian Nov. 21, 2018, 2:06 a.m. UTC
Don't expect read(2) can always read as many as it's told.

Signed-off-by: Li Zhijian <lizhijian@cn.fujitsu.com>
---
 hw/core/loader.c | 24 ++++++++++++++----------
 1 file changed, 14 insertions(+), 10 deletions(-)
diff mbox series

Patch

diff --git a/hw/core/loader.c b/hw/core/loader.c
index 0d53229..5f891e2 100644
--- a/hw/core/loader.c
+++ b/hw/core/loader.c
@@ -78,7 +78,7 @@  int64_t get_image_size(const char *filename)
 ssize_t load_image(const char *filename, uint8_t *addr)
 {
     int fd;
-    ssize_t size;
+    ssize_t size, r = 0, l = 0;
     fd = open(filename, O_RDONLY | O_BINARY);
     if (fd < 0)
         return -1;
@@ -91,11 +91,16 @@  ssize_t load_image(const char *filename, uint8_t *addr)
     }
 
     lseek(fd, 0, SEEK_SET);
-    if (read(fd, addr, size) != size) {
-        close(fd);
-        return -1;
+    while ((r = read(fd, addr + l, size - l)) > 0 ) {
+        l += r;
     }
     close(fd);
+
+    if (l != size) {
+        fprintf(stderr, "expect read %ld, actual read %ld\n", size, l);
+        return -1;
+    }
+
     return size;
 }
 
@@ -103,21 +108,20 @@  ssize_t load_image(const char *filename, uint8_t *addr)
 ssize_t load_image_size(const char *filename, void *addr, size_t size)
 {
     int fd;
-    ssize_t actsize;
+    ssize_t actsize, l = 0;
 
     fd = open(filename, O_RDONLY | O_BINARY);
     if (fd < 0) {
         return -1;
     }
 
-    actsize = read(fd, addr, size);
-    if (actsize < 0) {
-        close(fd);
-        return -1;
+    while ((actsize = read(fd, addr + l, size - l)) > 0) {
+        l += actsize;
     }
+
     close(fd);
 
-    return actsize;
+    return actsize < 0 ? -1 : l;
 }
 
 /* read()-like version */