elf-entry.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. fclose(file);
  49. return EXIT_FAILURE;
  50. }
  51. if (memcmp(hdr.ehdr32.e_ident, ELFMAG, SELFMAG)) {
  52. fclose(file);
  53. die("Input is not an ELF\n");
  54. }
  55. switch (hdr.ehdr32.e_ident[EI_CLASS]) {
  56. case ELFCLASS32:
  57. switch (hdr.ehdr32.e_ident[EI_DATA]) {
  58. case ELFDATA2LSB:
  59. entry = le32toh(hdr.ehdr32.e_entry);
  60. break;
  61. case ELFDATA2MSB:
  62. entry = be32toh(hdr.ehdr32.e_entry);
  63. break;
  64. default:
  65. fclose(file);
  66. die("Invalid ELF encoding\n");
  67. }
  68. /* Sign extend to form a canonical address */
  69. entry = (int64_t)(int32_t)entry;
  70. break;
  71. case ELFCLASS64:
  72. switch (hdr.ehdr32.e_ident[EI_DATA]) {
  73. case ELFDATA2LSB:
  74. entry = le64toh(hdr.ehdr64.e_entry);
  75. break;
  76. case ELFDATA2MSB:
  77. entry = be64toh(hdr.ehdr64.e_entry);
  78. break;
  79. default:
  80. fclose(file);
  81. die("Invalid ELF encoding\n");
  82. }
  83. break;
  84. default:
  85. fclose(file);
  86. die("Invalid ELF class\n");
  87. }
  88. printf("0x%016" PRIx64 "\n", entry);
  89. fclose(file);
  90. return EXIT_SUCCESS;
  91. }