2025 01 21 12 11 [C] elf64_checksum() 的範例程式


以下是用chatgpt 生成 elf64_checksum()的範例程式.
PS: 有再經過人工修改.

#include <stdio.h>
#include <fcntl.h>
#include <gelf.h>
#include <libelf.h>

int main(int argc, char *argv[]) {

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <ELF file>\n", argv[0]);
        return 1;
    }

    const char *elf_file = argv[1];

    if (elf_version(EV_CURRENT) == EV_NONE) {
        fprintf(stderr, "ELF library initialization failed: %s\n", elf_errmsg(-1));
        return 1;
    }

    int fd = open(elf_file, O_RDONLY);

    if (fd < 0) {
        perror("Failed to open ELF file");
        return 1;
    }

    Elf *elf = elf_begin(fd, ELF_C_READ, NULL);

    if (!elf) {
        fprintf(stderr, "elf_begin() failed: %s\n", elf_errmsg(-1));
        close(fd);
        return 1;
    }

    uint32_t checksum = elf64_checksum(elf);
    printf("Checksum: 0x%x\n", checksum);

    elf_end(elf);
    close(fd);
    return 0;
}

PS: readelf -d a.out
or objdump -p a.out
這可以顯示elf檔裡面的 dynamic section.
用來研究跟DT_CHECKSUM到底有什麼關係.
還有 ld.so --list-diagnostics.