在代码中解释ar文件时出现问题



我一直在尝试使用ar.h中声明的这个结构来解释ar(libglib-2.0.a(文件。根据wiki,结束字符应该是0x60和0x0A,但我得到的是0x35和0x34,事实上,结束字符实际上在流中领先8个字节!这是代码:

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <elf.h>
#include <ar.h>

int main(){
int fd = open("libglib-2.0.a", O_RDONLY);
char b[1000];
read(fd, b, 1000);
ar_hdr *arS = (ar_hdr*) b;
int dummy = 0;
}

我是不是错过了什么?

首先,您错过了顶部的8字节偏移量。

#define ARMAG   "!<arch>n" /* String that begins an archive file.  */
#define SARMAG  8       /* Size of that string.  */

然后,创建一个奇怪大小的缓冲区——1000。这个值毫无意义,我们有一个正确的缓冲区大小,也就是头本身的大小——我们静态地知道,它是60字节。更不用说要将缓冲区解释为正确的结构,内存表示应该正确对齐。

这里有一个工作示例,为了简洁起见,省略了错误检查。

#include <stdio.h>
#include "unistd.h"
#include <fcntl.h>
#include <string.h>
#include "ar.h"
int main() {
int fd = open("/usr/lib/libc.a", O_RDONLY);
lseek(fd, SARMAG, SEEK_SET);
ssize_t bufSize = sizeof(struct ar_hdr);
char buf[bufSize];
read(fd, buf, bufSize);
struct ar_hdr header;
memcpy(&header, buf, bufSize);
printf("%02hhx, %02hhxn", header.ar_fmag[0], header.ar_fmag[1]);
return 0;
}
$ ./read
60, 0a

最新更新