ldso: check e_machine of ELF binaries

Check if e_machine matches architecture the linker was build for.
This commit is contained in:
Sebastian Sumpf 2025-03-07 12:47:44 +01:00 committed by Norman Feske
parent f88a61a6a0
commit f9eea846fa
8 changed files with 45 additions and 3 deletions
repos/base/src/lib/ldso

@ -112,9 +112,13 @@ namespace Linker {
/**
* Legal values for e_machine (architecture)
*/
enum {
EM_NONE = 0, /* no machine */
EM_386 = 3, /* intel 80386 */
enum Em_machine {
EM_NONE = 0, /* no machine */
EM_386 = 3, /* x86_32 */
EM_ARM = 40, /* arm_v6/7 */
EM_X86_64 = 62, /* x86_64 */
EM_AARCH64 = 183, /* arm_v8 */
EM_RISCV = 243, /* riscv */
};
/**

@ -34,6 +34,11 @@ namespace Linker {
static inline bool is_rw(Elf::Phdr const &ph) {
return ((ph.p_flags & PF_MASK) == (PF_R | PF_W)); }
/**
* Returns machine linker is compiled for
*/
Elf::Half machine();
}
@ -154,6 +159,18 @@ struct Linker::Elf_file : File
start = 0;
}
char const * _machine(Elf::Half machine)
{
switch (machine) {
case EM_386: return "x86_32";
case EM_ARM: return "arm";
case EM_X86_64: return "x86_64";
case EM_AARCH64: return "aarch64";
case EM_RISCV: return "riscv";
default: return "unknown";
}
}
Elf_file(Env &env, Allocator &md_alloc, Name const &name, bool load)
:
env(env), rom_cap(_rom_dataspace(name)), loaded(load)
@ -193,6 +210,14 @@ struct Linker::Elf_file : File
return false;
}
/* check if machine matches linker's machine */
if (ehdr.e_machine != Linker::machine()) {
error("LD: incompatbile machine in ELF ('",
_machine(ehdr.e_machine), "'), expected '",
_machine(Linker::machine()), "'");
return false;
}
if (ehdr.e_ident[EI_CLASS] != ELFCLASS) {
error("LD: support for 32/64-bit objects only");
return false;

@ -75,6 +75,8 @@ Genode::Mutex &Linker::shared_object_mutex()
return _mutex;
}
Elf::Half Linker::machine() { return E_MACHINE; };
/**************************************************************
** ELF object types (shared object, dynamic binaries, ldso **

@ -18,6 +18,9 @@
#include <dynamic_generic.h>
namespace Linker {
static constexpr Elf::Half E_MACHINE = EM_ARM;
enum Reloc_types {
R_ABS32 = 2,
R_REL32 = 3,

@ -20,6 +20,8 @@
namespace Linker {
static constexpr Elf::Half E_MACHINE = EM_AARCH64;
/**
* Relocation types
*/

@ -18,6 +18,8 @@
namespace Linker {
static constexpr Elf::Half E_MACHINE = EM_RISCV;
inline unsigned long dynamic_address()
{
unsigned long addr;

@ -19,6 +19,8 @@
namespace Linker {
static constexpr Elf::Half E_MACHINE = EM_386;
enum Reloc_types {
R_32 = 1,
R_COPY = 5,

@ -19,6 +19,8 @@
namespace Linker {
static constexpr Elf::Half E_MACHINE = EM_X86_64;
/**
* Relocation types
*/