[PATCH v2 06/21] riscv: implement elf_apply_relocations() for ELF relocation support

Ahmad Fatoum a.fatoum at pengutronix.de
Tue Jan 6 05:11:29 PST 2026



On 1/6/26 1:53 PM, Sascha Hauer wrote:
> Add architecture-specific ELF relocation support for RISC-V,
> enabling dynamic relocation of position-independent ELF binaries.
> The implemetation reuses the existing relocate_image().
> 
> 🤖 Generated with [Claude Code](https://claude.com/claude-code)
> 
> Co-Authored-By: Claude Sonnet 4.5 <noreply at anthropic.com>
> Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>

With below point addressed:

Reviewed-by: Ahmad Fatoum <a.fatoum at pengutronix.de>

> ---
>  arch/riscv/lib/reloc.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 55 insertions(+)
> 
> diff --git a/arch/riscv/lib/reloc.c b/arch/riscv/lib/reloc.c
> index 18b13a7013cff4032c12b999470f265dbda13c51..9a5004cf5b762b39bb98f7f0ab112c204185b33a 100644
> --- a/arch/riscv/lib/reloc.c
> +++ b/arch/riscv/lib/reloc.c
> @@ -75,3 +75,58 @@ void relocate_to_current_adr(void)
>  
>  	sync_caches_for_execution();
>  }
> +
> +#if __riscv_xlen == 64
> +
> +/*
> + * Apply RISC-V 64-bit ELF relocations
> + */
> +int elf_apply_relocations(struct elf_image *elf, const void *dyn_seg)
> +{
> +	Elf64_Rela *rela;

If you drop this and use only rel_ptr, this can be made a single
function for both platforms.

Cheers,
Ahmad

> +	void *rel_ptr;
> +	u64 relasz;
> +	phys_addr_t base = (phys_addr_t)elf->reloc_offset;
> +	int ret;
> +
> +	ret = elf_parse_dynamic_section_rela(elf, dyn_seg, &rel_ptr, &relasz);
> +	if (ret)
> +		return ret;
> +
> +	rela = (Elf64_Rela *)rel_ptr;
> +
> +	relocate_image(base, rela, (void *)rela + relasz, NULL, NULL);
> +
> +	return 0;
> +}
> +
> +#else /* 32-bit RISC-V */
> +
> +/*
> + * Apply RISC-V 32-bit ELF relocations
> + */
> +int elf_apply_relocations(struct elf_image *elf, const void *dyn_seg)
> +{
> +	Elf32_Rela *rela;
> +	void *rel_ptr;
> +	u64 relasz;
> +	phys_addr_t base = (phys_addr_t)elf->reloc_offset;
> +	int ret;
> +
> +	if (elf->class != ELFCLASS32) {
> +		pr_err("Wrong ELF class for RISC-V 32 relocation\n");
> +		return -EINVAL;
> +	}
> +
> +	ret = elf_parse_dynamic_section_rela(elf, dyn_seg, &rel_ptr, &relasz);
> +	if (ret)
> +		return ret;
> +
> +	rela = (Elf32_Rela *)rel_ptr;
> +
> +	relocate_image(base, rela, (void *)rela + relasz, NULL, NULL);
> +
> +	return 0;
> +}
> +
> +#endif
> 

-- 
Pengutronix e.K.                  |                             |
Steuerwalder Str. 21              | http://www.pengutronix.de/  |
31137 Hildesheim, Germany         | Phone: +49-5121-206917-0    |
Amtsgericht Hildesheim, HRA 2686  | Fax:   +49-5121-206917-5555 |




More information about the barebox mailing list