* remove "\r" nonsense
[mascara-docs.git] / C / web / elf-object / page.txt
blob2afdc0db6c28ae3b7f453f4c0c5d6f12569e4dd7
1 Quantcast
2 Username/Email: [               ] Password: [               ] [Login] 
3 Register | Forgot your password?
4 TwitterFacebookFlickrRSS
5 Skip to Navigation
6 Linux Journal
7 Home ›
9 The ELF Object File Format: Introduction
11 Issue 12
13 From Issue #12
14 April 1995
16 Apr 01, 1995  By Eric Youngdale
17  in
19   • Software
21 The Executable and Linking Format (ELF) has been a popular topic lately. People
22 wonder why the kernel configuations script asks whether or not to donfigure
23 loading ELF executables. As ELF will eventually be the common object file
24 format for Linux binaries, it is appropriate to document it a bit. This month,
25 Eric introduces us to ELF, and next month he will give us a guided tour of real
26 ELF files.
28 Now that we are on the verge of a public release of ELF file format compilers
29 and utilities, it is a logical time to explain the differences between a.out
30 and ELF, and discuss how they will be visible to the user. As long as I am at
31 it, I will also guide you on a tour of the internals of the ELF file format and
32 show you how it works. I realize that Linux users range from people brand new
33 to Unix to people who have used Unix systems for years—for this reason I will
34 start with a fairly basic explanation which may be of little use to the more
35 experienced users, because I would like this article to be useful in some way
36 to as many people as possible.
38 People often ask why we are bothering with a new file format. A couple reasons
39 come to mind—first, the current shared libraries can be somewhat cumbersome to
40 build, especially for large packages such as the X Window System that span
41 multiple directories. Second, the current a.out shared library scheme does not
42 support the dlopen() function, which allows you to tell the dynamic loader to
43 load additional shared libraries. Why ELF? The Unix community seems to be
44 standardizing this file format; various implementations of SVr4 such as MIPS,
45 Solaris, Unixware currently use ELF; SCO will reportedly switch to ELF in the
46 near future; and there are rumors of other vendors switching to ELF. One
47 interesting sidenote—Windows NT uses a file format based upon the COFF file
48 format, the SVr3 file format that the Unix community is abandoning in favor of
49 ELF.
51 Let us start at the beginning. Users will generally encounter three types of
52 ELF files—.o files, regular executables, and shared libraries. While all of
53 these files serve different purposes, their internal structure files are quite
54 similar. Thus we can begin with a general description, and proceed to a
55 discussion of the specifics of the three file types. Next month, I will
56 demonstrate the use of the readelf program, which can be used to display and
57 interpret various portions of ELF files.
59 One universal concept among all different ELF file types (and also a.out and
60 many other executable file formats) is the notion of a section. This concept is
61 important enough to spend some time explaining. Simply put, a section is a
62 collection of information of a similar type. Each section represents a portion
63 of the file. For example, executable code is always placed in a section known
64 as .text; all data variables initialized by the user are placed in a section
65 known as .data; and uninitialized data is placed in a section known as .bss
67 In principle, one could devise an executable file format where everything is
68 jumbled together—MS-DOS binaries come to mind. But dividing executables into
69 sections has important advantages. For example, once you have loaded the
70 executable portions of an executable into memory, these memory locations need
71 not change. (In principle, program executable code could modify itself, but
72 this is considered to be extremely poor programming practice.) On modern
73 machine architectures, the memory manager can mark portions of memory
74 read-only, such that any attempt to modify a read-only memory location results
75 in the program dying and dumping core. Thus, instead of merely saying that we
76 do not expect a particular memory location to change, we can specify that any
77 attempt to modify a read-only memory location is a fatal error indicating a bug
78 in the application. That being said, typically you cannot individually set the
79 read-only status for each byte of memory—instead you can individually set the
80 protections of regions of memory known as pages. On the i386 architecture the
81 page size is 4096 bytes—thus you could indicate that addresses 0-4095 are
82 read-only, and bytes 4096 and up are writable, for example.
84 Given that we want all executable portions of an executable in read-only memory
85 and all modifiable locations of memory (such as variables) in writable memory,
86 it turns out to be most efficient to group all of the executable portions of an
87 executable into one section of memory (the .text section), and all modifiable
88 data areas together into another area of memory (henceforth known as the .data
89 section).
91 A further distinction is made between data variables the user has initialized
92 and data variables the user has not initialized. If the user has not specified
93 the initial value of a variable, there is no sense wasting space in the
94 executable file to store the value. Thus, initialized variables are grouped
95 into the .data section, and uninitialized variables are grouped into the .bss
96 section, which is special because it doesn't take up space in the file—it only
97 tells how much space is needed for uninitialized variables.
99 When you ask the kernel to load and run an executable, it starts by looking at
100 the image header for clues about how to load the image. It locates the .text
101 section within the executable, loads it into the appropriate portions of
102 memory, and marks these pages as read-only. It then locates the .data section
103 in the executable and loads it into the user's address space, this time in
104 read-write memory. Finally, it finds the location and size of the .bss section
105 from the image header, and adds the appropriate pages of memory to the user's
106 address space. Even though the user has not specified the initial values of
107 variables placed in .bss, by convention the kernel will initialize all of this
108 memory to zero.
110 Typically each a.out or ELF file also includes a symbol table. This contains a
111 list of all of the symbols (program entry points, addresses of variables, etc.)
112 that are defined or referenced within the file, the address associated with the
113 symbol, and some kind of tag indicating the type of the symbol. In an a.out
114 file, this is more or less the extent of the information present; as we shall
115 see later, ELF files have considerably more information. In some cases, the
116 symbol tables can be removed with the strip utility. The advantage is that the
117 executable is smaller once stripped, but you lose the ability to debug the
118 stripped binary. With a.out it is always possible to remove the symbol table
119 from a file, but with ELF you typically need some symbolic information in the
120 file for the program to load and run. Thus, in the case of ELF, the strip
121 program will remove a portion of the symbol table, but it will never remove all
122 of the symbol table.
124 Finally, we need to discuss the concept of relocations. Let us say you compile
125 a simple “hello world” program:
127  main( )
129         printf("Hello World\n");
132 The compiler generates an object file which contains a reference to the
133 function printf . Since we have not defined this symbol, it is an external
134 reference. The executable code for this function will contain an instruction to
135 call printf, but in the object code we do not yet know the actual location to
136 call to perform this function. The assembler notices that the function printf
137 is external, and it generates a relocation, which contains several components.
138 First, it contains an index into the symbol table—this way, we know which
139 symbol is being referenced. Second, it contains an offset into the .text
140 section, which refers to the address of the operand of the call instructions.
141 Finally, it contains a tag which indicates what type of relocation is actually
142 present. When you link this file, the linker walks through the relocations,
143 looks up the final address of the external function printf, then patches this
144 address back into the operand of the call instruction so the call instruction
145 now points to the actual function print.
147 a.out executables have no relocations. The kernel loader cannot resolve any
148 symbols and will reject any attempt to run such a binary. An a.out object file
149 will of course have relocations, but the linker must be able to fully resolve
150 these to generate a usable executable.
152 So far everything I have described applies to both a.out and ELF. Now I will
153 enumerate the shortcomings of a.out so that it is more clear why we would want
154 to switch to ELF.
156 First, the header of an a.out file (struct exec, defined in /usr/include/linux/
157 a.out.h) contains limited information. It only allows the above-described
158 sections to exist and does not directly support any additional sections.
159 Second, it contains only the sizes of the various sections, but does not
160 directly specify the offsets within the file where the section starts. Thus the
161 linker and the kernel loader have some unwritten understanding about where the
162 various sections start within a file. Finally, there is no built-in shared
163 library support—a.out was developed before shared library technology was
164 developed, so implementations of shared libraries based on a.out must abuse and
165 misuse some of the existing sections in order to accomplish the tasks required.
167 About 6 months ago, the default file format switched from ZMAGIC to QMAGIC
168 files. Both of these are a.out formats, and the only real difference is the
169 different set of unwritten understandings between the linker and kernel. Both
170 formats of executable have a 32 byte header at the start of the file, but with
171 ZMAGIC the .text section starts at byte offset 1024, while with QMAGIC the
172 .text section starts at the beginning of the file and includes the header. Thus
173 ZMAGIC wastes disk space, but, more importantly, the 1024 byte offset used with
174 ZMAGIC makes efficient buffer cache management within the kernel more
175 difficult. With a QMAGIC binary, the mapping from the file offset to the block
176 representing a given page of memory is more natural, and should allow for some
177 performance enhancements in the kernel. ELF binaries are also formatted in a
178 natural way that is compatible with possible future changes to the buffer
179 cache.
181 I have said that shared library support in a.out is lacking—while this is true,
182 it is not impossible to design shared library implementations that work with
183 a.out. The current Linux shared libraries are certainly one example; another
184 example is SunOS-style shared libraries which are currently used by BSD-du-jour
185 . SunOS-style shared libraries contain a lot of the same concepts as ELF shared
186 libraries, but ELF allows us to discard some of the really silly hacks that
187 were required to piggyback a shared library implementation onto a.out.
189 Before we go into our hands-on description of how ELF works, it would be
190 worthwhile to spend a little time discussing some general concepts related to
191 shared libraries. Then when we start to pick apart an ELF file, it will be
192 easier to see what is going on.
194 First, I should explain a little bit about what a shared library is; a
195 surprising number of people look at shared libraries as sort of black boxes
196 without a good understanding of what goes on inside. Most users are at least
197 aware of the fact that if they mess up their shared libraries, the system can
198 become nearly unusable. This leads most people to treat them with a certain
199 reverence.
201 If we step back a little bit, we recall that non-shared libraries (also known
202 as static libraries) contain useful procedures that programs might wish to make
203 use of. Thus the programmer does not need to do everything from scratch, but
204 can use a set of standard well-defined functions. This allows the programmer to
205 be more productive. Unfortunately, when you link against a static library, the
206 linker must extract all library functions you require and make them part of
207 your executable, which can make it rather large.
209 The idea behind a shared library is that you would somehow take the contents of
210 the static library (not literally the contents, but usually something generated
211 from the same source tree), and pre-link it into some kind of special
212 executable. When you link your program against the shared library, the linker
213 merely makes note of the fact that you are calling a function in a shared
214 library, so it does not extract any executable code from the shared library.
215 Instead, the linker adds instructions to the executable which tell the startup
216 code in your executable that some shared libraries are also required, so when
217 you run your program, the kernel starts by inserting the executable into your
218 address space, but once your program starts up, all of these shared libraries
219 are also added to your address space. Obviously some mechanism must be present
220 for making sure that when your program calls a function in the shared library,
221 it actually branches to the correct location within the shared library. I will
222 be discussing the mechanics of this for ELF in a little bit.
224 More info about ELF
226 Now that we have explained shared libraries, we can start to discuss some of
227 the general concepts related to how shared libraries are implemented under ELF.
228 To begin with, ELF shared libraries are position independent. This means that
229 you can load them more or less anywhere in memory, and they will work. The
230 current a.out shared libraries are known as fixed address libraries: each
231 library has one specific address where it must be loaded to work, and it would
232 be foolish to try to load it anywhere else. ELF shared libraries achieve their
233 position independence in a couple of ways. The main difference is that you
234 should compile everything you want to insert into the shared library with the
235 compiler switch -fPIC. This tells the compiler to generate code that is
236 designed to be position independent, and it avoids referencing data by absolute
237 address as much as possible.
239 Position independence does not come without a cost, however. When you compile
240 something to be PIC, the compiler reserves one machine register ( %ebx on the
241 i386) to point to the start of a special table known as the global offset table
242 (or GOT for short). That this register is reserved means that the compiler will
243 have less flexibility in optimizing code, and this means that it will take
244 longer to do the same job. Fortunately, our benchmark indicates that for most
245 normal programs the drop in performance is less than 3% for a worst case, and
246 in many cases much less than this.
248 Another ELF feature is that its shared libraries resolve symbols and externals
249 at run time. This is done using a symbol table and a list of relocations which
250 must be performed before the image can start to execute. While this sounds like
251 it could be slow, a number of optimizations built into ELF make it fairly fast.
252 I should mention that when you compile PIC code into a shared library, there
253 are generally very few relocations, one more reason why the performance impact
254 is not of great concern. Technically, it is possible to generate a shared
255 library from code that was not compiled with -fPIC, but an incredible number of
256 relocations would need to be performed before the shared library was usable,
257 another reason why -fPIC is important.
259 When you reference global data within a shared library, the assembly code
260 cannot simply load the value from memory the way you would do with non-PIC
261 code. If you tried this, the code would not be position independent and a
262 relocation would be associated with the instruction where you were attempting
263 to load the value from the variable. Instead, the compiler/assembler/linker
264 create the GOT, which is nothing more than a table of pointers, one pointer for
265 each global variable defined or referenced in the shared library. Each time the
266 library needs to reference a given variable, it first loads the address of the
267 variable from the GOT (remember that the address of the GOT is always stored in
268 %ebx so we only need an offset into the GOT). Once we have this, we can
269 dereference it to obtain the actual value. The advantage of doing it this way
270 is that to establish the address of a global variable, we need to store the
271 address in only one place, and hence we need only one relocation per global
272 variable.
274 We must do something similar for functions. It is critical that we allow the
275 user to redefine functions which might be in the shared library, and if the
276 user does, we want to force the shared library to always use the version the
277 user defined and never use the version of the function in the shared library.
278 Since the function could conceivably be used lots of times within a shared
279 library, we use something known as the procedure linkage table (or PLT) to
280 reference all functions. In a sense this is nothing more than a fancy name for
281 a jumptable, an array of jump instructions, one for each function that you
282 might need to go to. Thus if a particular function is called from thousands of
283 locations within the shared library, control will always pass through one jump
284 instruction. This way, you need only one relocation to determine which version
285 of a given function is actually called, and from the standpoint of performance
286 this is about as good as you are going to get.
288 Next month, we will use this information to dissect real ELF files, explaining
289 specifics about the ELF file format.
291 Eric Youngdale Eric Youngdale has worked with Linux for over two years, and has
292 been active in kernel development. He also developed the current Linux shared
293 libraries.
295   • 1
296   • 2
297   • next ›
298   • last »
300 ______________________
302   • Login to save this as favorite
303   • del.icio.us
304   • Digg
305   • Facebook
306   • Reddit
307   • SlashDot
308   • StumbleUpon
309   • Post to Twitter
311 Comments
313 Comment viewing options
315 [Threaded list - expanded ]
316 [Date - newest first]
317 [50 comments per page ]
318 [Save settings]
319 Select your preferred way to display the comments and click "Save settings" to
320 activate your changes.
323 khalid's picture
324 Submitted by khalid (not verified) on Tue, 11/03/2009 - 01:56.
326 I am using gcc compiler in linux can anybody mail me in detail what libraries
327 are needed in the linux executable programs and how the libraries in the linux
328 are dynamically loaded. if possible can any one mail me source code for this.
330 thanks & regards
332 khalid
334 process to execute the arm program
336 parvendra's picture
337 Submitted by parvendra (not verified) on Wed, 01/21/2009 - 05:59.
339 sir,
340 i m not not getting the compilation for arm program ,please tell me how we
341 select the path and which file we include in this,
343 please tell the total commands to run program in linux redhat8.0.
345 when i enter first command which is like that
347 arm-elf-as -D -gstabs -ahlms -mcpu=arm7tdmi -O add.o add.s
349 than i get the message
350 arm-elf-as: no such file or directory
351 please help me...
353 thanking u in advance
355 Dynamic Loader
357 Benitta Lawrence's picture
358 Submitted by Benitta Lawrence (not verified) on Thu, 11/08/2007 - 02:54.
360 I am trying to develop a Dynamic Loader for elf format shared libraries.I would
361 like to know whether a function which is defined in an application say app.out
362 can be called in a shared object file.If yes, How can it be done.
364 how to convert a.out to a flat binary file
366 srikanth's picture
367 Submitted by srikanth (not verified) on Wed, 02/14/2007 - 12:35.
369 hi friends
371 i am trying to convert a.out(or we can say "executable") into a flat binary
372 file. so that i can load it into a floppy and run it with out any operating
373 system.
374 can anyone help me out...
376 Link to ne next part
378 hibou57's picture
379 Submitted by hibou57 (not verified) on Sun, 12/03/2006 - 16:37.
381 As a link is missing to the next part - Part 2 : The ELF Object File Format by
382 Dissection
384 GCC-ELF
386 Anonymous's picture
387 Submitted by Anonymous (not verified) on Tue, 11/28/2006 - 02:07.
389 Hi everyone,
391 I am trying to use 'gcc-elf' but its not reconizing the command. Does anyone
392 know what files I'm missing and where I can obtain them..thanks
394 Ex. gcc-elf -dr foo.c -> to generate ir(or rtl) using elf format
396 dude, just use gcc today -
398 Anonymous's picture
399 Submitted by Anonymous (not verified) on Wed, 01/24/2007 - 04:27.
401 dude, just use gcc today - gcc-elf is what he was using when Linux was still
402 using a.out. So, in that article, he would've been using:
404 'gcc' - a.out
405 'gcc-elf' - ELF binary
407 duh.
409 This outstanding article is
411 Prakash's picture
412 Submitted by Prakash (not verified) on Sun, 10/01/2006 - 21:40.
414 This outstanding article is continuing to benefit mankind even 11 years after
415 its submission.
417 I was able to do minimal elf file walkthrough using a C program based on
418 concepts learnt from Eric's articles.
420 Thank you so much Eric for doing this for us.
422 Kind Regards,
423 Prakash
425 Very useful even after 12
427 Anonymous's picture
428 Submitted by Anonymous (not verified) on Wed, 01/24/2007 - 00:44.
430 Very useful even after 12 years, and will remain so till we have elf ;;)
432 The doc about the ELF format
434 Hibou57's picture
435 Submitted by Hibou57 (not verified) on Sun, 04/02/2006 - 20:06.
437 The doc about the ELF format is now there : ELF Format
439 Just one Word to descirbe
441 Balkad's picture
442 Submitted by Balkad (not verified) on Mon, 03/13/2006 - 03:20.
444 Just one Word to descirbe this article : FANTASTIC !!!!
446 Re: Kernel Korner: The ELF Object File Format: Introduction
448 Anonymous's picture
449 Submitted by Anonymous on Wed, 09/03/2003 - 01:00.
451 concise & clear
453 Re: Kernel Korner: The ELF Object File Format: Introduction
455 Anonymous's picture
456 Submitted by Anonymous on Thu, 08/22/2002 - 01:00.
458 Really very useful and interesting introduction.With this i can understand that
459 main advantages of ELF format over a.out is in using with Shared lib and it
460 provides more symbolic information which is useful for Debugger.
462 Are there any more advantages of ELF over *.out format??
464 Re: Kernel Korner: The ELF Object File Format: Introduction
466 Anonymous's picture
467 Submitted by Anonymous on Thu, 08/08/2002 - 01:00.
469 Very interesting, unfortuneately the link given for the ELF doc. is not
470 availible anymore.
472   • Video
473   • News
474   • Blogs
475   • Reviews
476   • HOWTOs
477   • Participate
478   • Hep & Tips
479   • How to Get Linux
480   • Getting Help
482 Loading
484 Already a subscriber? Click here for subscriber services.
486 Trending Topics
488   • Cloud
489   • Desktop
490   • Embedded
491   • HPC
492   • Security
493   • SysAdmin
494   • Virtualization
495   • Web Development
497   • The Latest
498   • Popular
499   • Recent Comments
501 Basic Chemistry on the GNOME Desktop               Jan 20, 2012
502 Black Wednesday                                    Jan 18, 2012
503 Can we help AT&T solve its mobile data problem?    Jan 17, 2012
504 ZevenOS - Does it recapture the flavor of BeOS?    Jan 17, 2012
505 Enter to Win a Free "Oops... Wrong window" TShirt! Jan 16, 2012
506 gStrings in Your Pocket                            Jan 13, 2012
508 more
510   • Readers' Choice Awards 2011
511   • Problem with ad on page 31 (October 2011 issue - PDF version)
512   • Basic Chemistry on the GNOME Desktop
513   • Why Python?
514   • Validate an E-Mail Address with PHP, the Right Way
515   • Eleven SSH Tricks
516   • Can we help AT&T solve its mobile data problem?
517   • Boot with GRUB
518   • RSS Feeds
519   • Python for Android
521 more
523   • Kindle Fire Accessories & Apps
524     5 hours 36 min ago
525   • Got used to GNOME3
526     20 hours 42 min ago
527   • Gnome?
528     1 day 2 hours ago
529   • I just installed Mint 12. The
530     1 day 5 hours ago
531   • How to convert MTS to MOV on Mac
532     1 day 5 hours ago
533   • Great Article
534     1 day 14 hours ago
535   • I always wish to visualize by my choice these molecules.
536     1 day 17 hours ago
537   • You went to a beach resort in
538     1 day 20 hours ago
539   • thanks
540     2 days 1 hour ago
541   • Comments
542     2 days 5 hours ago
544 Linux Newsletter
546 Linux Newsletter
548 Return to Solid State
550 See video                        See video
551 Get Firefox Menu Button in Linux Quick and Dirty SSH Tunneling
553 Click here for more videos
555 Poll
557 How do you manage your files? Do you: :
558 ( ) Organize your files into folders, and find them based on your filing
559 structure
560 ( ) Lump all your files together and rely on search to find a specific file
561 ( ) Organize your files into folders, but find them using a search
562 [Vote]
563 First Name                Last Name
564 [                  ]      [                  ]
565 Address 1                 Address 2
566 [                  ]      [                  ]
567 City                      State   Zip
568 [                  ]      [  ]    [     ]
569 Email
570 [                                        ]
571                                   [clickhere]
572 Canadian Residents | Foreign Residents | Gift Subscriptions | Customer Service
573 | Privacy Policy
575 Digital Edition
577   • Subscribe/Renew
578   • Pay My Bill
579   • Customer Service
580   • Digital Downloads
581   • Gift Subscriptions
583 Magazine Formats
585   • PC/Mac
586   • Android
587   • iPhone/iPad
588   • EPUB
589   • Kindle
591 The Store
593   • Stickers
594   • T-shirts
595   • Posters
596   • Back Issues
597   • Archive CD
599 About Us
601   • Advertise
602   • Author Info
603   • Write a Letter
604   • FAQ
605   • Masthead
607 The Site
609   • Copyright
610   • RSS Feeds
611   • Privacy Policy
612   • Report Problems
613   • Contact Us
615 Copyright © 1994 - 2011 Linux Journal. All rights reserved.