blob: a900a1497ad35e81d6fa44aa17d401821abf80e4 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001// SPDX-License-Identifier: GPL-2.0+
Rick Chen42ac26f2017-12-26 13:55:56 +08002/*
3 * Copyright (C) 2017 Andes Technology
4 * Chih-Mao Chen <cmchen@andestech.com>
5 *
Rick Chen42ac26f2017-12-26 13:55:56 +08006 * 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
Rick Chen42ac26f2017-12-26 13:55:56 +080011#include <errno.h>
12#include <stdbool.h>
13#include <stdint.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17
18#include <elf.h>
19#include <fcntl.h>
20#include <sys/mman.h>
21#include <sys/stat.h>
22#include <sys/types.h>
23#include <unistd.h>
Marcus Comstedte6044102019-08-02 19:45:15 +020024#include <compiler.h>
Rick Chen42ac26f2017-12-26 13:55:56 +080025
26#ifndef EM_RISCV
27#define EM_RISCV 243
28#endif
29
30#ifndef R_RISCV_32
31#define R_RISCV_32 1
32#endif
33
34#ifndef R_RISCV_64
35#define R_RISCV_64 2
36#endif
37
38#ifndef R_RISCV_RELATIVE
39#define R_RISCV_RELATIVE 3
40#endif
41
42const char *argv0;
43
44#define die(fmt, ...) \
45 do { \
46 fprintf(stderr, "%s: " fmt "\n", argv0, ## __VA_ARGS__); \
47 exit(EXIT_FAILURE); \
48 } while (0)
49
50#define PRELINK_INC_BITS 32
51#include "prelink-riscv.inc"
52#undef PRELINK_INC_BITS
53
54#define PRELINK_INC_BITS 64
55#include "prelink-riscv.inc"
56#undef PRELINK_INC_BITS
57
58int main(int argc, const char *const *argv)
59{
60 argv0 = argv[0];
61
62 if (argc < 2) {
63 fprintf(stderr, "Usage: %s <u-boot>\n", argv0);
64 exit(EXIT_FAILURE);
65 }
66
67 int fd = open(argv[1], O_RDWR, 0);
68
69 if (fd < 0)
70 die("Cannot open %s: %s", argv[1], strerror(errno));
71
72 struct stat st;
73
74 if (fstat(fd, &st) < 0)
75 die("Cannot stat %s: %s", argv[1], strerror(errno));
76
77 void *data =
78 mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
79
80 if (data == MAP_FAILED)
81 die("Cannot mmap %s: %s", argv[1], strerror(errno));
82
83 close(fd);
84
85 unsigned char *e_ident = (unsigned char *)data;
86
87 if (memcmp(e_ident, ELFMAG, SELFMAG) != 0)
88 die("Invalid ELF file %s", argv[1]);
89
90 bool is64 = e_ident[EI_CLASS] == ELFCLASS64;
91
92 if (is64)
93 prelink64(data);
94 else
95 prelink32(data);
96
97 return 0;
98}