For a shared library file, how to convert between the file offset and virtual address of the definition of a symbol?
In ELF document, for a symbol in a symbol table,
In executable and shared object files,
st_value
holds a virtual address. To make these files' symbols more useful for the dynamic linker, the section offset (file interpretation) gives way to a virtual address (memory interpretation) for which the seciton number is irrelevant.
But how can I get the according offset in the file? Or given an offset, how can I calculate the virtual address(file interpretation to memory interpretation)?
Imagine a scenario like this. During the execution of a process, suppose it is using a function implemented in a shared library, say libx.so, and that the library file is mapped into a region represented by vma
.
//addr holds the value of PC
offset = (vma->vm_pgoff << PAGE_SIZE) + addr -vma->vm_start;
As I understand it, now offset
holds the offset of the instruction in the library file. Given this offset, I'd like to know the function name. One way is to calculate the the virtual address corresponding to offset
, and compare the virtual address with the st_value
s in the symbol table. If st_value
s are processed to be stored in ascending order, then st_value_1 < virtual_address < st_value_2
means st_name_1 is what I'm looking for. So the problem lies in the conversion.
For reference, data structure of a symbol table entry is:
typedef struct{
Elf32_Word st_name;
Elf32_Addr st_value;
Elf32_Word st_size;
unsigned char st_info;
unsigned char st_other;
Elf32_Half st_shndx;
}Elf32_Sym;