Skip to content

Instantly share code, notes, and snippets.

@deborasetton
Created September 6, 2015 22:18
Show Gist options
  • Select an option

  • Save deborasetton/f0faaef5ed48130d8c70 to your computer and use it in GitHub Desktop.

Select an option

Save deborasetton/f0faaef5ed48130d8c70 to your computer and use it in GitHub Desktop.
Python script to search for a symbol in libraries loaded by the dynamic linker (ld.so)
#!/usr/bin/env python
# Python script to search for a given symbol in libraries that are loaded by
# the dynamic linker (ld.so) in Linux.
#
# For example: to use the function `cabs` (absolute value of a complex number)
# you need to include the header <complex.h>, but the function itself is
# defined in libm.so.
#
# To find that out, you'd run:
# sudo findsym cabs
#
# Obs: sudo is needed to run ldconfig without errors.
#
# Command-line equivalent:
# $ ldconfig -v
# $ nm -D <path-to-so-file> | grep -i <symbol>
#
# Based on:
# http://stackoverflow.com/questions/9922949/how-to-print-the-ldlinker-search-path
# http://stackoverflow.com/questions/1237575/how-do-i-find-out-what-all-symbols-are-exported-from-a-shared-object
import re
import sh
import sys
# Terminal ANSI colors.
class tcolors:
RED = '\033[31m'
GREEN = '\033[32m'
BLUE = '\033[34m'
ENDC = '\033[0m'
current_user = sh.whoami().strip()
if current_user != "root":
print(tcolors.RED + "You must be root to use this script. Please re-run with sudo." + tcolors.ENDC)
exit(1)
if len(sys.argv) < 2:
print(tcolors.RED + "Missing search term." + tcolors.ENDC)
print(tcolors.RED + "Usage: %s <search-term>" % sys.argv[0] + tcolors.ENDC)
exit(1)
ldconfig_out = sh.ldconfig("-v")
# Store current library directory we're inspecting
basepath = None
# Store absolute path to .so files.
files = []
search_term = sys.argv[1]
print(tcolors.BLUE + "Looking for term: " + search_term + tcolors.ENDC)
for line in ldconfig_out.splitlines():
if line.startswith("\t"):
if basepath is None:
print("[error] Unexpected library name without a basepath.")
exit(1)
md = re.match('\t([^ ]+)', line)
if md is not None:
libname = md.group(1)
files.append(basepath + "/" + libname)
else:
basepath = line[0:-1]
# Search all files found in ldconfig output for the given symbol.
for filename in files:
nm_out = sh.nm("-D", filename)
try:
grep_out = sh.grep("-i", search_term, _in=nm_out)
print(tcolors.GREEN + "\nFound match in file: " + filename + tcolors.ENDC)
print(grep_out)
except sh.ErrorReturnCode_1:
# No match, but it's not an error.
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment