1/* SPDX-License-Identifier: BSD-2-Clause */
2/*
3 * Copyright  2022  Beijing ESWIN Computing Technology Co., Ltd.
4 */
5
6#include <asm.S>
7#include <elf_common.h>
8
9/*
10 * _ldelf_start() - Entry of ldelf
11 *
12 * See include/ldelf.h for details on TEE Core interaction.
13 *
14 * void _ldelf_start(struct ldelf_arg *arg);
15 */
16FUNC _ldelf_start , :
17	/*
18	 * First ldelf needs to be relocated. The binary is compiled to
19	 * contain only a minimal number of R_RISCV_RELATIVE relocations in
20	 * read/write memory, leaving read-only and executable memory
21	 * untouched.
22	 */
23	lla	a1, reloc_end_rel
24	lw	a3, 0(a1)
25	lla	a1, reloc_begin_rel
26	lw	a2, 0(a1)
27	add	a2, a2, a1
28	add	a3, a3, a1
29	beq	a2, a3, 2f
30
31	lla	a1, _ldelf_start	/* Get the load offset */
32
33	/* Loop over the relocations (Elf64_Rela) and process all entries */
341:
35	ld	t1, 0(a2)	/* t1 = r_offset */
36	ld	t2, 8(a2)	/* t2 = r_info */
37	ld	t3, 16(a2)	/* t3 = r_addend */
38	addi	a2, a2, 24
39	and	t2, t2, 0xff
40	addi	t4, zero, R_RISCV_RELATIVE
41	bne	t2, t4, 3f
42
43	/* Update the pointer at r_offset + load offset */
44	add	t1, a1, t1
45	ld	t4, 0(t1)
46	add	t4, t4, t3
47	add	t4, t4, a1
48	sd	t4, 0(t1)
49	ble	a2, a3, 1b
502:
51	jal	ldelf
52	addi	a0, a0, 0
53	jal	_ldelf_return
543:
55	addi	a0, a0, 0
56	jal	_ldelf_panic
57reloc_begin_rel:
58    .word __reloc_begin - reloc_begin_rel
59reloc_end_rel:
60    .word __reloc_end - reloc_end_rel
61END_FUNC _ldelf_start
62