0001
0002 #include <byteswap.h>
0003 #include <elf.h>
0004 #include <endian.h>
0005 #include <inttypes.h>
0006 #include <stdint.h>
0007 #include <stdio.h>
0008 #include <stdlib.h>
0009 #include <string.h>
0010
0011 #ifdef be32toh
0012
0013 #elif BYTE_ORDER == LITTLE_ENDIAN
0014 # define be32toh(x) bswap_32(x)
0015 # define le32toh(x) (x)
0016 # define be64toh(x) bswap_64(x)
0017 # define le64toh(x) (x)
0018 #elif BYTE_ORDER == BIG_ENDIAN
0019 # define be32toh(x) (x)
0020 # define le32toh(x) bswap_32(x)
0021 # define be64toh(x) (x)
0022 # define le64toh(x) bswap_64(x)
0023 #endif
0024
0025 __attribute__((noreturn))
0026 static void die(const char *msg)
0027 {
0028 fputs(msg, stderr);
0029 exit(EXIT_FAILURE);
0030 }
0031
0032 int main(int argc, const char *argv[])
0033 {
0034 uint64_t entry;
0035 size_t nread;
0036 FILE *file;
0037 union {
0038 Elf32_Ehdr ehdr32;
0039 Elf64_Ehdr ehdr64;
0040 } hdr;
0041
0042 if (argc != 2)
0043 die("Usage: elf-entry <elf-file>\n");
0044
0045 file = fopen(argv[1], "r");
0046 if (!file) {
0047 perror("Unable to open input file");
0048 return EXIT_FAILURE;
0049 }
0050
0051 nread = fread(&hdr, 1, sizeof(hdr), file);
0052 if (nread != sizeof(hdr)) {
0053 perror("Unable to read input file");
0054 fclose(file);
0055 return EXIT_FAILURE;
0056 }
0057
0058 if (memcmp(hdr.ehdr32.e_ident, ELFMAG, SELFMAG)) {
0059 fclose(file);
0060 die("Input is not an ELF\n");
0061 }
0062
0063 switch (hdr.ehdr32.e_ident[EI_CLASS]) {
0064 case ELFCLASS32:
0065 switch (hdr.ehdr32.e_ident[EI_DATA]) {
0066 case ELFDATA2LSB:
0067 entry = le32toh(hdr.ehdr32.e_entry);
0068 break;
0069 case ELFDATA2MSB:
0070 entry = be32toh(hdr.ehdr32.e_entry);
0071 break;
0072 default:
0073 fclose(file);
0074 die("Invalid ELF encoding\n");
0075 }
0076
0077
0078 entry = (int64_t)(int32_t)entry;
0079 break;
0080
0081 case ELFCLASS64:
0082 switch (hdr.ehdr32.e_ident[EI_DATA]) {
0083 case ELFDATA2LSB:
0084 entry = le64toh(hdr.ehdr64.e_entry);
0085 break;
0086 case ELFDATA2MSB:
0087 entry = be64toh(hdr.ehdr64.e_entry);
0088 break;
0089 default:
0090 fclose(file);
0091 die("Invalid ELF encoding\n");
0092 }
0093 break;
0094
0095 default:
0096 fclose(file);
0097 die("Invalid ELF class\n");
0098 }
0099
0100 printf("0x%016" PRIx64 "\n", entry);
0101 fclose(file);
0102 return EXIT_SUCCESS;
0103 }