[llvm] [LLVM][Support] check for error return from dladdr. (PR #138369)

via llvm-commits llvm-commits at lists.llvm.org
Fri May 2 17:25:53 PDT 2025


https://github.com/jeremyd2019 created https://github.com/llvm/llvm-project/pull/138369

In case of an error, the DL_info struct may have been left uninitialized, so it is not safe to use its members.

In one error case, initialize dli_sname to nullptr explicitly, so that the later check against nullptr is guaranteed to be safe.

>From dcd5e18b4a2eaed261679958a5d4fdd7676c3ae2 Mon Sep 17 00:00:00 2001
From: Jeremy Drake <github at jdrake.com>
Date: Fri, 2 May 2025 17:21:21 -0700
Subject: [PATCH] [LLVM][Support] check for error return from dladdr.

In case of an error, the DL_info struct may have been left
uninitialized, so it is not safe to use its members.

In one error case, initialize dli_sname to nullptr explicitly, so that
the later check against nullptr is guaranteed to be safe.

Signed-off-by: Jeremy Drake <github at jdrake.com>
---
 llvm/lib/Support/Unix/Signals.inc | 33 +++++++++++++++++++------------
 1 file changed, 20 insertions(+), 13 deletions(-)

diff --git a/llvm/lib/Support/Unix/Signals.inc b/llvm/lib/Support/Unix/Signals.inc
index 691e1014f18e8..b2bc76a1121d4 100644
--- a/llvm/lib/Support/Unix/Signals.inc
+++ b/llvm/lib/Support/Unix/Signals.inc
@@ -826,14 +826,17 @@ void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
   int width = 0;
   for (int i = 0; i < depth; ++i) {
     Dl_info dlinfo;
-    dladdr(StackTrace[i], &dlinfo);
-    const char *name = strrchr(dlinfo.dli_fname, '/');
-
     int nwidth;
-    if (!name)
-      nwidth = strlen(dlinfo.dli_fname);
-    else
-      nwidth = strlen(name) - 1;
+    if (dladdr(StackTrace[i], &dlinfo) == 0) {
+      nwidth = 7; // "(error)"
+    } else {
+      const char *name = strrchr(dlinfo.dli_fname, '/');
+
+      if (!name)
+        nwidth = strlen(dlinfo.dli_fname);
+      else
+        nwidth = strlen(name) - 1;
+    }
 
     if (nwidth > width)
       width = nwidth;
@@ -841,15 +844,19 @@ void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
 
   for (int i = 0; i < depth; ++i) {
     Dl_info dlinfo;
-    dladdr(StackTrace[i], &dlinfo);
 
     OS << format("%-2d", i);
 
-    const char *name = strrchr(dlinfo.dli_fname, '/');
-    if (!name)
-      OS << format(" %-*s", width, static_cast<const char *>(dlinfo.dli_fname));
-    else
-      OS << format(" %-*s", width, name + 1);
+    if (dladdr(StackTrace[i], &dlinfo) == 0) {
+      OS << format(" %-*s", width, "(error)");
+      dlinfo.dli_sname = nullptr;
+    } else {
+      const char *name = strrchr(dlinfo.dli_fname, '/');
+      if (!name)
+        OS << format(" %-*s", width, static_cast<const char *>(dlinfo.dli_fname));
+      else
+        OS << format(" %-*s", width, name + 1);
+    }
 
     OS << format(" %#0*lx", (int)(sizeof(void *) * 2) + 2,
                  (unsigned long)StackTrace[i]);



More information about the llvm-commits mailing list