#include <elf.h>
char* find_module_by_name(char *name){
FILE* fp = fopen("/proc/self/maps","r");
char line[1024] ={0};
char* ptr = NULL;
if(fp){
while (fgets(line,1024,fp)){
if(strstr(line,name)){
sscanf(line,"%p-%*p %*s %*s %*s %*s %*s",&ptr);
break;
}
}
fclose(fp);
}
return ptr;
}
void* my_dlsym( char* path, char* name){
char* base = find_module_by_name(path);
Elf32_Ehdr* elf_head = (Elf32_Ehdr*)base;
Elf32_Phdr* phead_table =(Elf32_Phdr*) (base+elf_head->e_phoff);
struct LoadableSegment{
size_t num=0;
size_t max_size =10;
Elf32_Phdr* segment[10];
}loadable_segment;
size_t loadable_segment_num = 0;
Elf32_Sym* sym;
char* shdr;
void* result = 0;
auto get_rel_addr = [&base,&loadable_segment](Elf32_Addr it){
for(int i=0;i<loadable_segment.num;i++){
if( it < loadable_segment.segment[i]->p_filesz){
return base+ it - (off_t)loadable_segment.segment[i]->p_vaddr + loadable_segment.segment[i]->p_offset ;
}
}
return (char*)NULL;
};
for(int i=0;i<elf_head->e_phnum;i++){
if(phead_table[i].p_type ==PT_LOAD){
if(loadable_segment_num>=loadable_segment.max_size){
continue;
}
loadable_segment.segment[loadable_segment.num] = phead_table+i;
loadable_segment.num++;
}
else if(phead_table[i].p_type ==PT_DYNAMIC){
Elf32_Dyn* dyn = (Elf32_Dyn*)get_rel_addr(phead_table[i].p_offset );
for(int j = 0;j < phead_table[i].p_memsz/phead_table[i].p_align;j++){
Elf32_Dyn* tmp = dyn+j;
if(dyn[j].d_tag == DT_SYMTAB ){
sym =(Elf32_Sym*)get_rel_addr(dyn[j].d_un.d_ptr);
}
if(dyn[j].d_tag == DT_STRTAB){
shdr = (char*)get_rel_addr(dyn[j].d_un.d_ptr);
}
}
break;
}
}
for (;(char*)sym<(char*)shdr;sym++){
char* ptr = shdr+sym->st_name;
if( strstr(ptr ,name)){
LOGD("sym->st_value %p",sym->st_value);
result =(void*) get_rel_addr(sym->st_value);
LOGD("result %p",result);
}
}
return result;
}
void test(){
char*(*GetJniNativeInterface)() =(char*(*)()) my_dlsym("libart.so","GetJniNativeInterface");
char* gJniNativeInterface = GetJniNativeInterface();
}
手动查找elf导出表函数
最新推荐文章于 2024-01-12 09:52:11 发布