On Fri, Jun 30, 2023 at 1:35 AM Jiri Olsa <jolsa@xxxxxxxxxx> wrote: > > Adding elf_open/elf_close functions and using it in > elf_find_func_offset_from_file function. It will be > used in following changes to save some common code. > > Signed-off-by: Jiri Olsa <jolsa@xxxxxxxxxx> > --- > tools/lib/bpf/elf.c | 59 +++++++++++++++++++++++++------------- > tools/lib/bpf/libbpf_elf.h | 8 ++++++ > tools/lib/bpf/usdt.c | 31 ++++++-------------- > 3 files changed, 56 insertions(+), 42 deletions(-) > one nit below Acked-by: Andrii Nakryiko <andrii@xxxxxxxxxx> > diff --git a/tools/lib/bpf/elf.c b/tools/lib/bpf/elf.c > index 2b62b4af28ce..74e35071d22e 100644 > --- a/tools/lib/bpf/elf.c > +++ b/tools/lib/bpf/elf.c > @@ -11,6 +11,40 @@ > > #define STRERR_BUFSIZE 128 > > +int elf_open(const char *binary_path, struct elf_fd *elf_fd) > +{ > + char errmsg[STRERR_BUFSIZE]; > + int fd, ret; > + Elf *elf; > + > + if (elf_version(EV_CURRENT) == EV_NONE) { > + pr_warn("elf: failed to init libelf for %s\n", binary_path); > + return -LIBBPF_ERRNO__LIBELF; > + } > + fd = open(binary_path, O_RDONLY | O_CLOEXEC); > + if (fd < 0) { > + ret = -errno; > + pr_warn("elf: failed to open %s: %s\n", binary_path, > + libbpf_strerror_r(ret, errmsg, sizeof(errmsg))); > + return ret; > + } > + elf = elf_begin(fd, ELF_C_READ_MMAP, NULL); > + if (!elf) { > + pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1)); > + close(fd); > + return -LIBBPF_ERRNO__FORMAT; > + } > + elf_fd->fd = fd; > + elf_fd->elf = elf; > + return 0; > +} > + > +void elf_close(struct elf_fd *elf_fd) > +{ > + elf_end(elf_fd->elf); > + close(elf_fd->fd); nit: I'd make elf_close() work correctly with a) NULL elf_fd and b) NULL elf_fd->elf, just to never have to think about this > +} > + > /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */ > static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn) > { [...]