From 0aed4315b2f6c54f4efcf8a8d22e59a36e6eb30d Mon Sep 17 00:00:00 2001 From: Mark Wielaard Date: Mon, 19 Jul 2021 15:52:51 +0200 Subject: libelf: Optimize elf_strptr.c validate_str by checking last char first In most cases the last char of the sectio will be zero. Check that first before calling memrchr. This is a minor optimization in normal cases. But it helps asan a lot by removing the memrchr call in most cases. https://sourceware.org/bugzilla/show_bug.cgi?id=28101 Signed-off-by: Mark Wielaard --- libelf/ChangeLog | 5 +++++ libelf/elf_strptr.c | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/libelf/ChangeLog b/libelf/ChangeLog index 62437c55..f521ed3d 100644 --- a/libelf/ChangeLog +++ b/libelf/ChangeLog @@ -1,3 +1,8 @@ +2021-07-19 Mark Wielaard + + * elf_strptr.c (validate_str): Check last char is zero first before + calling memrchr on the whole block. + 2021-06-09 Andrei Homescu * elf_getdata.c: Fix d_align for sections where alignment is larger diff --git a/libelf/elf_strptr.c b/libelf/elf_strptr.c index 76f2caf1..79a24d25 100644 --- a/libelf/elf_strptr.c +++ b/libelf/elf_strptr.c @@ -56,7 +56,9 @@ get_zdata (Elf_Scn *strscn) static bool validate_str (const char *str, size_t from, size_t to) { #if HAVE_DECL_MEMRCHR - return memrchr (&str[from], '\0', to - from) != NULL; + // Check end first, which is likely a zero terminator, to prevent function call + return ((to > 0 && str[to - 1] == '\0') + || (to - from > 0 && memrchr (&str[from], '\0', to - from - 1) != NULL)); #else do { if (to <= from) -- cgit v1.2.1