1// SPDX-License-Identifier: GPL-2.0
2#include <elf.h>
3#include <inttypes.h>
4#include <stdint.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8
9__attribute__((noreturn))
10static void die(const char *msg)
11{
12	fputs(msg, stderr);
13	exit(EXIT_FAILURE);
14}
15
16int main(int argc, const char *argv[])
17{
18	uint64_t entry;
19	size_t nread;
20	FILE *file;
21	union {
22		Elf32_Ehdr ehdr32;
23		Elf64_Ehdr ehdr64;
24	} hdr;
25
26	if (argc != 2)
27		die("Usage: elf-entry <elf-file>\n");
28
29	file = fopen(argv[1], "r");
30	if (!file) {
31		perror("Unable to open input file");
32		return EXIT_FAILURE;
33	}
34
35	nread = fread(&hdr, 1, sizeof(hdr), file);
36	if (nread != sizeof(hdr)) {
37		fclose(file);
38		perror("Unable to read input file");
39		return EXIT_FAILURE;
40	}
41
42	if (memcmp(hdr.ehdr32.e_ident, ELFMAG, SELFMAG)) {
43		fclose(file);
44		die("Input is not an ELF\n");
45	}
46
47	switch (hdr.ehdr32.e_ident[EI_CLASS]) {
48	case ELFCLASS32:
49		/* Sign extend to form a canonical address */
50		entry = (int64_t)(int32_t)hdr.ehdr32.e_entry;
51		break;
52
53	case ELFCLASS64:
54		entry = hdr.ehdr64.e_entry;
55		break;
56
57	default:
58		fclose(file);
59		die("Invalid ELF class\n");
60	}
61
62	fclose(file);
63	printf("0x%016" PRIx64 "\n", entry);
64
65	return EXIT_SUCCESS;
66}
67