From 584458181c463950c55e367f0ea325ba57497db9 Mon Sep 17 00:00:00 2001 From: Giuliano Belinassi Date: Sat, 26 Oct 2024 19:19:34 -0300 Subject: [PATCH 1/4] Add small ELF parser This small ELF parser contains just the bare minimum functions so we can load ELF sections without the use of any external library. This module also doesn't allocate dynamic memory. Signed-off-by: Giuliano Belinassi --- include/Makefile.am | 3 +- include/minielf.h | 69 ++++++++++++ lib/Makefile.am | 3 +- lib/minielf.c | 248 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 321 insertions(+), 2 deletions(-) create mode 100644 include/minielf.h create mode 100644 lib/minielf.c diff --git a/include/Makefile.am b/include/Makefile.am index 98a1dcb3..c9204f29 100644 --- a/include/Makefile.am +++ b/include/Makefile.am @@ -27,7 +27,8 @@ noinst_HEADERS = \ terminal_colors.h \ ld_rtld.h \ insn_queue.h \ - insn_queue_lib.h + insn_queue_lib.h \ + minielf.h # Workaround a bug in Autoconf 2.69 if CPU_X86_64 diff --git a/include/minielf.h b/include/minielf.h new file mode 100644 index 00000000..37875add --- /dev/null +++ b/include/minielf.h @@ -0,0 +1,69 @@ +/* + * libpulp - User-space Livepatching Library + * + * Copyright (C) 2024 SUSE Software Solutions GmbH + * + * This file is part of libpulp. + * + * libpulp is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libpulp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with libpulp. If not, see . + */ + +/* Small parser for elf, not depending on larger libraries such as libelf + * and with very small memory footprint. No allocation on the heap is done + * in this library. + */ + +#include + +/** Maximum size of the Section String Table. */ +#define STRTBL_SIZE_MAX 0x500 + +/** Typedefs so we can adjust according to architecture. */ +typedef Elf64_Ehdr Elf_Ehdr; +typedef Elf64_Shdr Elf_Shdr; +typedef Elf64_Half Elf_Half; +typedef Elf64_Off Elf_Off; + +/** Read the Elf File Header. */ +Elf_Ehdr *Elf_Parse_Ehdr(Elf_Ehdr *ehdr, int fd); + +/** Get an ELF section by its name. + * + * OBS: use `readelf -S ` to show section names. + */ +Elf_Shdr *Elf_Get_Shdr_By_Name(Elf_Shdr *shdr, const char *name, int fd, + const Elf_Ehdr *ehdr, const char strtbl[]); + + +/** Get an ELF section by its index. + * + * OBS: use `readelf -S ` to show section index []. + */ +Elf_Shdr *Elf_Get_Shdr(Elf_Shdr *shdr, Elf_Half index, + int fd, const Elf_Ehdr *ehdr); + +/** Get the section string table. */ +long Elf_Load_Strtbl(char strtbl[STRTBL_SIZE_MAX], const Elf_Ehdr *ehdr, int fd); + +/** Load Section into `dest` buffer. */ +long Elf_Load_Section(unsigned dest_size, unsigned char *dest, + const Elf_Shdr *shdr, int fd); + +/** ----- ELF functions related to ULP ----- . */ + +/** Get the .ulp section from the given ELF file. */ +int Get_ULP_Section(unsigned dest_size, unsigned char *dest, const char *file); + +/** Get the .ulp.rev section from the given ELF file. */ +int Get_ULP_REV_Section(unsigned dest_size, unsigned char *dest, const char *file); diff --git a/lib/Makefile.am b/lib/Makefile.am index 77b64c7c..38719c17 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -24,7 +24,8 @@ libpulp_la_SOURCES = \ interpose.c \ msg_queue.c \ insn_queue.c \ - error.c + error.c \ + minielf.c libpulp_la_LDFLAGS = \ -ldl \ diff --git a/lib/minielf.c b/lib/minielf.c new file mode 100644 index 00000000..cec4fc46 --- /dev/null +++ b/lib/minielf.c @@ -0,0 +1,248 @@ +/* + * libpulp - User-space Livepatching Library + * + * Copyright (C) 2024 SUSE Software Solutions GmbH + * + * This file is part of libpulp. + * + * libpulp is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libpulp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with libpulp. If not, see . + */ + +/* Small parser for elf, not depending on larger libraries such as libelf + * and with very small memory footprint. No allocation on the heap is done + * in this library. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "error.h" +#include "minielf.h" +#include "ulp_common.h" + +#define debug(...) DEBUG(__VA_ARGS__) +#define warn(...) WARN(__VA_ARGS__) + +/** Ban memory allocation functions. This module should never allocate memory + in the heap. */ +#pragma GCC poison malloc calloc free + +/** Read the Elf File Header. */ +Elf_Ehdr *Elf_Parse_Ehdr(Elf_Ehdr *ehdr, int fd) +{ + /* Go to begining of file. */ + lseek(fd, 0L, SEEK_SET); + + ssize_t n = read(fd, ehdr, sizeof(Elf_Ehdr)); + + if (n != sizeof(Elf_Ehdr)) { + warn("Invalid ELF file: invalid size"); + return NULL; + } + + /* Check if the header makes sense. */ + if (memcmp(&ehdr->e_ident, ELFMAG, SELFMAG) != 0) { + warn("Invalid ELF file: invalid magic number"); + return NULL; + } + + return ehdr; +} + +/** Get an ELF section by its name. + * + * OBS: use `readelf -S ` to show section names. + */ +Elf_Shdr *Elf_Get_Shdr_By_Name(Elf_Shdr *shdr, const char *name, int fd, + const Elf_Ehdr *ehdr, const char strtbl[]) +{ + /* Make sure it will fit the buffer. */ + libpulp_assert(ehdr->e_shentsize == sizeof(Elf_Shdr)); + + /* Go to offset. */ + lseek(fd, ehdr->e_shoff, SEEK_SET); + + for (Elf_Half i = 0; i < ehdr->e_shnum; i++) { + /* Load the header. */ + ssize_t n = read(fd, shdr, ehdr->e_shentsize); + + if (n != ehdr->e_shentsize) { + warn("Invalid ELF file: invalid size\n"); + return NULL; + } + + /* Check if name matches. */ + if (strcmp(name, &strtbl[shdr->sh_name]) == 0) { + return shdr; + } + } + + return NULL; +} + +/** Get an ELF section by its index. + * + * OBS: use `readelf -S ` to show section index []. + */ +Elf_Shdr *Elf_Get_Shdr(Elf_Shdr *shdr, Elf_Half index, + int fd, const Elf_Ehdr *ehdr) +{ + /* Make sure it will fit the buffer. */ + libpulp_assert(ehdr->e_shentsize == sizeof(Elf_Shdr)); + + /* Go to offset. */ + lseek(fd, ehdr->e_shoff, SEEK_SET); + + for (Elf_Half i = 0; i < ehdr->e_shnum; i++) { + /* Load the header. */ + ssize_t n = read(fd, shdr, ehdr->e_shentsize); + + if (n != ehdr->e_shentsize) { + warn("Invalid ELF file: invalid size"); + return NULL; + } + + /* Check if index matches. */ + if (index == i) { + return shdr; + } + } + + return NULL; +} + +/** Get the section string table. */ +long Elf_Load_Strtbl(char strtbl[STRTBL_SIZE_MAX], const Elf_Ehdr *ehdr, int fd) +{ + /* Make sure it will fit the buffer. */ + libpulp_assert(ehdr->e_shentsize == sizeof(Elf_Shdr)); + + /* Declare a section for us to store and iterate. */ + Elf_Shdr shdr; + Elf_Shdr *p_shdr = Elf_Get_Shdr(&shdr, ehdr->e_shstrndx, fd, ehdr); + + /* Make sure we are in the correct section. */ + if (p_shdr == NULL) { + warn("Invalid ELF file: no section string table"); + return 0L; + } + + if (shdr.sh_size > STRTBL_SIZE_MAX) { + warn("Unable to load section string table: size larger than buffer"); + return 0L; + } + + /* Go to offset. */ + lseek(fd, shdr.sh_offset, SEEK_SET); + + /* Load the strtbl. */ + ssize_t n = read(fd, strtbl, shdr.sh_size); + + if ((size_t)n != shdr.sh_size) { + warn("Unable to load section string table: file size mismatch.\n"); + return 0L; + } + + return shdr.sh_size; +} + +/** Load Section into `dest` buffer. */ +long Elf_Load_Section(unsigned dest_size, unsigned char *dest, + const Elf_Shdr *shdr, int fd) +{ + /* Check if dest can hold the section. */ + if (shdr->sh_size > dest_size) { + warn("Unable to load section: buffer too small"); + return 0L; + } + + /* Go to offset. */ + lseek(fd, shdr->sh_offset, SEEK_SET); + + /* Load the section. */ + ssize_t n = read(fd, dest, shdr->sh_size); + + if ((size_t)n != shdr->sh_size) { + warn("Unable to load section string table: read size mismatch"); + return 0L; + } + + return shdr->sh_size; +} + +/** Load the .ulp section of livepatch of `file` into the buffer. */ +static int +Get_Elf_Section(unsigned dest_size, unsigned char *dest, + const char *section_name, const char *file) +{ + /* Open ELF file. */ + int elf_fd = open(file, O_RDONLY); + if (elf_fd < 0) { + warn("Unable to open file %s: %s", file, strerror(errno)); + return ENOENT; + } + + /* Load ELF file header. */ + Elf_Ehdr ehdr; + Elf_Ehdr *p_ehdr = Elf_Parse_Ehdr(&ehdr, elf_fd); + if (p_ehdr == NULL) { + warn("File is not an ELF object."); + + close(elf_fd); + return EINVAL; + } + + /* Load ELF section string table. */ + char strtbl[STRTBL_SIZE_MAX]; + Elf_Load_Strtbl(strtbl, &ehdr, elf_fd); + + /* Load section header from the ELF file. */ + Elf_Shdr ulp_shdr; + Elf_Shdr *p_ulp_shdr = Elf_Get_Shdr_By_Name(&ulp_shdr, section_name, + elf_fd, &ehdr, strtbl); + + if (p_ulp_shdr == NULL) { + warn("Section %s not found.", section_name); + + close(elf_fd); + return EINVAL; + } + + /* Load ELF section into dest. */ + long x = Elf_Load_Section(dest_size, dest, &ulp_shdr, elf_fd); + if (x == 0) { + close(elf_fd); + return EINVAL; + } + + close(elf_fd); + return 0; +} + +int +Get_ULP_Section(unsigned dest_size, unsigned char *dest, const char *file) +{ + return Get_Elf_Section(dest_size, dest, ".ulp", file); +} + +int +Get_ULP_REV_Section(unsigned dest_size, unsigned char *dest, const char *file) +{ + return Get_Elf_Section(dest_size, dest, ".ulp.rev", file); +} From 92477409498f1ce4a8c469765910388a1925a726 Mon Sep 17 00:00:00 2001 From: Giuliano Belinassi Date: Sat, 26 Oct 2024 21:41:36 -0300 Subject: [PATCH 2/4] Add small gdb interface Livepatch load works but it doesn't modify the addresses because there is nothing to interpret the insn_queue. Signed-off-by: Giuliano Belinassi --- include/minielf.h | 4 +- lib/Makefile.am | 3 +- lib/gdb_interface.c | 131 ++++++++++++++++++++++++++++++++++++++++++ lib/minielf.c | 20 +++---- tools/introspection.c | 3 + 5 files changed, 148 insertions(+), 13 deletions(-) create mode 100644 lib/gdb_interface.c diff --git a/include/minielf.h b/include/minielf.h index 37875add..e4efdc91 100644 --- a/include/minielf.h +++ b/include/minielf.h @@ -63,7 +63,7 @@ long Elf_Load_Section(unsigned dest_size, unsigned char *dest, /** ----- ELF functions related to ULP ----- . */ /** Get the .ulp section from the given ELF file. */ -int Get_ULP_Section(unsigned dest_size, unsigned char *dest, const char *file); +long Get_ULP_Section(unsigned dest_size, unsigned char *dest, const char *file); /** Get the .ulp.rev section from the given ELF file. */ -int Get_ULP_REV_Section(unsigned dest_size, unsigned char *dest, const char *file); +long Get_ULP_REV_Section(unsigned dest_size, unsigned char *dest, const char *file); diff --git a/lib/Makefile.am b/lib/Makefile.am index 38719c17..58855107 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -25,7 +25,8 @@ libpulp_la_SOURCES = \ msg_queue.c \ insn_queue.c \ error.c \ - minielf.c + minielf.c \ + gdb_interface.c libpulp_la_LDFLAGS = \ -ldl \ diff --git a/lib/gdb_interface.c b/lib/gdb_interface.c new file mode 100644 index 00000000..e1fc0789 --- /dev/null +++ b/lib/gdb_interface.c @@ -0,0 +1,131 @@ +/* + * libpulp - User-space Livepatching Library + * + * Copyright (C) 2024 SUSE Software Solutions GmbH + * + * This file is part of libpulp. + * + * libpulp is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libpulp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with libpulp. If not, see . + */ + +/* Small interface that allows livepatches to be applied or reverted + * within gdb. */ + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#include +#include +#include + +#include "config.h" +#include "ulp_common.h" +#include "ulp.h" +#include "minielf.h" +#include "error_common.h" + +extern char __ulp_metadata_buffer[ULP_METADATA_BUF_LEN]; + +int +inject_lp_path(const char *path, long metadata_size) +{ + /* FIXME: This is absurdly awkward. */ + + /* Copy the final metadata into final_meta buffer. Things works here as + * follows: + * + * 1. Copy the first 1 + 32 bytes containing the patch type and patch id. + * 2. Copy the size of the path to the livepatch container file. + * 3. Copy the path to the livepatch container file. + * 4. Copy the remaining metadata stuff. + * + * We do it in this way so we don't have to carry the path to the patch + * container with the patch. This info can be retrieved from the path to + * patch and avoid problems regarding the application running in another path + * than the ulp tool. + * + * See introspection.c: 1868. + * */ + + long metadata_left = 1 + 32; + long metadata_right = metadata_size - metadata_left; + + + char *head = &__ulp_metadata_buffer[metadata_left]; + + uint32_t path_size = strlen(path) + 1; + uint32_t path_object_size = sizeof(uint32_t) + path_size; + + /* Check if it will still fit the metadata buffer. */ + if (metadata_size + path_object_size > ULP_METADATA_BUF_LEN) { + /* Won't fit. */ + return ENOMEM; + } + + /* Shift right so it fits. */ + memmove(head + path_object_size, head, metadata_right); + + /* Inject the path. */ + memcpy(head, &path_size, sizeof(uint32_t)); + head += sizeof(uint32_t); + + memcpy(head, path, path_size); + head += path_object_size; + + return 0; +} + +int +gdb_ulp_apply(const char *path) +{ + /* Prepare the ULP metadata buffer. */ + memset(__ulp_metadata_buffer, '\0', ULP_METADATA_BUF_LEN); + + /* Load the .ulp section into the metadata buffer. */ + long len = Get_ULP_Section(ULP_METADATA_BUF_LEN, (void*)__ulp_metadata_buffer, path); + if (len < 0) { + /* Invalid. */ + return (int) -len; + } + + if (inject_lp_path(path, len)) { + return EINVALIDULP; + } + + /* Trigger the livepatch. */ + return __ulp_apply_patch(); +} + + +int +gdb_ulp_revert(const char *path) +{ + /* Prepare the ULP metadata buffer. */ + memset(__ulp_metadata_buffer, '\0', ULP_METADATA_BUF_LEN); + + /* Load the .ulp section into the metadata buffer. */ + long len = Get_ULP_REV_Section(ULP_METADATA_BUF_LEN, (void *)__ulp_metadata_buffer, path); + if (len < 0) { + /* Invalid. */ + return (int) -len; + } + + if (inject_lp_path(path, len)) { + return EINVALIDULP; + } + + /* Trigger the livepatch. */ + return __ulp_apply_patch(); +} diff --git a/lib/minielf.c b/lib/minielf.c index cec4fc46..5b1a4856 100644 --- a/lib/minielf.c +++ b/lib/minielf.c @@ -187,7 +187,7 @@ long Elf_Load_Section(unsigned dest_size, unsigned char *dest, } /** Load the .ulp section of livepatch of `file` into the buffer. */ -static int +static long Get_Elf_Section(unsigned dest_size, unsigned char *dest, const char *section_name, const char *file) { @@ -195,7 +195,7 @@ Get_Elf_Section(unsigned dest_size, unsigned char *dest, int elf_fd = open(file, O_RDONLY); if (elf_fd < 0) { warn("Unable to open file %s: %s", file, strerror(errno)); - return ENOENT; + return -ENOENT; } /* Load ELF file header. */ @@ -205,7 +205,7 @@ Get_Elf_Section(unsigned dest_size, unsigned char *dest, warn("File is not an ELF object."); close(elf_fd); - return EINVAL; + return -EINVAL; } /* Load ELF section string table. */ @@ -221,27 +221,27 @@ Get_Elf_Section(unsigned dest_size, unsigned char *dest, warn("Section %s not found.", section_name); close(elf_fd); - return EINVAL; + return -EINVAL; } /* Load ELF section into dest. */ - long x = Elf_Load_Section(dest_size, dest, &ulp_shdr, elf_fd); - if (x == 0) { + long len = Elf_Load_Section(dest_size, dest, &ulp_shdr, elf_fd); + if (len == 0) { close(elf_fd); - return EINVAL; + return -EINVAL; } close(elf_fd); - return 0; + return len; } -int +long Get_ULP_Section(unsigned dest_size, unsigned char *dest, const char *file) { return Get_Elf_Section(dest_size, dest, ".ulp", file); } -int +long Get_ULP_REV_Section(unsigned dest_size, unsigned char *dest, const char *file) { return Get_Elf_Section(dest_size, dest, ".ulp.rev", file); diff --git a/tools/introspection.c b/tools/introspection.c index cab1ded8..59125999 100644 --- a/tools/introspection.c +++ b/tools/introspection.c @@ -1848,6 +1848,9 @@ extract_ulp_from_so_to_mem(const char *livepatch, bool revert, char **out, char *final_meta = (char *)malloc(meta_size); char *meta_head = final_meta; + + /* FIXME: This is absurdly awkward. */ + /* Copy the final metadata into final_meta buffer. Things works here as * follows: * From afde580d41eb97233f44097eecd62efbbf39f8c0 Mon Sep 17 00:00:00 2001 From: Giuliano Belinassi Date: Wed, 30 Oct 2024 12:56:28 -0300 Subject: [PATCH 3/4] Implement a insnq interpreter on libpulp side This commit adds a insnq_interp in libpulp side as a way to trigger a livepatch without the `ulp` tool. This is useful for debugging libpulp as for example to use it in valgrind, since we can't run it under addrsan. Signed-off-by: Giuliano Belinassi --- common/Makefile.am | 5 +- common/insn_queue.c | 128 ++++++++++++++++++++++++++ include/insn_queue.h | 9 ++ include/insn_queue_lib.h | 3 + include/ulp_common.h | 1 + lib/gdb_interface.c | 26 +++++- lib/insn_queue.c | 193 +++++++++++++++++++++++++++++++++++++++ lib/libpulp.versions | 2 + tests/insn_queue.c | 4 + tools/insn_queue.c | 100 +------------------- 10 files changed, 370 insertions(+), 101 deletions(-) create mode 100644 common/insn_queue.c diff --git a/common/Makefile.am b/common/Makefile.am index b062db78..51e66cc7 100644 --- a/common/Makefile.am +++ b/common/Makefile.am @@ -23,4 +23,7 @@ noinst_LTLIBRARIES = libcommon.la # Ensure access to the include directory AM_CFLAGS += -I$(abs_top_srcdir)/include -libcommon_la_SOURCES = common.c +# Add -fno-strict-alias to the insn_queue code. +insn_queue.lo : CFLAGS += -fno-strict-aliasing + +libcommon_la_SOURCES = common.c insn_queue.c diff --git a/common/insn_queue.c b/common/insn_queue.c new file mode 100644 index 00000000..adf25657 --- /dev/null +++ b/common/insn_queue.c @@ -0,0 +1,128 @@ +/* + * libpulp - User-space Livepatching Library + * + * Copyright (C) 2023 SUSE Software Solutions GmbH + * + * This file is part of libpulp. + * + * libpulp is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libpulp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with libpulp. If not, see . + */ + +#include "ulp_common.h" +#include "insn_queue.h" +#include "error_common.h" + +#include +#include + +/** @brief Interpret a print instruction. + * + * @param insn Instruction to interpet. Must be a print instruction. + * + * @return Size of interpreted instruction. + */ +int +insn_interpret_print(struct ulp_insn *insn) +{ + struct ulp_insn_print *p_insn = (struct ulp_insn_print *)insn; + + printf("%s\n", p_insn->bytes); + return insn->size; +} + +/** @brief Interpret NOP instruction. + * + * @param insn Instruction to interpet. Must be a NOP instruction. + * + * @return Size of interpreted instruction (always 1 byte). + */ +int +insn_interpret_nop(struct ulp_insn *insn) +{ + return sizeof(*insn); +} + +/* Writes are specific from libpulp and libpulp-tools: + * - On tools, use ptrace. + * - On libpulp, set text permission and use memcpy. + */ +int +insn_interpret_write(struct ulp_insn *insn); + +/** Table of decoders. Index must match the `enum ulp_insn_table` object. */ +static int (*decoders[ULP_NUM_INSNS])(struct ulp_insn *insn) = { + insn_interpret_nop, + insn_interpret_print, + insn_interpret_write, +}; + +/** @brief Interpret the given instruction. + * + * This function will interpret the given instruction. + * + * @param insn Instruction to interpret. + * + * @return Size of instruction interpreted. + */ +int +insn_interpret(struct ulp_insn *insn) +{ + int index = (int)insn->type; + return (decoders[index])(insn); +} + +/** @brief Interpret the instructions in queue. + * + * Interpret all instructions inserted into the queue object. + * + * @param queue + */ +int +insnq_interpret(insn_queue_t *queue) +{ + int pc = 0; /* Like a CPU program counter. */ + int num_insns_executed = 0; + + int size = queue->size; + int num_insns = queue->num_insns; + char *buffer = queue->buffer; + + while (num_insns_executed < num_insns) { + struct ulp_insn *insn = (struct ulp_insn *)&buffer[pc]; + if (ulp_insn_valid(insn)) { + pc += insn_interpret(insn); + num_insns_executed++; + } + else { + /* Abort if an invalid insn is received. */ + WARN("insnq: invalid insn with opcode %d. Further insns will be " + "ignored.", (int)insn->type); + return EINSNQ; + } + } + + /* The pc should stop at the size of the queue. */ + if (pc != size) { + WARN("insnq: there are bytes left in the instruction queue"); + return EINSNQ; + } + + /* Number of instructions should match what is in the queue. */ + if (num_insns_executed != num_insns) { + WARN("insnq: not all instructions executed"); + return EINSNQ; + } + + return 0; +} diff --git a/include/insn_queue.h b/include/insn_queue.h index 937390c1..2f4ae6b3 100644 --- a/include/insn_queue.h +++ b/include/insn_queue.h @@ -138,4 +138,13 @@ ulp_insn_valid(struct ulp_insn *insn) } } + +/** @brief Interpret the instructions in queue. + * + * Interpret all instructions inserted into the queue object. + * + * @param queue + */ +int insnq_interpret(insn_queue_t *queue); + #endif /* INSNQ_H */ diff --git a/include/insn_queue_lib.h b/include/insn_queue_lib.h index cddbe78e..72f1fa90 100644 --- a/include/insn_queue_lib.h +++ b/include/insn_queue_lib.h @@ -32,4 +32,7 @@ ulp_error_t insnq_insert_write(void *addr, int n, const void *bytes); int insnq_ensure_emptiness(void); +/** Interpret the global instruction queue from process side. */ +int insnq_interpret_from_lib(void); + #endif diff --git a/include/ulp_common.h b/include/ulp_common.h index dd4c0871..7eb97ece 100644 --- a/include/ulp_common.h +++ b/include/ulp_common.h @@ -27,6 +27,7 @@ #include #include #include +#include #define OUT_PATCH_NAME "metadata.ulp" #define OUT_REVERSE_NAME "reverse.ulp" diff --git a/lib/gdb_interface.c b/lib/gdb_interface.c index e1fc0789..94533eb1 100644 --- a/lib/gdb_interface.c +++ b/lib/gdb_interface.c @@ -35,6 +35,7 @@ #include "ulp.h" #include "minielf.h" #include "error_common.h" +#include "insn_queue_lib.h" extern char __ulp_metadata_buffer[ULP_METADATA_BUF_LEN]; @@ -90,6 +91,8 @@ inject_lp_path(const char *path, long metadata_size) int gdb_ulp_apply(const char *path) { + int ret; + /* Prepare the ULP metadata buffer. */ memset(__ulp_metadata_buffer, '\0', ULP_METADATA_BUF_LEN); @@ -105,13 +108,23 @@ gdb_ulp_apply(const char *path) } /* Trigger the livepatch. */ - return __ulp_apply_patch(); + if ((ret = __ulp_apply_patch()) != 0) { + return ret; + } + + /* Process instruction queue. */ + if ((ret = insnq_interpret_from_lib()) != 0) { + return ret; + } + + return 0; } int gdb_ulp_revert(const char *path) { + int ret; /* Prepare the ULP metadata buffer. */ memset(__ulp_metadata_buffer, '\0', ULP_METADATA_BUF_LEN); @@ -127,5 +140,14 @@ gdb_ulp_revert(const char *path) } /* Trigger the livepatch. */ - return __ulp_apply_patch(); + if ((ret = __ulp_apply_patch()) != 0) { + return ret; + } + + /* Process instruction queue. */ + if ((ret = insnq_interpret_from_lib()) != 0) { + return ret; + } + + return 0; } diff --git a/lib/insn_queue.c b/lib/insn_queue.c index e1c0ea73..8b6590d2 100644 --- a/lib/insn_queue.c +++ b/lib/insn_queue.c @@ -24,6 +24,11 @@ #include #include #include +#include +#include +#include +#include +#include #include "error.h" #include "ulp_common.h" @@ -170,3 +175,191 @@ insnq_ensure_emptiness(void) return 0; } + + +/* + * Read one line from FD into BUF, which must be pre-allocated and large + * enough to hold LEN characteres. The offset into FD is advanced by the + * amount of bytes read. + * + * @return -1 on error, 0 on End-of-file, or the amount of bytes read. + */ +static int +read_line(int fd, char *buf, size_t len) +{ + char *ptr; + int retcode; + size_t offset; + + /* Read one byte at a time, until a newline is found. */ + offset = 0; + while (offset < len) { + ptr = buf + offset; + + /* Read one byte. */ + retcode = read(fd, ptr, 1); + + /* Error with read syscall. */ + if (retcode == -1) { + if (errno == EINTR || errno == EAGAIN) + continue; + else + return -1; + } + + /* Stop at EOF or EOL. */ + if (retcode == 0 || *ptr == '\n') { + return offset; + } + + offset++; /* Reading one byte at a time. */ + } + + /* EOL not found. */ + return -1; +} + +/* @brief Retrieves the memory protection bits of the page containing ADDR. + * + * @param addr Address of the page. + * @return If errors ocurred, return -1. + */ +static int __attribute((unused)) +memory_protection_get(uintptr_t addr) +{ + char line[LINE_MAX]; + char *str; + char *end; + int fd; + int result; + int retcode; + uintptr_t addr1; + uintptr_t addr2; + + fd = open("/proc/self/maps", O_RDONLY); + if (fd == -1) + return -1; + + /* Iterate over /proc/self/maps lines. */ + result = -1; + for (;;) { + + /* Read one line. */ + retcode = read_line(fd, line, LINE_MAX); + if (retcode <= 0) + break; + + /* Parse the address range in the current line. */ + str = line; + addr1 = strtoul(str, &end, 16); + str = end + 1; /* Skip the dash used in the range output. */ + addr2 = strtoul(str, &end, 16); + + /* Skip line if target address not within range. */ + if (addr < addr1 || addr >= addr2) + continue; + + /* Otherwise, parse the memory protection bits. */ + result = 0; + if (*(end + 1) == 'r') + result |= PROT_READ; + if (*(end + 2) == 'w') + result |= PROT_WRITE; + if (*(end + 3) == 'x') + result |= PROT_EXEC; + break; + } + + close(fd); + return result; +} + +/* When we are testing insnq there are some functions we do not want in the + compilation unit. */ +#ifndef DISABLE_INSNQ_FUNCS_FOR_TESTING + +/** @brief Interpret WRITE instruction. + * + * @param insn Instruction to interpet. Must be a WRITE instruction. + * + * @return Size of interpreted instruction. + */ +int +insn_interpret_write(struct ulp_insn *insn) +{ + struct ulp_insn_write *winsn = (struct ulp_insn_write *)insn; + + uintptr_t page_mask, page_size; + + page_size = getpagesize(); + page_mask = ~(page_size - 1); + + uintptr_t page1 = winsn->address & page_mask; + uintptr_t pagen = (winsn->address + winsn->n) & page_mask; + + int num_pages = 1 + (pagen - page1) / page_size; + + int prot[num_pages]; + + for (int i = 0; i < num_pages; i++) { + uintptr_t page = page1 + i * page_size; + + /* Make sure we always get the one with page size. */ + libpulp_assert(page == (page & page_mask)); + + prot[i] = memory_protection_get(page); + + if (prot[i] == -1) { + WARN("Memory protection get error (%d page)", i); + return errno; + } + } + + for (int i = 0; i < num_pages; i++) { + uintptr_t page = page1 + i * page_size; + if (mprotect((void *)page, page_size, prot[i] | PROT_WRITE)) { + WARN("Memory protection set error (%d page)", i); + return errno; + } + } + + memcpy((void *)winsn->address, winsn->bytes, winsn->n); + + /* Make sure we wrote that. */ + if (memcmp((void *)winsn->address, winsn->bytes, winsn->n) != 0) { + WARN("Failed to write at address 0x%lx", winsn->address); + } + + for (int i = 0; i < num_pages; i++) { + uintptr_t page = page1 + i * page_size; + if (mprotect((void *)page, page_size, prot[i])) { + WARN("Memory protection set error (%d page)", i); + return errno; + } + } + + return insn->size; +} + +#endif //DISABLE_INSNQ_FUNCS_FOR_TESTING + +/** @brief Process global instruction queue. + * + * Processes the global instruction queue that should be sent to the `ulp` + * command, but we may need to process this queue in the process side if we + * are debugging libpulp (e.g. patch triggered from gdb interface). + */ +int +insnq_interpret_from_lib(void) +{ + /* Interpret global queue. */ + struct insn_queue *queue = &__ulp_insn_queue; + int ret = insnq_interpret(queue); + + /* Clean up the queue. */ + memset(queue->buffer, 0, INSN_BUFFER_MAX); + queue->num_insns = 0; + queue->size = 0; + + return ret; +} diff --git a/lib/libpulp.versions b/lib/libpulp.versions index 9ecbe1bc..f583af6c 100644 --- a/lib/libpulp.versions +++ b/lib/libpulp.versions @@ -28,6 +28,8 @@ __ulp_enable_or_disable_patching; __ulp_insn_queue; __ulp_version; + gdb_ulp_apply; + gdb_ulp_revert; local: *; }; diff --git a/tests/insn_queue.c b/tests/insn_queue.c index 5fa2bd1c..a2367bda 100644 --- a/tests/insn_queue.c +++ b/tests/insn_queue.c @@ -33,9 +33,13 @@ msgq_push(const char *format, ...) /* Disable the poisoning in error.h. */ #define DISABLE_ERR_POISON +/* Disable some functions from libpulp side. */ +#define DISABLE_INSNQ_FUNCS_FOR_TESTING + #include "../lib/error.c" #include "../lib/insn_queue.c" #include "../tools/insn_queue.c" +#include "../common/insn_queue.c" #include "../tools/ptrace.c" /* Set a two-way communcation channel between child and parent. */ diff --git a/tools/insn_queue.c b/tools/insn_queue.c index 88fb075f..8ba5f641 100644 --- a/tools/insn_queue.c +++ b/tools/insn_queue.c @@ -29,40 +29,13 @@ /** PID of target process in which we will execute the instructions. */ static int remote_pid; -/** @brief Interpret a print instruction. - * - * @param insn Instruction to interpet. Must be a print instruction. - * - * @return Size of interpreted instruction. - */ -static int -insn_interpret_print(struct ulp_insn *insn) -{ - struct ulp_insn_print *p_insn = (struct ulp_insn_print *)insn; - - printf("%s\n", p_insn->bytes); - return insn->size; -} - -/** @brief Interpret NOP instruction. - * - * @param insn Instruction to interpet. Must be a NOP instruction. - * - * @return Size of interpreted instruction (always 1 byte). - */ -static int -insn_interpret_nop(struct ulp_insn *insn) -{ - return sizeof(*insn); -} - -/** @brief Interpret NOP instruction. +/** @brief Interpret WRITE instruction. * * @param insn Instruction to interpet. Must be a WRITE instruction. * * @return Size of interpreted instruction. */ -static int +int insn_interpret_write(struct ulp_insn *insn) { int pid = remote_pid; // Pass process pid. @@ -74,75 +47,6 @@ insn_interpret_write(struct ulp_insn *insn) return insn->size; } -/** Table of decoders. Index must match the `enum ulp_insn_table` object. */ -static int (*decoders[ULP_NUM_INSNS])(struct ulp_insn *insn) = { - insn_interpret_nop, - insn_interpret_print, - insn_interpret_write, -}; - -/** @brief Interpret the given instruction. - * - * This function will interpret the given instruction. - * - * @param insn Instruction to interpret. - * - * @return Size of instruction interpreted. - */ -int -insn_interpret(struct ulp_insn *insn) -{ - int index = (int)insn->type; - return (decoders[index])(insn); -} - -/** @brief Interpret the instructions in queue. - * - * Interpret all instructions inserted into the queue object. - * - * @param queue - */ -int -insnq_interpret(insn_queue_t *queue) -{ - int pc = 0; /* Like a CPU program counter. */ - int num_insns_executed = 0; - - int size = queue->size; - int num_insns = queue->num_insns; - char *buffer = queue->buffer; - - while (num_insns_executed < num_insns) { - struct ulp_insn *insn = (struct ulp_insn *)&buffer[pc]; - if (ulp_insn_valid(insn)) { - pc += insn_interpret(insn); - num_insns_executed++; - } - else { - /* Abort if an invalid insn is received. */ - WARN("on pid: %d invalid insn with opcode %d. Further insns will be " - "ignored.", - remote_pid, (int)insn->type); - return EINSNQ; - } - } - - /* The pc should stop at the size of the queue. */ - if (pc != size) { - WARN("on pid %d: there are bytes left in the instruction queue", - remote_pid); - return EINSNQ; - } - - /* Number of instructions should match what is in the queue. */ - if (num_insns_executed != num_insns) { - WARN("on pid %d: not all instructions executed", remote_pid); - return EINSNQ; - } - - return 0; -} - /** @brief Get the instruction queue on remote process. * * This function will get the instruction queue on `queue_adddr` of process From b7abdd30ce3b1eb0de8c11375c3147e218f96d01 Mon Sep 17 00:00:00 2001 From: Giuliano Belinassi Date: Mon, 4 Nov 2024 13:41:01 -0300 Subject: [PATCH 4/4] Only build and expose the gdb interface when requested The gdb interface should be used for debugging libpulp, so applications may not want this exposed. To enable it, build with ``` configure --enable-gdb-interface ``` Signed-off-by: Giuliano Belinassi --- configure.ac | 10 ++++++++++ include/insn_queue_lib.h | 5 +++++ include/minielf.h | 5 +++++ include/ulp_common.h | 1 + lib/gdb_interface.c | 11 +++++++++-- lib/minielf.c | 7 +++++++ 6 files changed, 37 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 4034ae7b..d73a3a0f 100644 --- a/configure.ac +++ b/configure.ac @@ -150,6 +150,16 @@ AC_SUBST([LIBUNWIND_LIBS], ["-lunwind-generic -lunwind-ptrace -lunwind"]) AC_DEFINE(ENABLE_STACK_CHECK, 1, [Enable stack checking routines]), AC_DEFINE(ENABLE_STACK_CHECK, 0, [Disable stack checking routines])) +# Enable a gdb interface so that livepatches can be triggered within gdb. +AC_ARG_ENABLE(gdb-interface, +AS_HELP_STRING([--enable-gdb-interface], +[build and exposes an interface for livepatching withing gdb. [default=no]]), +[enable_gdb_interface=yes], +[enable_gdb_interface=no; break]) + +AS_IF([test "$enable_gdb_interface" = "yes"], +AC_DEFINE(ENABLE_GDB_INTERFACE, 1, [Enable gdb interface for livepatching])) + # Check if libseccomp is present. This is required for testing. CFLAGS="$CFLAGS -I/usr/include/libseccomp/" AC_CHECK_HEADER([seccomp.h],, diff --git a/include/insn_queue_lib.h b/include/insn_queue_lib.h index 72f1fa90..adc18710 100644 --- a/include/insn_queue_lib.h +++ b/include/insn_queue_lib.h @@ -32,7 +32,12 @@ ulp_error_t insnq_insert_write(void *addr, int n, const void *bytes); int insnq_ensure_emptiness(void); +/* Not necessary if compiling without gdb interface. */ +#ifdef ENABLE_GDB_INTERFACE + /** Interpret the global instruction queue from process side. */ int insnq_interpret_from_lib(void); +#endif //ENABLE_GDB_INTERFACE + #endif diff --git a/include/minielf.h b/include/minielf.h index e4efdc91..9ef69511 100644 --- a/include/minielf.h +++ b/include/minielf.h @@ -24,6 +24,9 @@ * in this library. */ +/* This file is not needed if we are compiling without gdb interface. */ +#ifdef ENABLE_GDB_INTERFACE + #include /** Maximum size of the Section String Table. */ @@ -67,3 +70,5 @@ long Get_ULP_Section(unsigned dest_size, unsigned char *dest, const char *file); /** Get the .ulp.rev section from the given ELF file. */ long Get_ULP_REV_Section(unsigned dest_size, unsigned char *dest, const char *file); + +#endif //ENABLE_GDB_INTERFACE diff --git a/include/ulp_common.h b/include/ulp_common.h index 7eb97ece..35687158 100644 --- a/include/ulp_common.h +++ b/include/ulp_common.h @@ -22,6 +22,7 @@ #ifndef _ULP_LIB_COMMON_ #define _ULP_LIB_COMMON_ +#include "config.h" #include #include #include diff --git a/lib/gdb_interface.c b/lib/gdb_interface.c index 94533eb1..155bf0bf 100644 --- a/lib/gdb_interface.c +++ b/lib/gdb_interface.c @@ -20,7 +20,13 @@ */ /* Small interface that allows livepatches to be applied or reverted - * within gdb. */ + * within gdb. There is no need to compile this file if + * ENABLE_GDB_INTERFACE is not defined. + */ + +#include "config.h" + +#ifdef ENABLE_GDB_INTERFACE #ifndef _GNU_SOURCE #define _GNU_SOURCE @@ -30,7 +36,6 @@ #include #include -#include "config.h" #include "ulp_common.h" #include "ulp.h" #include "minielf.h" @@ -151,3 +156,5 @@ gdb_ulp_revert(const char *path) return 0; } + +#endif //ENABLE_GDB_INTERFACE diff --git a/lib/minielf.c b/lib/minielf.c index 5b1a4856..93268a29 100644 --- a/lib/minielf.c +++ b/lib/minielf.c @@ -24,6 +24,11 @@ * in this library. */ +#include "config.h" + +/* So far there is no need to compile this file if GDB interface is not set. */ +#ifdef ENABLE_GDB_INTERFACE + #include #include #include @@ -246,3 +251,5 @@ Get_ULP_REV_Section(unsigned dest_size, unsigned char *dest, const char *file) { return Get_Elf_Section(dest_size, dest, ".ulp.rev", file); } + +#endif //ENABLE_GDB_INTERFACE