1 // SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause 2 /* reloc_riscv.c - position independent ELF shared object relocator 3 Copyright (C) 2018 Alexander Graf <agraf@suse.de> 4 Copyright (C) 2014 Linaro Ltd. <ard.biesheuvel@linaro.org> 5 Copyright (C) 1999 Hewlett-Packard Co. 6 Contributed by David Mosberger <davidm@hpl.hp.com>. 7 8 All rights reserved. 9 10 Redistribution and use in source and binary forms, with or without 11 modification, are permitted provided that the following conditions 12 are met: 13 14 * Redistributions of source code must retain the above copyright 15 notice, this list of conditions and the following disclaimer. 16 * Redistributions in binary form must reproduce the above 17 copyright notice, this list of conditions and the following 18 disclaimer in the documentation and/or other materials 19 provided with the distribution. 20 * Neither the name of Hewlett-Packard Co. nor the names of its 21 contributors may be used to endorse or promote products derived 22 from this software without specific prior written permission. 23 24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 25 CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 26 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 27 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 29 BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 30 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 31 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 32 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 33 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 34 TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 35 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 36 SUCH DAMAGE. 37 */ 38 39 #include <efi.h> 40 41 #include <elf.h> 42 43 #define Elf_Dyn Elf64_Dyn 44 #define Elf_Rela Elf64_Rela 45 #define ELF_R_TYPE ELF64_R_TYPE 46 47 EFI_STATUS EFIAPI _relocate(long ldbase, Elf_Dyn *dyn) 48 { 49 long relsz = 0, relent = 0; 50 Elf_Rela *rel = NULL; 51 unsigned long *addr; 52 int i; 53 54 for (i = 0; dyn[i].d_tag != DT_NULL; ++i) { 55 switch (dyn[i].d_tag) { 56 case DT_RELA: 57 rel = (Elf_Rela *)((unsigned long)dyn[i].d_un.d_ptr + ldbase); 58 break; 59 case DT_RELASZ: 60 relsz = dyn[i].d_un.d_val; 61 break; 62 case DT_RELAENT: 63 relent = dyn[i].d_un.d_val; 64 break; 65 default: 66 break; 67 } 68 } 69 70 if (!rel && relent == 0) 71 return EFI_SUCCESS; 72 73 if (!rel || relent == 0) 74 return EFI_LOAD_ERROR; 75 76 while (relsz > 0) { 77 /* apply the relocs */ 78 switch (ELF_R_TYPE(rel->r_info)) { 79 case R_RISCV_RELATIVE: 80 addr = (unsigned long *)(ldbase + rel->r_offset); 81 *addr = ldbase + rel->r_addend; 82 break; 83 default: 84 break; 85 } 86 rel = (Elf_Rela *)((char *)rel + relent); 87 relsz -= relent; 88 } 89 return EFI_SUCCESS; 90 } 91