prelink-riscv.c 1.9 KB

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