Reputation: 143
I have a program that takes in command line arguments and a path to an elf file and displays the content of them using a struct. The elf header file is set up to have 16 bytes. Of those bytes, every two bytes describes something else about the header (version, entry point, etc) and the last four bytes hold a magic number that tells you it's the end of the file. The bytes are all in hex.
bool read_header (FILE *file, elf_hdr_t *hdr)
{
if (hdr != NULL && file != NULL && fread(hdr, sizeof(*hdr), 1, file) == 1)
{
fread(hdr, sizeof(*hdr), 1, file);
if (hdr->magic == 0x00464C45)
{
return true;
}
}
return false;
}
I am supposed to print out each bite from the struct on the same line in %x hexadecimal format
Here is the struct that I am storing the values into.
typedef struct __attribute__((__packed__)) elf {
uint16_t e_version; /* version should be 1 */
uint16_t e_entry; /* entry point of program */
uint16_t e_phdr_start; /* start of program headers */
uint16_t e_num_phdr; /* number of program headers */
uint16_t e_symtab; /* start of symbol table */
uint16_t e_strtab; /* start of string table */
uint32_t magic; /* ELF */
} elf_hdr_t;
I was told I could use a for loop but I don't know how. how do you suggest I do this?
I need to use the following method
void dump_header (elf_hdr_t hdr)
{
}
Upvotes: 0
Views: 88
Reputation: 154110
I am supposed to print out each bite from the struct on the same line in %x hexadecimal format
After reading the header once,
bool read_header (FILE *file, elf_hdr_t *hdr) {
if (hdr != NULL && file != NULL && fread(hdr, sizeof(*hdr), 1, file) == 1) {
// comment out next line
// fread(hdr, sizeof(*hdr), 1, file);
if (hdr->magic == 0x00464C45) {
return true;
}
}
return false;
}
... print its bytes contents. Cast the hdr
address to a unsigned char *
.
void dump_header(elf_hdr_t hdr) {
bool success = read_header(file, &hdr);
printf("Success %d\n", success);
for (size+t i = 0; i < sizeof hdr; i++) {
printf("%x ", ((unsigned char *)&hdr)[i]);
}
printf("\n");
}
Passing in elf_hdr_t *
is the more common C approach.
Upvotes: 1