prelink-riscv.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright (C) 2017 Andes Technology
  3. * Chih-Mao Chen <cmchen@andestech.com>
  4. *
  5. * SPDX-License-Identifier: GPL-2.0+
  6. *
  7. * Statically process runtime relocations on RISC-V ELF images
  8. * so that it can be directly executed when loaded at LMA
  9. * without fixup. Both RV32 and RV64 are supported.
  10. */
  11. #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
  12. #error "Only little-endian host is supported"
  13. #endif
  14. #include <errno.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <elf.h>
  21. #include <fcntl.h>
  22. #include <sys/mman.h>
  23. #include <sys/stat.h>
  24. #include <sys/types.h>
  25. #include <unistd.h>
  26. #ifndef EM_RISCV
  27. #define EM_RISCV 243
  28. #endif
  29. #ifndef R_RISCV_32
  30. #define R_RISCV_32 1
  31. #endif
  32. #ifndef R_RISCV_64
  33. #define R_RISCV_64 2
  34. #endif
  35. #ifndef R_RISCV_RELATIVE
  36. #define R_RISCV_RELATIVE 3
  37. #endif
  38. const char *argv0;
  39. #define die(fmt, ...) \
  40. do { \
  41. fprintf(stderr, "%s: " fmt "\n", argv0, ## __VA_ARGS__); \
  42. exit(EXIT_FAILURE); \
  43. } while (0)
  44. #define PRELINK_INC_BITS 32
  45. #include "prelink-riscv.inc"
  46. #undef PRELINK_INC_BITS
  47. #define PRELINK_INC_BITS 64
  48. #include "prelink-riscv.inc"
  49. #undef PRELINK_INC_BITS
  50. int main(int argc, const char *const *argv)
  51. {
  52. argv0 = argv[0];
  53. if (argc < 2) {
  54. fprintf(stderr, "Usage: %s <u-boot>\n", argv0);
  55. exit(EXIT_FAILURE);
  56. }
  57. int fd = open(argv[1], O_RDWR, 0);
  58. if (fd < 0)
  59. die("Cannot open %s: %s", argv[1], strerror(errno));
  60. struct stat st;
  61. if (fstat(fd, &st) < 0)
  62. die("Cannot stat %s: %s", argv[1], strerror(errno));
  63. void *data =
  64. mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  65. if (data == MAP_FAILED)
  66. die("Cannot mmap %s: %s", argv[1], strerror(errno));
  67. close(fd);
  68. unsigned char *e_ident = (unsigned char *)data;
  69. if (memcmp(e_ident, ELFMAG, SELFMAG) != 0)
  70. die("Invalid ELF file %s", argv[1]);
  71. bool is64 = e_ident[EI_CLASS] == ELFCLASS64;
  72. if (is64)
  73. prelink64(data);
  74. else
  75. prelink32(data);
  76. return 0;
  77. }