doimage.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (c) 2019, Remi Pommarel <repk@triplefau.lt>
  3. *
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #include <stdint.h>
  11. #include <endian.h>
  12. #define DEFAULT_PROGNAME "doimage"
  13. #define PROGNAME(argc, argv) (((argc) >= 1) ? ((argv)[0]) : DEFAULT_PROGNAME)
  14. #define BL31_MAGIC 0x12348765
  15. #define BL31_LOADADDR 0x05100000
  16. #define BUFLEN 512
  17. static inline void usage(char const *prog)
  18. {
  19. fprintf(stderr, "Usage: %s <bl31.bin> <bl31.img>\n", prog);
  20. }
  21. static inline int fdwrite(int fd, uint8_t *data, size_t len)
  22. {
  23. ssize_t nr;
  24. size_t l;
  25. int ret = -1;
  26. for (l = 0; l < len; l += nr) {
  27. nr = write(fd, data + l, len - l);
  28. if (nr < 0) {
  29. perror("Cannot write to bl31.img");
  30. goto out;
  31. }
  32. }
  33. ret = 0;
  34. out:
  35. return ret;
  36. }
  37. int main(int argc, char **argv)
  38. {
  39. int fin, fout, ret = -1;
  40. ssize_t len;
  41. uint32_t data;
  42. uint8_t buf[BUFLEN];
  43. if (argc != 3) {
  44. usage(PROGNAME(argc, argv));
  45. goto out;
  46. }
  47. fin = open(argv[1], O_RDONLY);
  48. if (fin < 0) {
  49. perror("Cannot open bl31.bin");
  50. goto out;
  51. }
  52. fout = open(argv[2], O_WRONLY | O_CREAT, 0660);
  53. if (fout < 0) {
  54. perror("Cannot open bl31.img");
  55. goto closefin;
  56. }
  57. data = htole32(BL31_MAGIC);
  58. if (fdwrite(fout, (uint8_t *)&data, sizeof(data)) < 0)
  59. goto closefout;
  60. lseek(fout, 8, SEEK_SET);
  61. data = htole32(BL31_LOADADDR);
  62. if (fdwrite(fout, (uint8_t *)&data, sizeof(data)) < 0)
  63. goto closefout;
  64. lseek(fout, 0x200, SEEK_SET);
  65. while ((len = read(fin, buf, sizeof(buf))) > 0)
  66. if (fdwrite(fout, buf, len) < 0)
  67. goto closefout;
  68. if (len < 0) {
  69. perror("Cannot read bl31.bin");
  70. goto closefout;
  71. }
  72. ret = 0;
  73. closefout:
  74. close(fout);
  75. closefin:
  76. close(fin);
  77. out:
  78. return ret;
  79. }