在C中查找elf的文本部分

问题描述 投票:1回答:1

获取Elf文件的文本部分并显示其内容的正确方法是什么?我已经尝试过自己做,但是它只显示250位数据,但是当我使用readelf命令尝试时,它显示的内容更多。我想我只是弄错了偏移量以获得该部分。什么是正确的方法?

代码:

    Elf32_Ehdr elfHdr;
    Elf32_Shdr sectHdr;
    FILE* ElfFile = NULL;
    char* SectNames = NULL;

    if(argc != 2) {
        perror("Chose file!");
        return -1;
    }   



    ElfFile = fopen(argv[1],"r");
    if(ElfFile == NULL) {
        printf("Error opening file");
        return -1;
    }

    fread(&elfHdr, 1, sizeof(Elf32_Ehdr), ElfFile);


    fseek(ElfFile, elfHdr.e_shoff + elfHdr.e_shstrndx * elfHdr.e_shentsize, SEEK_SET);
    fread(&sectHdr, 1, sizeof(sectHdr), ElfFile);
    SectNames = malloc(sectHdr.sh_size);
    fseek(ElfFile, sectHdr.sh_offset, SEEK_SET);
    fread(SectNames, 1, sectHdr.sh_size, ElfFile);

    printf("\nSECTION HEADERS:\n\n");

    for (int idx = 0; idx < elfHdr.e_shnum; idx++){
        char* name = "";

        fseek(ElfFile, elfHdr.e_shoff + idx * sizeof(sectHdr), SEEK_SET);
        fread(&sectHdr, 1, sizeof(sectHdr), ElfFile);

        // print section name
        if (sectHdr.sh_name);
        name = SectNames + sectHdr.sh_name;

        printf("%i %s\n", idx, name);
    }


    printf("\nTEXT SECTION (start: 0x%lx):\n\n", elfHdr.e_entry);
    printf("Section size: %i\n\n", sectHdr.sh_size);

    fseek(ElfFile, elfHdr.e_entry, SEEK_SET);

    for(int i=0; i < sectHdr.sh_size; i = i+32) {
        int value;
        fseek(ElfFile, sectHdr.sh_addr + i, SEEK_SET);
        fread(&value, 1, sizeof(value), ElfFile);
        printf("0x%x\n", value);
    }

    fclose(ElfFile);

c elf
1个回答
1
投票

我想我刚弄错了偏移量以获得该部分。

您的程序遍历所有节,因此在第一个循环的末尾,sectHdr包含last节的节头,.text节不太可能。

因此,在第二个循环中,您将打印最后一个节的内容。

要打印.text部分,遇到它时,需要保存其部分标题。

更新:

因此,如果我在所有节中进行循环,然后使用每个名称进行strcmp,并且当发现与.text匹配时,我将保存该标头的地址。

您不保存该标头的地址-您保存内容

如果我要访问不是Section(具有自己的类型:Elf32_Sym)的Symbol表,该怎么办?

符号表does有其自己的部分(包含一组Elf32_Sym记录)。参见此answer

© www.soinside.com 2019 - 2024. All rights reserved.