The code to load an ELF binary into Sim386 is incorporated into the class ELFMemory of Sim386. This class is discussed in section 3.1 and shown in Figure 3.1. We parsed the ELF executable using the routines provided in the ELF access library, libelf. We present an example of parsing an ELF executable in the remainder of this section.
Figure 3.6 contains sample code to find the text segment in an ELF executable file. The ELF access library provides a function to determine if the ELF versions of the access library and the ELF object file are compatible. Once this determination is made, we then obtain an ELF descriptor. This provides a unique handle to the ELF object file. We obtain a pointer to the ELF header by using the elf32_getehdr() routine. The ELF header provides a map of the rest of the file. With it, we can obtain pointers to the section header table and the program header table. In this example, we retrieve the pointer to the program header table from the ELF header pointer using the elf32_getphdr(). As discussed in section 2.4.1, the program header is an array of structures where each one describes a segment. Thus, we iterate through these entries until we find the structure whose p_type and p_flags indicate that the segment is the text segment. The p_type and p_flags are shown in the structure in Figure 2.7 as the first and seventh field in the structure. Once the entry has been found that contains the text segment, the text segment can be read from the file, using conventional methods, with the location in the file and size of the text segment acquired from the program table entry structure.