gpt4 book ai didi

尝试遍历共享库的符号表时导致 C 指针分段

转载 作者:行者123 更新时间:2023-11-30 15:11:42 29 4
gpt4 key购买 nike

我想知道是否有人能想到当指针处于以下状态时从指针读取如何导致分段的原因:1.非NULL指针。

我想做的事情是遍历共享库并访问它们的符号表。当我尝试访问 ELF 哈希表以获取符号表中的符号数量时,会发生分段。

这在 x86 平台中没有被注意到。仅在 MIPS64 平台上执行时才会发生。

代码基于此链接: How to interpret the dynamic symbol table in an ELF executable?

static void
btrace_dl_symtab_walk(struct dl_phdr_info *info,
btrace_dl_lib_t *ctx) {
ElfW(Dyn*) dyn;
ElfW(Sym*) sym = NULL;
ElfW(Word*) hash;

ElfW(Word) sym_cnt = 0;
char* strtab = NULL;
char* sym_name = NULL;
unsigned int i;
int j;

/*
* Make indicator to show all of them acomplished before going forward
*/

for (j = 0; j < info->dlpi_phnum; j++) {
if (info->dlpi_phdr[j].p_type == PT_DYNAMIC) {
dyn = (ElfW(Dyn)*)(info->dlpi_addr + info->dlpi_phdr[j].p_vaddr);
while(dyn->d_tag != DT_NULL) {
if (dyn->d_tag == DT_HASH) {
hash = (ElfW(Word*))dyn->d_un.d_ptr;
if (!hash) {
return;
}

/*
* SEGFAULT happens here
*/
printf("Before Seg Fault\n");
sym_cnt = *(hash + 1); //<=============== This line causes seg fault
printf("Never reached here\n");
} else if(dyn->d_tag == DT_GNU_HASH) {
/*
* Since there is no simply way to find entry count
* in GNU hash table, we have no choice but to
* count by hand
*/
uint32_t *buckets;
uint32_t *hashval;
hash = (ElfW(Word*))dyn->d_un.d_ptr;
buckets = hash + 4 + (hash[2]*sizeof(size_t)/4);
for (i = sym_cnt = 0; i < hash[0]; i++) {
if (buckets[i] > sym_cnt) {
sym_cnt = buckets[i];
}
}
if (sym_cnt) {
sym_cnt -= hash[1];
hashval = buckets + hash[0] + sym_cnt;
do {
sym_cnt++;
} while (!(*hashval++ & 1));
}
sym_cnt += hash[1];
}else if (dyn->d_tag == DT_STRTAB) {
strtab = (char*)dyn->d_un.d_ptr;
} else if (dyn->d_tag == DT_SYMTAB) {
sym = (ElfW(Sym*))dyn->d_un.d_ptr;
break;
}
dyn++;
}
break;
}
}

// Other acitivities
}

欢迎任何指导。谢谢

最佳答案

I was wondering if anyone can think of a reason how a read from a pointer could cause a segmentation when the pointer is: 1. non NULL pointer.

指针不是NULL这一事实意味着您可以从中读取内容。它可能因多种原因而无效,例如

char *p = mmap(...);
munmap(p, ...);

char c = p[0]; // p points into unmapped memory, SIGSEGV likely.

This is not noticed in x86 platform. It happens only when executing on MIPS64 platform.

您在两个平台上使用相同版本的 GLIBC 吗?

如果我没记错的话,旧版本的 GLIBC 没有重新定位 DT_HASH,但新版本会这样做。这也可能是特定于体系结构的。

您需要打印 hash 的值,并将其与 dyn 的值进行比较。如果hash很小,您需要通过info->dlpi_addr重新定位它。

关于尝试遍历共享库的符号表时导致 C 指针分段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35515217/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com