-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathelf.c
116 lines (100 loc) · 2.5 KB
/
elf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include <stddef.h>
#include <stdint.h>
#include "addrs.h"
#include "elf.h"
#include "util.h"
typedef struct {
uint8_t e_ident[16];
uint16_t e_type;
uint16_t e_machine;
uint32_t e_version;
uint32_t e_entry;
uint32_t e_phoff;
uint32_t e_shoff;
uint32_t e_flags;
uint16_t e_ehsize;
uint16_t e_phentsize;
uint16_t e_ph_num;
uint16_t e_shentsize;
uint16_t e_sh_num;
uint16_t e_shstrndx;
} Elf32_Ehdr;
typedef struct {
uint8_t e_ident[16];
uint16_t e_type;
uint16_t e_machine;
uint32_t e_version;
uint64_t e_entry;
uint64_t e_phoff;
uint64_t e_shoff;
uint32_t e_flags;
uint16_t e_ehsize;
uint16_t e_phentsize;
uint16_t e_ph_num;
uint16_t e_shentsize;
uint16_t e_sh_num;
uint16_t e_shstrndx;
} Elf64_Ehdr;
typedef struct
{
uint32_t p_type;
uint32_t p_offset;
uint32_t p_vaddr;
uint32_t p_paddr;
uint32_t p_filesz;
uint32_t p_memsz;
uint32_t p_flags;
uint32_t p_align;
} Elf32_Phdr;
typedef struct {
uint32_t p_type;
uint32_t p_flags;
uint64_t p_offset;
uint64_t p_vaddr;
uint64_t p_paddr;
uint64_t p_filesz;
uint64_t p_memsz;
uint64_t p_align;
} Elf64_Phdr;
#if __riscv_xlen == 64
# define Elf_Ehdr Elf64_Ehdr
# define Elf_Phdr Elf64_Phdr
#else
# define Elf_Ehdr Elf32_Ehdr
# define Elf_Phdr Elf32_Phdr
#endif
#define PT_LOAD 1
#define SHT_RELA 4
#define SHF_ALLOC 2
static int check_elf(const void *data) {
// Check alignment
if ((size_t)data & 3)
return 0;
// Check magic number
const Elf_Ehdr *eh = data;
if (!(eh->e_ident[0] == '\177' && eh->e_ident[1] == 'E' &&
eh->e_ident[2] == 'L' && eh->e_ident[3] == 'F')) {
return 0;
}
return 1;
}
size_t program_flash_with_elf(const void *data, size_t flash_offset) {
if (!check_elf(data))
return 0;
const Elf_Ehdr *eh = data;
int ph_num = eh->e_ph_num;
const Elf_Phdr *ph = data + eh->e_phoff;
for (int i = 0; i < ph_num; i++) {
if (ph[i].p_type != PT_LOAD || ph[i].p_memsz == 0)
continue;
if (!is_flash(ph[i].p_paddr))
continue;
// Load data into simulated Flash segment
size_t paddr = ph[i].p_paddr + flash_offset;
memcpy((void*)paddr, data + ph[i].p_offset, ph[i].p_filesz);
}
return eh->e_entry + flash_offset;
}