libelf: Optimize elf_strptr.c validate_str by checking last char first
authorMark Wielaard <mark@klomp.org>
Mon, 19 Jul 2021 13:52:51 +0000 (15:52 +0200)
committerMark Wielaard <mark@klomp.org>
Mon, 19 Jul 2021 13:52:51 +0000 (15:52 +0200)
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 <mark@klomp.org>
libelf/ChangeLog
libelf/elf_strptr.c

index 62437c5..f521ed3 100644 (file)
@@ -1,3 +1,8 @@
+2021-07-19  Mark Wielaard  <mark@klomp.org>
+
+       * elf_strptr.c (validate_str): Check last char is zero first before
+       calling memrchr on the whole block.
+
 2021-06-09  Andrei Homescu  <ah@immunant.com>
 
        * elf_getdata.c: Fix d_align for sections where alignment is larger
index 76f2caf..79a24d2 100644 (file)
@@ -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)