ELF Tutorial: Difference between revisions

m
Bot: Replace deprecated source tag with syntaxhighlight
[unchecked revision][unchecked revision]
m (Bot: Replace deprecated source tag with syntaxhighlight)
m (Bot: Replace deprecated source tag with syntaxhighlight)
 
Line 5:
==ELF Data Types==
 
<sourcesyntaxhighlight lang="cpp">
# include <stdint.h>
 
Line 13:
typedef uint32_t Elf32_Word; // Unsigned int
typedef int32_t Elf32_Sword; // Signed int
</syntaxhighlight>
</source>
 
The ELF file format is made to function on a number of different architectures, many of which support different data widths. For support across multiple machine types, the ELF format provides a set of guidelines for fixed width types that make up the layout of the section and data represented within object files. You may choose to name your types differently or use types defined in stdint.h directly, but they should conform to those shown above.
Line 376:
While the BSS is one specific example, any section that is of type '''SHT_NOBITS''' and has the attribute '''SHF_ALLOC''' should be allocated early on during program loading. Since this tutorial is intended to be general and unspecific, the example below will follow the trend and use the simplest example for allocating sections.
 
<sourcesyntaxhighlight lang="cpp">
static int elf_load_stage1(Elf32_Ehdr *hdr) {
Elf32_Shdr *shdr = elf_sheader(hdr);
Line 403:
return 0;
}
</syntaxhighlight>
</source>
 
The example above allocates as much memory as necessary for the section, described by the '''sh_size''' field of the section's header. Although the function in the example only seeks out sections that needs to be allocated, it can be modified to perform other operation that should be performed early on into the loading process.
Line 445:
Loading a relocatable ELF file entails processing all relocation entries present in the file (Remember to alloc allocate all '''SHT_NOBITS''' sections first!). This process starts with finding all the relocation tables in the file, which is done in the example code below.
 
<sourcesyntaxhighlight lang="cpp">
# define ELF_RELOC_ERR -1
 
Line 472:
return 0;
}
</syntaxhighlight>
</source>
 
Note that the code above only processes '''Elf32_Rel''' entries, but it can be modified to process entries with explicit addends as well. The code also relies on a function called '''elf_do_reloc''' which will be shown in the next example. This example function stops, displays an error message, and returns an error code if it's unable to process a relocation.