The executable and linking format has been a popular topic lately, as people ask why the Kernel configuration script asks whether or not to configure loading elf executables. since elf will eventually be the common object file format for Linux binaries, it is appropriate to document it a bit. last month, Eric introduced us to elf, and this month, he gives us a guided tour of real elf files.
Last month, we reached a point where were beginning to dissect some real elf files. for this, I will use the readelf utility which I wrote when I was first trying to understand the ELF format itself. later on, it became a valuable tool for debugging the linker as I added support for elf. the sources to readelf shocould be on tsx-11.mit.edu in pub/Linux/packages/GCC/src or in pub/Linux/beta/ibcs2.
Let us start with a very simple program-the hello World program we used last month.
Largo % cat hello. c
Main (){
Printf ("Hello World/N ");
}
Largo % gcc-elf-C hello. c
On my laptop, the GCC-elf command invokes the elf version of GCC-once elf becomes the default format, you will be able to use the regular GCC command which produces the ELF File hello. o. each ELF file starts with a header (struct elfhdr in/usr/include/Linux/elf. h), and the readelf utility can display the contents of all of the fields:
Largo % readelf-H hello. o
Elf magic: 7f 45 4C 46 01 01 00 00 00 00 00 00 00 00 00
Type, machine, version = 1 3 1
Entry, phoff, shoff, flags = 0 0 440 0
Ehsize, phentsize, phnum = 52 0 0
Shentsize, shnum, shstrndx = 40 11 8
The elf magic field is just a way ofunambiguously identifying this as an elf file. if a file does not contain those 16 bytes in the magic field, it isnot an elf file. the type, machine, and version fields identify this as an et_rel file (I. E ., an object file) for the iworkflow. The ehsize field is just the sizeof (struct elfhdr ).
Each ELF file contains a table that describes the sections within the file. the shnum field indicates that there are 11 sections; the shoff field indicates that the section header table starts at byte offset 440 within the file. the shentsize field indicates that the entry for each section is 40 bytes long. all throughout elf, the sizes of various structures are always explicitly stated. this allows for flexibility; the structures can be expanded as required for some hardware platforms and the standard elf tools do not have to know about this to be able to make sense of the binary. also, it allows room for future expansion of the structures by newer versions of the standard.
Largo % readelf-s hello. o
There are 11 section headers, starting at offset 1b8:
[0] Null 00000000 00000 00000 0 0 0
[1]. Text progbits 00000000 00040 00014 00/6 0 0 10
[2]. Rel. Text rel 00000000 00370 00010 08/0 9 1 4
[3]. Data progbits 00000000 00054 00000 00/3 0 0 4
[4]. BSS nobits 00000000 00054 00000 00/3 0 0 4
[5]. note Note 00000000 00054 00014 00/0 0 0 1
[6]. rodata progbits 00000000 00068 running D 00/2 0 0 1
[7]. Comment progbits 00000000 00075 00012 00/0 0 0 1
[8]. shstrtab strtab 00000000 00087 0004d 00/0 0 0 1
[9]. symtab 00000000 000d4 000c0 10/0 A 4
[A]. strtab 00000000 00194 00024 00/0 0 0 1
Listing 1. Section Table for hello. o
Each section header is just a struct elf32_shdr. you may notice that the name field is just a number-this is not a pointer, but an offset into. shstrtab section (we can find the index of. shstrtab section from the file header in the shstrndx field ). thus we find the name of each section at the specified offset within. shstrtab section. let us dump the section table for this file; see figure 1. you will notice sections for nearly everything which we have already discussed. each section has an identifier which specifies what the section contains (in general, you shoshould never have to actually know the name of a section or compare it to anything ).
After the type, there is a series of numbers. the first of these is the address in virtual memory where this section shoshould be loaded. since this is. o file, it is not intended to be loaded into virtual memory, and this field is not filled in. next is the offset within the file of the Section, and then is the size of the Section. after this come a series of numbers-I won't parse these in detail for you, but they contain things like the required alignment of the section, A set of flags which indicate whether the section is read-only, writable, and/or executable.
The readelf program is capable of parameter Ming disassembly:
Largo % readelf-I 1 hello. o
0x00000000 pushl % EBP
0x00000001 movl % ESP, % EBP
0x00000003 pushl $0x0
0x00000008 call 0x08007559
0x0000000d addl $4, % ESP
0x00000010 movl % EBP, % ESP
0x00000012 popl % EBP
0x00000013 RET
The. Rel. text section contains the relocations for the. text section of the file, and we can display them as follows:
Largo % readelf-r hello. o
Relocation section data:. Rel. Text (0x2 entries)
Tag: 00004 value 00301 r_1__32 (0)
Tag: 00009 value 00b02 r_1__pc32 (0 printf)
This indicates that. text section has two relocations. as expected, there is a relocation for printf indicating that we must patch the address of printf into offset 9 from the beginning of. text section, which happens to be the operand of the call instruction. there is also a relocation so that we pass the correct address to printf.
Now let us see what happens when this file is linked into an executable. The section table now looks something like Listing 2.
The first thing you will notice is a lot more sections than were in the simple. o file. Much of this because this file requires the elf shared library libc. so.1.
At this point I shocould mention the mechanics of what happens when you run an elf program. the kernel looks through the binary and loads it into the user's virtual memory. if the application is linked to a shared library, the application will also contain the name of the dynamic linker that shoshould be used. the kernel then transfers control to the dynamic linker, not to the application. the dynamic loader is responsibile for first initializing itself, loading the shared libraries into memory, resolving all remaining relocations, and then transferring control to the application.
Going back to our executable,. interp section simply contains an ASCII string that is the name of the dynamic loader. currently this will always be/lib/Elf/ld-linux.so.1 (the dynamic loader itself is also an elf shared library ).
Next you will notice 3 sections, called. hash ,. dynsym, and. dynstr. this is a minimal symbol table used by the dynamic linker when timing Ming relocations. you will notice that these sections are mapped into virtual memory (the virtual address field is non-zero ). at the very end of the image are the regular symbol and string tables, and these are not mapped into virtual memory by the loader. the. hash section is just a hash table that is used so that we can quickly locate a given symbol in. dynsym Section, thereby avoiding a linear search of the symbol table. A given symbol can typically be located in one or two tries through the use of the hash table.
The next section I want to mention is. PLT section. this contains the jump table that is used when we call functions in the shared library. by default. PLT entries are all initialized by the linker not to point to the correct target functions, but instead to point to the dynamic loader itself. thus, the first time you call any given function, the dynamic loader looks up the function and fixes the target of. PLT so that the next time this. PLT slot is used we call the correct function. after making this change, the dynamic loader callthe function itself.
This feature is known as lazy symbol binding. the idea is that if you have lots of shared libraries, it cocould take the dynamic loader lots of time to look up all of the functions to initialize all of. PLT slots, so it wocould be preferable to defer binding addresses to the functions until we actually need them. this turns out to be a big win if you only end up using a small fraction of the functions in a shared library. it is possible to instruct the dynamic loader to bind addresses to all of. PLT slots before transferring control to the application-this is done by setting the environment variable ld_bind_now = 1 before running the program. this turns out to be useful in some cases when you are debugging a program, for example. also, I shocould point out that. PLT is in read-only memory. thus the addresses used for the target of the jump are actually stored in. got section. the. got also contains a set of pointers for all of the global variables that are used within a program that come from a shared library.
The. dynamic section contains some shorthand notes used by the dynamic loader. you will notice that the section table is not itself loaded into virtual memory, and in fact it wocould not be good for performance for the dynamic loader to have to try to parse it to figure out what needs to be done. the. dynamic section is essential tially just a distilled version of the section header table that contains just what is needed for the dynamic loader to do its job.
You will notice that since the section header table is not loaded into memory, neither the kernel nor the dynamic loader will be able to use that table when loading files into memory. A shorthand table of program headers is added to provide a distilled version of the Section table containing just the information required to load a file into memory. for the above file it looks something like:
Largo % readelf-l Hello
ELF file is executable
Entry point 0x8000400
There are 5 program headers, starting at offset 34:
PHP 0x00034 0x08000034 0x000a0 0x000a0 R E
Interp 0x000d4 0x080000d4 0x00017 0x00017 R
Requesting program Interpreter/
[/Lib/Elf/ld-linux.so.1]
Load 0x00000 0x08000000 0x00515 0x00515 R E
Load 0x00518 0x08001518 0x000cc 0x000d4 RW
Dynamic 0x0054c 0x0800154c 0x00098 0x00098 RW
Shared Library: [libc. so.4] 1
As you can see, the program header contains a pointer to the name of the dynamic loader, instructions on what portions of the file are to be loaded into virtual memory (and the virtual addresses they shocould be loaded to), the permissions of the segments of memory, and finally a pointer to. dynamic Section that the dynamic loader will need. note that the list of required shared libraries is stored in. dynamic section.
I will not pick apart an elf shared library for you here-libraries look quite similar to elf executables. If you are interested, you can get the readelf utility and pick apart your own libraries.
At the start of this article, I said one reason we were switching to ELF was that it was easier to build shared libraries with elf. I will now demonstrate how. Consider two files:
Largo % cat hello1.c
Main ()
{
Greet ();
}
Largo % Cat English. c
Greet ()
{
Printf ("Hello World/N ");
}
The idea is that we want to build a shared library from English. C, and link hello1 against it. The commands to generate the shared library are:
Largo % gcc-elf-FPIC-C English. c
Largo % gcc-elf-shared-O libenglish. So English. o
That's all there is to it. Now we compile and link the hello1 program:
Largo % gcc-elf-C hello1.c
Largo % gcc-elf-O hello1 hello1.o-L.-lenglish
And finally we can run the program. normally the dynamic loader only looks in certain locations for shared libraries, and the current directory is not one of the places it normally looks. thus to run the program, you can use a command like:
Largo % LD_LIBRARY_PATH = ../hello1
Hello World
The environment variable LD_LIBRARY_PATH tells the dynamic loader to look in additional places for the shared libraries (this feature is disabled for setuid programs for security reasons ).
To avoid having to specify LD_LIBRARY_PATH, you have several options. You cocould copy your shared library to/lib/Elf, but you can also link your program in the following way:
Largo % gcc-elf-O hello1 hello1.o // home/Joe/libenglish. So
Largo %./hello1
Hello World
To build more complicated shared libraries, the procedure is not really that much different. everything that you want to put into the shared library shocould be compiled with-FPIC; when you have compiled everything, you just link it all together with the GCC-shared command.
The procedure is so much simpler mainly because we bind addresses to functions at runtime. with. out libraries, the addresses are bound at link time. this means that lots of special care must be taken to ensure that. PLT and. got have sufficient room for future expansion and that we keep the variables at the same addresses from one version of the Library to the next. the tools for building. out Libraries help ensure all of this, but it makes the build procedure much more complicated.
Elf offers one further feature that is not easily available with. out. the dlopen () function can be used to dynamically load a shared library into the user's memory, and you are then able to call the dynamic loader to find symbols within this shared library-in other words, you can call functions that are defined in these modules. in addition, the dynamic loader is used to resolve any undefined symbols within the module itself.
This may be easiest to explain with an example. Given the following source file:
# Include <dlfcn. h>
Main (INT argc, char * argv [])
{
Void (* greeting )();
Void * module;
If (argc> 2) Exit (0 );
Module = dlopen (argv [1], rtld_lazy );
If (! Module) Exit (0 );
Greeting = dlsym (module, "Greet ");
If (greeting ){
(* Greeting )();
}
Dlclose (module );
}
You can compile, link, and run it (using the shared library English. So which was built earlier ):
Largo % gcc-elf-C hello2.c
Largo % gcc-elf-O hello2 hello2.o-LDL
Largo %./hello2./libenglish. So
Hello World
To expand this example a little bit, you cocould generate other modules with greetings in other languages. thus in theory, one cocould add multi-lingual support for some application merely by supplying a set of shared libraries that contain the language-specific portions of the application. in the above example, I showed how you can locate the address of a function within a shared library. but the dlsym () function will also return the address of data variables, So you coshould just as easily retrieve the address of a text string from the shared library.
As I prepare to close, I shocould mention some options to readelf which I have not demonstrated. readelf-s dumps the symbol tables and readelf-F dumps the. Dynamic section.
Finally, I shocould mention something about the timetable. when we first got elf to a point where it was usable (last September), we decided to spend a relatively long period of time testing it and shaking out all of the problems. back then I felt that roughly 4-to-6 months wocould allow people to test it thoroughly, plus we wanted to give an opportunity for certain applications to be adapted for ELF (the most recent versions of insmod and wine now support elf, for example ). as I write this, no firm date has been set for a public release, but it is possible that elf will be public by the time you read this.
In these articles I have attempted to give you a guided introduction to the ELF file format. A lot of the material I have covered is not of much practical value to most users (unless you want to hack the linker ), but my experience is that there are a lot of people who are curous about how it all works, and I hope that I have provided enough information to satisfy most people.
For more information about the ELF File Format, you can obtain the elf specifications from a number of sources-you can try ftp.intel.com in pub/tis/elf11g.zip. the specifications are also available in a printed format. see System V Application binary interface (ISBN 0-13-100439-5) and System V Application binary interface, intel386 architecture processor supplement (ISBN 0-13-104670-5 ).
Eric youngdale has worked with Linux for over three years, and has been active in kernel development. he developed the current. out Linux shared libraries before developing much of the new elf support. he can be reached as eric@aib.com.