lebedov
lebedov

Reputation: 1391

get shared library soname in a Python program

I'm writing a Python wrapper for a shared Linux library using ctypes. Is there some way to extract the library's soname programmatically (e.g., possibly via some library for accessing its ELF data)? (I know that I can obtain this information from the output of the objdump command, but I was curious whether it can be done without having to execute a system command.)

Upvotes: 1

Views: 1285

Answers (3)

Daniel Schepler
Daniel Schepler

Reputation: 3103

Since the last posting, it seems that pyelftools has gotten a bit more convenient to use to extract the information:

from elftools.elf.elffile import ELFFile
from elftools.elf.dynamic import DynamicSegment

def getsoname(path):
    with open(path, 'rb') as f:
        ef = ELFFile(f)
        try:
            dynamic_segment = next(s for s in ef.iter_segments() if isinstance(s, DynamicSegment))
            soname_tag = next(t for t in dynamic_segment.iter_tags() if t['d_tag'] == 'DT_SONAME')
            return soname_tag.soname
        except StopIteration:
            return None

Upvotes: 0

lebedov
lebedov

Reputation: 1391

Figured it out; solution (using pyelftools) posted here.

Upvotes: 0

Ellioh
Ellioh

Reputation: 5330

Of course, you may execute objdump using subprocess and then parse its output to get soname, but that is what you want to avoid. However, a shell example is here.

There also is pyelftools to look at. As far as I see from the docs, it should be able to retrieve all the necessary data.

Upvotes: 4

Related Questions