git: b53ecd5cf63b - stable/13 - libc dlfcn.c: make dl_iterate_phdr() from libc more useful

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Sun, 13 Aug 2023 04:37:56 UTC
The branch stable/13 has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=b53ecd5cf63b90a72436642056733b686d881eb1

commit b53ecd5cf63b90a72436642056733b686d881eb1
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2023-08-09 05:07:05 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2023-08-13 04:35:41 +0000

    libc dlfcn.c: make dl_iterate_phdr() from libc more useful
    
    PR:     272992
    
    (cherry picked from commit 21a52f99440c9bec7679f3b0c5c9d888901c3694)
---
 lib/libc/gen/dlfcn.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/lib/libc/gen/dlfcn.c b/lib/libc/gen/dlfcn.c
index 61984e2fe86c..f1ee86ec1934 100644
--- a/lib/libc/gen/dlfcn.c
+++ b/lib/libc/gen/dlfcn.c
@@ -169,7 +169,9 @@ _rtld_thread_init(void *li __unused)
 #ifndef IN_LIBDL
 static pthread_once_t dl_phdr_info_once = PTHREAD_ONCE_INIT;
 static struct dl_phdr_info phdr_info;
+#ifndef PIC
 static mutex_t dl_phdr_info_lock = MUTEX_INITIALIZER;
+#endif
 
 static void
 dl_init_phdr_info(void)
@@ -208,7 +210,16 @@ int
 dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *) __unused,
     void *data __unused)
 {
-#ifndef IN_LIBDL
+#if defined IN_LIBDL
+	return (0);
+#elif defined PIC
+	int (*r)(int (*)(struct dl_phdr_info *, size_t, void *), void *);
+
+	r = dlsym(RTLD_DEFAULT, "dl_iterate_phdr");
+	if (r == NULL)
+		return (0);
+	return (r(callback, data));
+#else
 	tls_index ti;
 	int ret;
 
@@ -223,8 +234,6 @@ dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *) __unused,
 	ret = callback(&phdr_info, sizeof(phdr_info), data);
 	mutex_unlock(&dl_phdr_info_lock);
 	return (ret);
-#else
-	return (0);
 #endif
 }