libelf – classes for ELF and ar inspection

The Library class provides interaction with ELF files. To open a file from a filename, simply type:

from pylibelf import libelf
lib = libelf.Library("/bin/bash")
print lib

This will print out all the gory details of the library. If you don’t want this behaviour, you can set the sanestr setting to False (see settings for details), or use repr().

libelf.ldd(path, cwd=os.curdir, library_path=[], skip_missing=False)
Platform :Unix

Like ldd, return a list of libraries that an executable or shared library depends on.

Parameters:
  • path – path to the executable or library
  • cwd – if the cwd is specified in the RPATH of the executable or library, or specified by LD_LIBRARY_PATH (e.g. ‘foo:bar:’), use cwd as the cwd
  • library_path – path of library directories to search after RPATH but before LD_LIBRARY_PATH
  • skip_missing – if True, don’t raise LocateError when a dependency couldn’t be found
class libelf.Library(path|fd[, write=False[, create=False[, elfclass=ELFCLASSNONE]]])

Open an ELF file from a path or fd.

Parameters:
  • path – path to the ELF object file to open. For Ar file see the Ar class.
  • fd – file descriptor of the ELF file to open
  • write – specifies whether to open the ELF file for writing also
  • create – if true, create a new ELF file at path
  • elfclass – the class the ELF file should have

Note

Write support is currently experimental and may or may not bite you in the buttocks.

filename

Filename of the object, if path was given to the constructor.

mode

Mode the ELF file is opened in.

type

Type of ELF file (ET_EXEC, ET_DYN, etc).

kind

Kind of file (ELF_K_ELF, ELF_K_COFF, ELF_K_AR).

elfclass

The class of the ELF file (e.g. ELFCLASS32, ELFCLASS64).

ordering

Byte ordering of the ELF file (e.g. ELFDATA2LSB, ELFDATA2MSB).

os_abi

OS/ABI identification.

abi_version

The version of the ABI it wants.

machine

The machine architecture the ELF file was compiled for (e.g. EM_386, EM_X86_64).

entrypoint

The entrypoint of the program.

segments

The segments in the object file.

sections

The sections in the object file.

strtab

The string table section holding the section names.

symtab

The symbol table section of the object file (SHT_SYMTAB). Set for relocatable object files.

dynsym

The symbol table section of the object file (SHT_DYNSYM). Set for shared libraries and executables.

dynamic_section

The dynamic section of the object file (SHT_DYNAMIC).

dependencies

Direct dependencies of this object file.

soname

The name of the shared library.

findsection(**kwargs)

Convenience method, like find for sections.

findsegment(**kwargs)

Convenience method, like find for segments.

save([path])

Write the ELF representation to the path given in the constructor, or to path if supplied as an argument.

close()

Explicitly close the library (this would otherwise happen in the deconstructor).

Example:

>>> from pylibelf import libelf, elf, elf_constants
>>> lib = libelf.Library('/bin/ls')
>>> print lib.findsection(name='.interp')
Section(name:      '.interp'
        type:      Type(SHT_PROGBITS, 'Program data')
        flags:     0x02
        address:   0x400238
        offset:    0x238
        link:      0x00
        info:      0x00
        addralign: 0x01
        entsize:   0x00
        data:      SectionData(type:    Type(ELF_T_BYTE, 0)
                               version: 0x01
                               data:    '/lib64/ld-linux-x86-64.so.2\x00'
                               size:    0x1c))
>>> elf.pretty_print(elf.findall(lib.segments, type=elf_constants.PT_LOAD))
[Segment(type:             Type(PT_LOAD, 'Loadable program segment')
         readable:         0x01
         writable:         0x00
         executable:       0x01
         alignment:        Type('2**21')
         offset:           0x00
         virtual_address:  0x400000
         physical_address: 0x400000
         filesize:         0x1aa84
         memsize:          0x1aa84
         section_names:    ['.interp'
                            '.note.ABI-tag'
                            '.note.gnu.build-id'
                            '.hash'
                            '.gnu.hash'
                            '.dynsym'
                            '.dynstr'
                            '.gnu.version'
                            '.gnu.version_r'
                            '.rela.dyn'
                            '.rela.plt'
                            '.init'
                            '.plt'
                            '.text'
                            '.fini'
                            '.rodata'
                            '.eh_frame_hdr'
                            '.eh_frame'])
 Segment(type:             Type(PT_LOAD, 'Loadable program segment')
         readable:         0x01
         writable:         0x01
         executable:       0x00
         alignment:        Type('2**21')
         offset:           0x1ade0
         virtual_address:  0x61ade0
         physical_address: 0x61ade0
         filesize:         0x750
         memsize:          0x14a0
         section_names:    ['.ctors'
                            '.dtors'
                            '.jcr'
                            '.dynamic'
                            '.got'
                            '.got.plt'
                            '.data'
                            '.bss'])]
class libelf.Segment(*, sections, type=PT_NOTE, flags=PF_R, alignment=0, offset=-1, virtual_address=0, physical_address=0, filesize=0, memsize=0)

Represents an ELF segment. Attributes are as listed in the constructor, they correspond to the p_* attributes of the ELF segment header. Additional attributes are readable, writable and executable.

class libelf.Section(*, name, data=None, type, flags=0, address=0, offset=0, size=0, link=0, info=0, addralign=0, entsize=0)

Represents an ELF section. Attributes are as listed in the constructor, they correspond to the sh_* attributes of the ELF section header.

issym()

Indicates whether this section is a symbol table.

class libelf.SymbolTable(symbols[, **kwargs])

Extends Section. symbols should be a list of Symbol. kwargs is passed to the parent constructor.

symbols

The list of symbols in the section.

strtab

The string table holding the names of the symbols

findsymbol(name[, **kwargs])

Find a symbol with name name and optionally attributes specified by kwargs.

class libelf.StringTable(strings[, **kwargs])

Extends Section. strings should be a list of strings.

strings

The list of strings that are in the string table.

add_strings(*newstrings)

Add a bunch of strings to the string table. This method takes care of substrings (e.g. serialize [‘spamham’, ‘ham’] as ‘\0spamham\0’ instead of ‘\0spamham\0ham\0’).

string_from_offset(offset)

Return the string given the offset into the section data.

class libelf.RelocationSection(relocations[, **kwargs])

Extends Section. strings should be a list of Relocation.

relocations

The relocations specified by the section.

relocatee

The section the relocations apply to.

symtab

The associated symbol table.

class libelf.DynamicSection(dyns[, **kwargs])

Extends Section. dyns should be a list of Dyn.

dyns

The list of entries with dynamic linking information.

strtab

The string table associated with the dynamic section.

rpath

List of paths that the library specifies to look for for dependencies.

dependencies

Equivalent to Library.dependencies

class libelf.SectionData(data[, *, type, alignment])

Represents the data of a section, it is the data attribute of a Section.

data

The data of the section as a byte string.

type

The type of the items in the data (e.g. ELF_T_BYTE, ELF_T_DYN, etc)

alignment

Alignment used by the section.

class libelf.Symbol([*, name, value, size, binding=STB_GLOBAL, type=STT_NOTYPE, other, shndx])

Represents a single symbol in a symbol table. The constructor arguments are attributes of the instance.

Get the section the symbol was specified in relation to. lib is the Library the symbol was found in.

class libelf.Relocation(machine, offset, symindex, type)

Represents a single relocation. machine should be one of the EM_* constants. offset, symindex and type are instance attributes. type can have values specified by the R_ constants (constants should be chosen according to machine).

info

The r_info attribute of the associated Elfxx_Rel structure.

class libelf.RelocationAddend(..., addend)

Like Relocation but with an addend.

class libelf.Dyn(tag, value)

An entry in the dynamic section. tag and value are instance attributes, and can have values specified by the flags DT_ and DF_ respectively.

ispointer()

Indicates whether self.value should be treated as a pointer.

class libelf.Ar(path)

Open an ar file for reading.

path

Path to the ar file.

headers

List of ArHeader founds in the ar file.

libs

List of ArLibrary found in the ar file.

symbols

Symbol table of the ar file.

lib_from_name(symbolname)

Get the ArLibrary object associated with symbol name symbolname.

lib_from_sym(symbol)

Get the ArLibrary object associated with symbol symbol.

lib_from_offset(offset)

Get the ArLibrary object associated with offset offset.

class libelf.ArLibrary

An ArLibrary is like a Library with some extra functionality.

header

The ArHeader that has some metadata of this library.

ar

The Ar file holding this library.

extracted

Tells us whether we extracted this library using the extract method.

extract(path)

Save the library to a file specified by path. After extraction addtional changes can be saved using the potentially broken save method.

class libelf.ArHeader

The header in the ar file holding metadata on a contained library. Attributes are name, ``date, uid, gid, mode, dataoffset, size.

class libelf.ArSymbol

A symbol in the ar file. Attribute are name, offset and hash.

Example:

>>> from pylibelf import libelf
>>> ar = libelf.Ar('/usr/lib/libpython2.6.a')
>>> print ar.libs[0].header
ArHeader(name:       'getbuildinfo.o'
         date:       Type('Fri Apr 16 16:42:48 2010')
         uid:        0x00
         gid:        0x00
         mode:       0x81a4
         offset:     0x6b9a
         dataoffset: 0x6bd6
         size:       0x8a0)
>>> print ar.libs[0].symtab
SymbolTable(name:      '.symtab'
            type:      Type(SHT_SYMTAB, 'Symbol table')
            flags:     0x00
            address:   0x00
            offset:    0x568
            link:      0x0d
            info:      0x0b
            addralign: 0x08
            entsize:   0x18
            data:      SectionData(type:    Type(ELF_T_SYM, 11)
                                   version: 0x01
                                   data:    '\x00\x00\x00\x00\x00\x00\x00\x00\x ...'
                                   size:    0x180)
            symbols:   [Symbol(name:    ''
                               value:   0x00
                               size:    0x00
                               binding: Type(STB_LOCAL, 'Local symbol')
                               type:    Type(STT_NOTYPE, 'Symbol type is unspecified')
                               shndx:   0x00)

                        ...

                        Symbol(name:    'PyOS_snprintf'
                               value:   0x00
                               size:    0x00
                               binding: Type(STB_GLOBAL, 'Global symbol')
                               type:    Type(STT_NOTYPE, 'Symbol type is unspecified')
                               shndx:   0x00)])

Exceptions

exception libelf.ELFError

Raised when any ELF related error occurs.

exception libelf.LocateError

Raised when ldd was not able to locate a shared library.

Table Of Contents

Previous topic

The pylibelf package

Next topic

elf – convenience functions and settings

This Page