bfd

Updating an object file using BFD interface


I have to add a symbol to an existing object file. I am presently trying with a elf32-i386 target. I tried opening the object file in read/write mode :

abfd = bfd_fopen ("test.o", "elf32-i386", "r+", -1);

I have no problem in reading the existing symbol table. I compared it with objdump output and it is fine. But when I add a new symbol to the existing asymbol** list and trying to set the new symbol table by calling `bfd_set_symtab(abfd, newsymtab, newsymtab_count), failure is returned.

Looking at syms.c file where bfd_set_symtab() is defined, it seems bfd object that is created using "write only" mode is allowed to set the symbol.

if (abfd->format != bfd_object || bfd_read_p (abfd))
{
      bfd_set_error (bfd_error_invalid_operation);
      return FALSE;
}

bfd_read_p (abfd) expands to : 
((abfd)->direction == read_direction || (abfd)->direction == both_direction)

"+" modes are both_direction.

I cannot open the object file in write mode as it will wipe out the existing data in the file. I am left with the only option of copying the BFD object created using read mode to another one created using write mode of a new output object file. Looked at the BFD interface and I am not able to see any api to copy/clone an existing BFD object. BFD documentation has a sample program to create a symbol table but it is in a new output object file. I want to update an existing object file.

Can anyone please tell how we can edit an object file using BFD interface for any one simple use case.

Many Thanks!


Solution

  • Figured about this myself. I referred objcopy utility code. copy_object() function does the task what I wanted. It does many extra stuffs based on the command line option. I had to throw away all those codes and retain only the core copy functions like setting up sections, copying the symbol table, copying relocations, copying the section contents and the private data. I can post the code if anybody is interested.