refactor: find_loaded_library (#31866)

Signed-off-by: tjp_zju <tanjianpingzju1990@gmail.com>
Co-authored-by: Cyrus Leung <cyrus.tl.leung@gmail.com>
This commit is contained in:
tjp_zju
2026-01-07 06:42:20 +00:00
committed by GitHub
co-authored by Cyrus Leung
parent c7a79d41a0
commit 55caa6051d
3 changed files with 29 additions and 54 deletions
+27
View File
@@ -267,3 +267,30 @@ def set_ulimit(target_soft_limit: int = 65535):
current_soft,
e,
)
def find_loaded_library(lib_name: str) -> str | None:
"""
According to according to https://man7.org/linux/man-pages/man5/proc_pid_maps.5.html,
the file `/proc/self/maps` contains the memory maps of the process, which includes the
shared libraries loaded by the process. We can use this file to find the path of the
a loaded library.
""" # noqa
found_line = None
with open("/proc/self/maps") as f:
for line in f:
if lib_name in line:
found_line = line
break
if found_line is None:
# the library is not loaded in the current process
return None
# if lib_name is libcudart, we need to match a line with:
# address /path/to/libcudart-hash.so.11.0
start = found_line.index("/")
path = found_line[start:].strip()
filename = path.split("/")[-1]
assert filename.rpartition(".so")[0].startswith(lib_name), (
f"Unexpected filename: {filename} for library {lib_name}"
)
return path