Reputation: 73
I've been trying to interpret an ar(the libglib-2.0.a) file using this struct here declared in ar.h
. Acording to the wiki the ending characters shoud be 0x60 and 0x0A, but what I got is 0x35 and 0x34, in fact the ending characters are actually 8 bytes ahead in the stream!
Here's the code:
#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;
}
Am I missing something?
Upvotes: 0
Views: 77
Reputation: 488
First of all, you miss the 8 bytes offset at the top.
#define ARMAG "!<arch>\n" /* String that begins an archive file. */
#define SARMAG 8 /* Size of that string. */
Then, you create a buffer of a bizarre size — 1000. That value makes absolutely no sense, we have a correct buffer size for it, which is the size of header itself — we know it statically, it's 60 bytes. Not to mention that to interpret the buffer as a correct struct, memory representation should be properly aligned.
Here's a working example, for the sake of brevity, error-checking is omitted.
#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, \%02hhx\n", header.ar_fmag[0], header.ar_fmag[1]);
return 0;
}
$ ./read
60, 0a
Upvotes: 3