elf_begin.3e (2010 09)

e
elf_begin(3E) elf_begin(3E)
limits the number of open files, the program can use
elf_cntl() to let it reuse file descriptors. After
calling
elf_cntl() with appropriate arguments, the program may close the file descriptor without
interfering with the library.
All data associated with an ELF descriptor remain allocated until
elf_end() terminates the
descriptor’s last activation. After the descriptors have been terminated, the storage is released; attempt-
ing to reference such data gives undefined behavior. Consequently, a program that deals with multiple
input (or output) files must keep the ELF descriptors active until it finishes with them.
Note
When a program calls
elf_begin() on a COFF file, the library translates COFF structures to their
ELF equivalents, allowing programs to read (but not to write) a COFF file as if it were ELF. This conver-
sion happens only to the memory image and not to the file itself.
EXAMPLES
A prototype for reading a file appears below. If the file is a simple object file, the program executes the
loop one time, receiving a null descriptor in the second iteration. In this case, both
elf and arf will
have the same value, the activation count will be two, and the program calls
elf_end() twice to ter-
minate the descriptor. If the file is an archive, the loop processes each archive member in turn, ignoring
those that are not object files.
if (elf_version(EV_CURRENT) == EV_NONE)
{
/* library out of date */
/* recover from error */
}
cmd = ELF_C_READ;
arf = elf_begin(fildes, cmd, (Elf *)0);
while ((elf = elf_begin(fildes, cmd, arf)) != 0)
{
if ((ehdr = elf32_getehdr(elf)) != 0)
{
/* process the file ...*/
}
cmd = elf_next(elf);
elf_end(elf);
}
elf_end(arf);
Alternatively, the next example illustrates random archive processing. After identifying the file as an
archive, the program repeatedly processes archive members of interest. For clarity, this example omits
error checking and ignores simple object files. Additionally, this fragment preserves the ELF descriptors
for all archive members, because it does not call
elf_end() to terminate them.
elf_version(EV_CURRENT);
arf = elf_begin(fildes, ELF_C_READ, (Elf *)0);
if (elf_kind(arf) != ELF_K_AR)
{
/* not an archive */
}
/* initial processing */
/* set offset =...fordesired member header */
while (elf_rand(arf, offset) == offset)
{
if ((elf = elf_begin(fildes, ELF_C_READ, arf)) == 0)
break;
if ((ehdr = elf32_getehdr(elf)) != 0)
{
/* process archive member ...*/
}
/* set offset =...fordesired member header */
}
The following outline shows how one might create a new ELF file. This example is simplified to show the
overall flow.
2 Hewlett-Packard Company 2 HP-UX 11i Version 3: September 2010