utils.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <errno.h>
  6. #include "utils.h"
  7. ssize_t read_from_buffer(char *fname, int fd, char *buffer, uint64_t size, uint64_t base) {
  8. ssize_t rc;
  9. char *buf = buffer;
  10. off_t offset = base;
  11. size_t count = 0;
  12. int loop = 0;
  13. while (count < size) {
  14. uint64_t bytes = size - count;
  15. if (bytes > RW_MAX_SIZE) {
  16. bytes = RW_MAX_SIZE;
  17. }
  18. if (offset) {
  19. rc = lseek(fd, offset, SEEK_SET);
  20. if (rc != offset) {
  21. fprintf(stderr, "%s, seek off 0x%lx != 0x%lx\n", fname, rc, offset);
  22. perror("seek file");
  23. return -EIO;
  24. }
  25. }
  26. /* Read data from file into buffer */
  27. rc = read(fd, buf, bytes);
  28. if (rc < 0) {
  29. fprintf(stderr, "%s, read failed\n", fname);
  30. perror("read file");
  31. return -EIO;
  32. }
  33. count += rc;
  34. if (rc != bytes) {
  35. fprintf(stderr, "%s, read failed, rc=%ld, bytes=%ld\n", fname, rc, bytes);
  36. break;
  37. }
  38. buf += bytes;
  39. offset += bytes;
  40. loop++;
  41. }
  42. if (count != size && loop) {
  43. fprintf(stderr, "%s, read failed, count=%ld, size=%ld\n", fname, count, size);
  44. return -EIO;
  45. }
  46. return count;
  47. }
  48. ssize_t write_to_buffer(char *fname, int fd, char *buffer, uint64_t size, uint64_t base) {
  49. ssize_t rc;
  50. char *buf = buffer;
  51. off_t offset = base;
  52. size_t count = 0;
  53. int loop = 0;
  54. while (count < size) {
  55. uint64_t bytes = size - count;
  56. if (bytes > RW_MAX_SIZE) {
  57. bytes = RW_MAX_SIZE;
  58. }
  59. if (offset) {
  60. rc = lseek(fd, offset, SEEK_SET);
  61. if (rc != offset) {
  62. fprintf(stderr, "%s, seek off 0x%lx != 0x%lx\n", fname, rc, offset);
  63. perror("seek file");
  64. return -EIO;
  65. }
  66. }
  67. /* Write data from buffer into file */
  68. rc = write(fd, buf, bytes);
  69. if (rc < 0) {
  70. fprintf(stderr, "%s,write 0x%lx @ 0x%lx @ 0x%lx failed %ld.\n", fname, bytes, offset, rc);
  71. perror("write file");
  72. return -EIO;
  73. }
  74. count += rc;
  75. printf("count = %ld, bytes = %ld\n", count, size);
  76. if (rc != bytes) {
  77. fprintf(stderr, "%s, write underflow 0x%lx/0x%lx @ 0x%lx.\n", fname, rc, bytes, offset);
  78. break;
  79. }
  80. buf += bytes;
  81. offset += bytes;
  82. loop++;
  83. }
  84. if (count != size && loop) {
  85. fprintf(stderr, "%s, write underflow, 0x%lx/0x%lx.\n", fname, count, size);
  86. return -EIO;
  87. }
  88. return count;
  89. }