我正在尝试读取 Elf 文件的第一个字节

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

我正在编写 C 代码来读取 ELF 文件的前 4 个字节并将其与 0x7f 进行比较以查看我是否得到匹配但它似乎不起作用。我做错了什么?

#include "main.h"
/**
 * readFirst4 - function to read first eight bytes
 * @filename: filename of file to be read
 * Return: string of bytes to be checked
 */
char *readFirst4(int fd_elf)
{
        unsigned int _read1;
        char *test_string;

        _read1 = read(fd_elf, test_string, sizeof(int));
        if (_read1 != 0 && _read1 != -1)
                return (test_string);
        else
                return ("Error unable to read file\n");
}

/**
 * closeFile - function that closes a file
 * @fd_elf: file descriptor
 */
void closeFile(int fd_elf, char *filename)
{
        if((close(fd_elf) == -1))
        {
                dprintf(STDERR_FILENO, "Error: unable to close file %s\n", filename);
                exit(98);
        }
}

/**
 * main - execute program
 * @argc: number of arguments
 * @args: array of arguments
 * Return: 0
 */
int main(int argc,char **argv)
{
        int fd_ELF, reader;
        char *first_four;

        first_four = malloc(sizeof(int));
        if (first_four == NULL)
                exit(98);

        if (argc != 2)
        {
                dprintf(STDERR_FILENO, "Usage: elf_header filename\n");
                exit(98);
        }

        fd_ELF = open(argv[1], O_RDONLY);
        if (fd_ELF == -1)
        {
                dprintf(STDERR_FILENO, "Error unable to read file %s\n", argv[1]);
                exit(98);
        }
        if ((first_four = readFirst4(fd_ELF)) != (char *)0x7F)
        {
                printf("%s\n", first_four);
                dprintf(STDERR_FILENO, "Error: Not an ELF file - it has the wrong magic bytes at the start\n");
                exit(98);
        }
        printf("file %s is an ELF file", argv[1]);
        closeFile(fd_ELF, argv[1]);
        return (0);
}                        

根据我的代码,如果文件不是 elf 文件,错误消息只应该显示。

我在错误之前包含了 printf 以查看读取的字节。我不断得到一个?框内的符号,然后是错误消息,因为读取的字节与 0x7f 不匹配,这是 elf 的第一个字节

c io elf
1个回答
0
投票

你的实现看起来真的很复杂。尝试使用下面的结构。

int main(int argc, const char ** argv) {
  // program argument checks

  // open file
  int fd = open(argv[1], O_RDONLY);
  // file discriptor checks
  char ref[4] = {0x7f, 0x45, 0x4c, 0x46};
  char arr[4];
  int cnt = read(fd, (char*) &arr, sizeof(char) * 4);
  // read check
  // expected values in arr is 0x7f 0x45 0x4c 0x46
  int cmp = memcmp((char*)&arr, (char*)&ret, 4 * sizeof(char));
  if(cmp == 0) {
    // ELF file found
  }
  close(fd);
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.