elf-entry.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <byteswap.h>
  3. #include <elf.h>
  4. #include <endian.h>
  5. #include <inttypes.h>
  6. #include <stdint.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #ifdef be32toh
  11. /* If libc provides [bl]e{32,64}toh() then we'll use them */
  12. #elif BYTE_ORDER == LITTLE_ENDIAN
  13. # define be32toh(x) bswap_32(x)
  14. # define le32toh(x) (x)
  15. # define be64toh(x) bswap_64(x)
  16. # define le64toh(x) (x)
  17. #elif BYTE_ORDER == BIG_ENDIAN
  18. # define be32toh(x) (x)
  19. # define le32toh(x) bswap_32(x)
  20. # define be64toh(x) (x)
  21. # define le64toh(x) bswap_64(x)
  22. #endif
  23. __attribute__((noreturn))
  24. static void die(const char *msg)
  25. {
  26. fputs(msg, stderr);
  27. exit(EXIT_FAILURE);
  28. }
  29. int main(int argc, const char *argv[])
  30. {
  31. uint64_t entry;
  32. size_t nread;
  33. FILE *file;
  34. union {
  35. Elf32_Ehdr ehdr32;
  36. Elf64_Ehdr ehdr64;
  37. } hdr;
  38. if (argc != 2)
  39. die("Usage: elf-entry <elf-file>\n");
  40. file = fopen(argv[1], "r");
  41. if (!file) {
  42. perror("Unable to open input file");
  43. return EXIT_FAILURE;
  44. }
  45. nread = fread(&hdr, 1, sizeof(hdr), file);
  46. if (nread != sizeof(hdr)) {
  47. perror("Unable to read input file");
  48. return EXIT_FAILURE;
  49. }
  50. if (memcmp(hdr.ehdr32.e_ident, ELFMAG, SELFMAG))
  51. die("Input is not an ELF\n");
  52. switch (hdr.ehdr32.e_ident[EI_CLASS]) {
  53. case ELFCLASS32:
  54. switch (hdr.ehdr32.e_ident[EI_DATA]) {
  55. case ELFDATA2LSB:
  56. entry = le32toh(hdr.ehdr32.e_entry);
  57. break;
  58. case ELFDATA2MSB:
  59. entry = be32toh(hdr.ehdr32.e_entry);
  60. break;
  61. default:
  62. die("Invalid ELF encoding\n");
  63. }
  64. /* Sign extend to form a canonical address */
  65. entry = (int64_t)(int32_t)entry;
  66. break;
  67. case ELFCLASS64:
  68. switch (hdr.ehdr32.e_ident[EI_DATA]) {
  69. case ELFDATA2LSB:
  70. entry = le64toh(hdr.ehdr64.e_entry);
  71. break;
  72. case ELFDATA2MSB:
  73. entry = be64toh(hdr.ehdr64.e_entry);
  74. break;
  75. default:
  76. die("Invalid ELF encoding\n");
  77. }
  78. break;
  79. default:
  80. die("Invalid ELF class\n");
  81. }
  82. printf("0x%016" PRIx64 "\n", entry);
  83. return EXIT_SUCCESS;
  84. }