Initializing libelf

This topic describes how the consumer application initializes libelf to process the information within an ELF object file.

Steps to initialize libelf

  1. Identify the ELF object file containing the data to be used.
  2. Create an ELF descriptor to represent the data in the file.

The application uses the elf_begin operation to create an ELF descriptor. This operation requires a file descriptor for the ELF object file. For example, the application is given the name of the file from a command line parameter. It then acquires the descriptor with the following code:

fd = open(opts.file_name, O_RDONLY);

Then validate the libelf interface, using the following code:

elf_version(EV_NONE);
if (elf_version(EV_CURRENT) == EV_NONE) {
  /* libelf interface is out of date */
}

Then create an ELF descriptor with the given ELF object file, using the following code:

Elf_Cmd cmd = ELF_C_READ;
Elf *elf;
elf = elf_begin(fd, cmd, NULL);
Note: Other operations that can be used are elf_begin_b and elf_begin_c. Consult the libelf documentation for details on using these operations.

To determine if the input ELF object file is a well-formed ELF object file, use the elf_getident operations. For example:

 char *ehdr_ident = NULL;
 ehdr_ident = elf_getident(elf, NULL);
 if (ehdr_ident[0] == '\x7f' &&
     ehdr_ident[1] == '\x45' &&  // 'E'
     ehdr_ident[2] == '\x4C' &&  // 'L'
     ehdr_ident[3] == '\x46') {  // 'F'
   /* This is a valid ELF object file */
 }

To determine if the ELF descriptor represents a 32-bit ELF object or a 64-bit ELF object. It uses the elf32_getehdr and elf64_getehdr operations. For example:

Elf32_Ehdr *eh32; 
Elf64_Ehdr *eh64; 
eh32 = elf32_getehdr(elf); 
eh64 = elf64_getehdr(elf);
After this sequence the ELF descriptor has been identified as:
  • 32 bit if eh32 is not NULL
  • 64 bit if eh32 is NULL, and eh64 is not NULL
  • Unknown if eh32 and eh64 are both NULL

If the processing was successful, then elf contains the ELF descriptor object which is used to interfact with libdwarf.