Zheng Bao | f080cd5 | 2023-03-22 12:50:36 +0800 | [diff] [blame] | 1 | /* SPDX-License-Identifier: GPL-2.0-only */ |
| 2 | |
| 3 | #include <fcntl.h> |
| 4 | #include <errno.h> |
| 5 | #include <limits.h> |
| 6 | #include <stdio.h> |
| 7 | #include <sys/stat.h> |
| 8 | #include <unistd.h> |
| 9 | #include <string.h> |
| 10 | #include <stdlib.h> |
| 11 | |
| 12 | #include "amdfwtool.h" |
| 13 | |
| 14 | void write_or_fail(int fd, void *ptr, size_t size) |
| 15 | { |
| 16 | ssize_t written; |
| 17 | |
| 18 | written = write_from_buf_to_file(fd, ptr, size); |
| 19 | if (written < 0 || (size_t)written != size) { |
| 20 | fprintf(stderr, "%s: Error writing %zu bytes - written %zd bytes\n", |
| 21 | __func__, size, written); |
| 22 | exit(-1); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | ssize_t read_from_file_to_buf(int fd, void *buf, size_t buf_size) |
| 27 | { |
| 28 | ssize_t bytes; |
| 29 | size_t total_bytes = 0; |
| 30 | |
| 31 | do { |
| 32 | bytes = read(fd, buf + total_bytes, buf_size - total_bytes); |
| 33 | if (bytes == 0) { |
| 34 | fprintf(stderr, "Reached EOF probably\n"); |
| 35 | break; |
| 36 | } |
| 37 | |
| 38 | if (bytes < 0 && errno == EAGAIN) |
| 39 | bytes = 0; |
| 40 | |
| 41 | if (bytes < 0) { |
| 42 | fprintf(stderr, "Read failure %s\n", strerror(errno)); |
| 43 | return bytes; |
| 44 | } |
| 45 | |
| 46 | total_bytes += bytes; |
| 47 | } while (total_bytes < buf_size); |
| 48 | |
| 49 | if (total_bytes != buf_size) { |
| 50 | fprintf(stderr, "Read data size(%zu) != buffer size(%zu)\n", |
| 51 | total_bytes, buf_size); |
| 52 | return -1; |
| 53 | } |
| 54 | return buf_size; |
| 55 | } |
| 56 | |
| 57 | ssize_t write_from_buf_to_file(int fd, const void *buf, size_t buf_size) |
| 58 | { |
| 59 | ssize_t bytes; |
| 60 | size_t total_bytes = 0; |
| 61 | |
| 62 | do { |
| 63 | bytes = write(fd, buf + total_bytes, buf_size - total_bytes); |
| 64 | if (bytes < 0 && errno == EAGAIN) |
| 65 | bytes = 0; |
| 66 | |
| 67 | if (bytes < 0) { |
| 68 | fprintf(stderr, "Write failure %s\n", strerror(errno)); |
| 69 | lseek(fd, SEEK_CUR, -total_bytes); |
| 70 | return bytes; |
| 71 | } |
| 72 | |
| 73 | total_bytes += bytes; |
| 74 | } while (total_bytes < buf_size); |
| 75 | |
| 76 | if (total_bytes != buf_size) { |
| 77 | fprintf(stderr, "Wrote more data(%zu) than buffer size(%zu)\n", |
| 78 | total_bytes, buf_size); |
| 79 | lseek(fd, SEEK_CUR, -total_bytes); |
| 80 | return -1; |
| 81 | } |
| 82 | |
| 83 | return buf_size; |
| 84 | } |