c-如何打印整个ELF文件头及其所有信息



我必须打印ELF文件头。它包含的所有数据,就像运行readelf-hhello.bin时一样。程序在C中。这就是我现在所拥有的:

typedef struct elf64_hdr {
unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */
Elf64_Half e_type;
Elf64_Half e_machine;
Elf64_Word e_version;
Elf64_Addr e_entry;       /* Entry point virtual address */
Elf64_Off e_phoff;        /* Program header table file offset */
Elf64_Off e_shoff;        /* Section header table file offset */
Elf64_Word e_flags;
Elf64_Half e_ehsize;
Elf64_Half e_phentsize;
Elf64_Half e_phnum;
Elf64_Half e_shentsize;
Elf64_Half e_shnum;
Elf64_Half e_shstrndx;
} Elf64_Ehdr;
typedef struct elf64_shdr {
Elf64_Word sh_name;       /* Section name, index in string tbl */
Elf64_Word sh_type;       /* Type of section */
Elf64_Xword sh_flags;     /* Miscellaneous section attributes */
Elf64_Addr sh_addr;       /* Section virtual addr at execution */
Elf64_Off sh_offset;      /* Section file offset */
Elf64_Xword sh_size;      /* Size of section in bytes */
Elf64_Word sh_link;       /* Index of another section */
Elf64_Word sh_info;       /* Additional section information */
Elf64_Xword sh_addralign; /* Section alignment */
Elf64_Xword sh_entsize;   /* Entry size if section holds table */
} Elf64_Shdr;

这些就是结构。以下是主要声明的变量:

FILE* ElfFile = NULL;
char* SectNames = NULL;
Elf64_Ehdr elfHdr;
Elf64_Shdr sectHdr;
uint32_t idx;

以下是需要您帮助的打印代码的相关部分:

// read ELF header, first thing in the file
fread(&elfHdr, 1, sizeof(Elf64_Ehdr), ElfFile); 
SectNames = malloc(sectHdr.sh_size); //variable for section names (like "Magic", "Data" etc.)
fseek(ElfFile, sectHdr.sh_offset, SEEK_SET); //going to the offset of the section
fread(SectNames, 1, sectHdr.sh_size, ElfFile); //reading the size of section
for(int i=0; i<sectHdr.sh_size; i++)
{
char *name1 = "";
fseek(ElfFile, elfHdr.e_shoff + i*sizeof(sectHdr), SEEK_SET);
fread(&sectHdr, 1, sizeof(sectHdr), ElfFile);
name1 = SectNames + sectHdr.sh_name;
printf("%s n", name1);
}

该代码编译但不打印任何内容。我本想把字符串打印成";Magic"数据"类";等等。

不能使用+运算符在C.中添加字符串

此行:

char *name1 = "";

意味着name1指向一个空的常量字符串
它不会为您可以添加字符串的某些字符串对象分配内存。

所以这个代码:

name1 = SectNames + sectHdr.sh_name;

只需在name1中放入一个垃圾值(某个数字(,这将导致未定义的行为(您的程序可能崩溃、不打印任何内容或打印随机字符(。

要打印分区名称,您需要这样的代码:

printf("Section name: %un", sectHdr.sh_name);

这将把sectHdr.sh_name中的值格式化为文本并输出到屏幕上。

您必须对所有其他字段逐个执行类似的操作,但必须注意字段类型并使用正确的格式说明符。

CCD_ 5表示";无符号整数";这是CCD_ 7所具有的最接近CCD_
仔细检查其他类型和合适的说明符!

最新更新