首页 > 解决方案 > 精灵读符号

问题描述

我正在尝试从 .symtab 部分读取符号,但似乎我没有以正确的方式获取此部分。我一直在阅读规范并在线搜索一段时间。

为什么 symtab[i].st_name 为每个条目读取 0 ?我正在阅读的可执行文件有符号。


            Elf64_Half shdr_tab_size = ehdr->e_shentsize * ehdr->e_shnum;
            Elf64_Shdr shdr_tab[shdr_tab_size];

            rewind(infos.fp);
            fseek(infos.fp, ehdr->e_shoff, SEEK_SET);
            fread(&shdr_tab, 1, ehdr->e_shentsize * ehdr->e_shnum, infos.fp);

            char *shdr_names;
            shdr_names = malloc(shdr_tab[ehdr->e_shstrndx].sh_size);
            if (shdr_names != NULL) {
                fseek(infos.fp, shdr_tab[ehdr->e_shstrndx].sh_offset, SEEK_SET);
                fread(shdr_names, 1, shdr_tab[ehdr->e_shstrndx].sh_size, infos.fp);
            }

            Elf64_Shdr shdr_strtab = get_section_hdr(".strtab", shdr_tab, shdr_names, ehdr->e_shnum);
            Elf64_Shdr shdr_symtab = get_section_hdr(".symtab", shdr_tab, shdr_names, ehdr->e_shnum);

            if (shdr_symtab.sh_type == SHT_SYMTAB) {

                Elf64_Sym *symtab = malloc(shdr_symtab.sh_size);
                fseek(infos.fp, shdr_symtab.sh_offset, SEEK_SET);
                fread(symtab, 1, shdr_symtab.sh_size, infos.fp);

                char *strtab = malloc(shdr_strtab.sh_size);
                fseek(infos.fp, shdr_tab[shdr_symtab.sh_link].sh_offset, SEEK_SET);
                fread(strtab, 1, shdr_strtab.sh_size, infos.fp);

                // 10 is arbitrary, I did not figure out how to get the number of entries yet
                for (int i = 0; i < 10; i++) 
                printf("%s\n", strtab + symtab[i].st_name); // .stname reads 0
            }

编辑:

对于每一个symtab[i]这是我得到的。好像我在某个地方犯了一个错误...

我已经使用nm和其他工具进行了验证,以确保符号和名称定义明确。

在此处输入图像描述

标签: celf

解决方案


如果 st_name 为 0,则该条目没有手册中描述的名称

st_name
An index into the object file's symbol string table, which holds the character 
representations of the symbol names. If the value is nonzero, it represents a string table
index that gives the symbol name. Otherwise, the symbol table entry has no name.

某些条目在表的开头为 0 是正常的。

如果您确定存在带有名称的符号,请尝试阅读所有条目并查看是否正确找到它们。条目数为shdr_symtab.sh_size / sizeof(Elf64_Sym)

另外,替换shdr_tab[shdr_symtab.sh_link].sh_offsetshdr_strtab.sh_offset如下:

                char *strtab = malloc(shdr_strtab.sh_size);
                fseek(infos.fp, shdr_strtab.sh_offset, SEEK_SET);
                fread(strtab, 1, shdr_strtab.sh_size, infos.fp);

推荐阅读