user1462787
user1462787

Reputation: 669

print the sections of elf

i need to write the function write_file: This function, write_file(int fdOut, char *start1, char *start2), receives a file descriptor for the output file and two pointers to ELF file structures which were mapped to memory. Loop over all section headers in the section header table, printing relevant fields (section name, offset, and length) to stdout (for debugging), and also write the respective section contents to the output file.

how do i "write the respective section contents to the output file" ? it's always copy 0 bytes...

this is what i wrote:void write_file(int fdOut, char *start_a, char *start_b) {

 char *start1=start_a;
 Elf32_Ehdr *header;
 Elf32_Shdr *curr;
 char *curr_name;
 int i;
 int c;


write(fdOut , start1 , 52);
start1=start_a;

header = (Elf32_Ehdr *)start1;

for(i=0 ; i< header->e_shnum ; i++){
  start1=start_a;
 curr= get_shdr_from_index(i, start1); /*returns a pointer to the requested section header**/
 curr_name=get_section_name(i, start1); /*returns a pointer into the section header string table.**/

 printf("[ %d ] %20s %20x %20x\n", i ,
           curr_name , curr->sh_offset , curr->sh_size);


 if (c=write(fdOut, curr, curr->sh_size)<0) {
  perror("error");
  exit(-1);
}
printf("%d" , c);

}

}

Upvotes: 1

Views: 3937

Answers (2)

Employed Russian
Employed Russian

Reputation: 213754

Your first bug is here:

if (c=write(fdOut, curr, curr->sh_size)<0) { ...

Read about operator precedence here. What you meant to write:

if ((c = write(fdOut, curr, curr->sh_size)) < 0) { ...

Your second bug is that you are asked to write section contents to fd. But you are writing section header, and not the contents. The contents is to be found in the original file, at offset curr->sh_offset. That data may not be present in memory at all, so you'll likely need to lseek in the original file to and read the data from there, before you can write the data to the output.

Upvotes: 1

Pavel Petrovich
Pavel Petrovich

Reputation: 764

Use the -O binary output format:

objcopy -O binary --only-section=.text foobar.elf foobar.text

Upvotes: 0

Related Questions