Initialize Tizen 2.3
[external/prelink.git] / doc / prelink.tex
1 \documentclass[twoside]{article}
2
3 \def\docversion{0.7}
4 % timezone: +01 == CET
5 \def\timezone{+01}
6 % Uncomment for draft print.
7 \def\isdraft{1}
8
9 \newif\ifpdf
10 \ifx\pdfoutput\undefined
11   \pdffalse % we are not running PDFLaTeX
12 \else
13   \pdfoutput=1 % we are running PDFLaTeX
14   \pdftrue
15 \fi
16
17 \usepackage{linuxtag}
18 \usepackage{times}
19 \usepackage{makeidx}
20 \usepackage{nomencl}
21 \usepackage[square]{natbib}
22 \usepackage{marvosym}
23 \usepackage{longtable}
24 \renewcommand\bibsection{\chapter{\bibname}}
25
26 \ifpdf
27   \usepackage[pdftex]{graphics}
28   \usepackage{type1cm}
29   \usepackage{thumbpdf}
30   \pdfcompresslevel9
31   \pdfinfo{/CreationDate (D:20030924012900\timezone'00')}
32   % The following code to set /ModDate comes from Heiko Oberdiek's paper
33   % one PDF & hyperref.  I only added the \timezone stuff.
34   \begingroup
35     \def\twodigits#1{\ifnum#1<10 0\fi\the#1}%
36     \count0=\time \divide\count0 by 60
37     \edef\x{\twodigits{\count0}}%
38     \multiply\count0 by 60
39     \count1=\time \advance\count1 by -\count0
40     \edef\x{\x\twodigits{\count1}}%
41     \edef\x{/ModDate (D:\the\year \twodigits\month \twodigits\day \x 00\timezone'00')}%
42     \expandafter\endgroup
43   \expandafter\pdfinfo\expandafter{\x}%
44   \input pdfcolor
45
46   %% For a "Draft" mark on the pages uncomment the following:
47   \ifx\isdraft\undefined
48     \relax
49   \else
50     \usepackage{eso-pic}
51     \usepackage{color}
52     \makeatletter
53       \AddToShipoutPicture{\rm%
54         \setlength{\@tempdimb}{.5\paperwidth}%
55         \setlength{\@tempdimc}{.5\paperheight}%
56         \setlength{\unitlength}{1pt}%
57         \put(\strip@pt\@tempdimb,\strip@pt\@tempdimc){%
58           \makebox(0,0){\rotatebox{45}{\textcolor[gray]{0.9}{\fontsize{5cm}{5cm}\selectfont{Draft}}}}
59         }
60     }
61     \makeatother
62   \fi
63 \else
64   \usepackage[dvips]{graphics}
65 \fi
66
67 \def\titlecolor{NavyBlue}
68 \makeatletter
69 \def\@sect#1#2#3#4#5#6[#7]#8{%
70   \ifnum #2>\c@secnumdepth
71     \let\@svsec\@empty
72   \else
73     \refstepcounter{#1}%
74     \protected@edef\@svsec{\@seccntformat{#1}\relax}%
75   \fi
76   \@tempskipa #5\relax
77   \ifdim \@tempskipa>\z@
78     \begingroup
79       \hbox{\expandafter\csname\titlecolor\endcsname#6{%
80         \@hangfrom{\hskip #3\relax\@svsec}%
81           \interlinepenalty \@M #8\@@par}\Black}%
82     \endgroup
83     \csname #1mark\endcsname{#7}%
84     \addcontentsline{toc}{#1}{%
85       \ifnum #2>\c@secnumdepth \else
86         \protect\numberline{\csname the#1\endcsname}%
87       \fi
88       #7}%
89   \else
90     \def\@svsechd{%
91       \hbox{\expandafter\csname\titlecolor\endcsname#6{\hskip #3\relax
92       \@svsec #8}%
93       \csname #1mark\endcsname{#7}\Black}%
94       \addcontentsline{toc}{#1}{%
95         \ifnum #2>\c@secnumdepth \else
96           \protect\numberline{\csname the#1\endcsname}%
97         \fi
98         #7}}%
99   \fi
100   \@xsect{#5}}
101 \def\@ssect#1#2#3#4#5{%
102   \@tempskipa #3\relax
103   \ifdim \@tempskipa>\z@
104     \begingroup
105       \expandafter\csname\titlecolor\endcsname#4{%
106         \@hangfrom{\hskip #1}%
107           \interlinepenalty \@M #5\@@par}\Black%
108     \endgroup
109   \else
110     \def\@svsechd{\expandafter\csname\titlecolor\endcsname#4{\hskip #1\relax #5}\Black}%
111   \fi
112   \@xsect{#3}}
113 \makeatother
114
115 \usepackage{fancyheadings}
116 \pagestyle{fancy}
117 \rhead{}
118 \chead{}
119 \lhead{}
120 \rfoot[\sl Prelink]{\thepage}
121 \lfoot[\thepage]{\sl Jakub Jel\'\i nek}
122 \ifx\isdraft\undefined
123 \cfoot{Version \docversion}
124 \else
125 \cfoot{Draft \docversion}
126 \fi
127 \renewcommand{\headrulewidth}{0.4pt}
128 \renewcommand{\footrulewidth}{0.4pt}
129
130 \ifx\isdraft\undefined
131 \relax
132 \else
133 \usepackage[mathlines]{lineno}
134 \fi
135
136 \usepackage{graphicx}
137 \usepackage{hyperref}
138 \hypersetup{
139   bookmarksnumbered,
140   bookmarksopen=true,
141   pdfpagemode=UseOutlines,
142   pdfkeywords={Prelink, ELF, DSO, Shared Library, Dynamic Linking, Linux}
143 }
144 \usepackage{prelinklisting}
145
146 \def\tts#1{\texttt{\small #1}}
147
148 \setcounter{dbltopnumber}{3}
149
150
151 \makeatletter
152 \newcommand{\annotate}[2][]{%
153   \marginpar{%
154     \pdfstringdef\x@title{#1}%
155     \edef\r{\string\r}%
156     \pdfstringdef\x@contents{#2}%
157     \pdfannot
158     width 50em%\linewidth
159     height .5\baselineskip
160     depth 2.5\baselineskip
161     {
162       /Subtype /Text
163       /T (\x@title)
164       /Contents (\x@contents)
165       }%
166     }
167   }
168 \makeatother
169
170 \makeglossary
171 \makeindex
172
173 \begin{document}
174
175   \makeatletter
176   \newcommand\orgmaketitle{}
177   \let\orgmaketitle\maketitle
178   \def\maketitle{%
179     \hypersetup{
180       pdftitle={\@title},
181       pdfsubject={Description of prelink tool},
182       pdfauthor={\@author}
183     }%
184     \orgmaketitle
185   }
186   \makeatother
187
188 \title{Prelink}
189 \author{Jakub Jel\'\i nek\\
190 Red Hat, Inc.\\
191 {\small\tt\href{mailto:jakub@redhat.com}{jakub@redhat.com}}}
192
193 %\maketitle
194
195 %\tableofcontents
196 %\vfil\break
197 %\listoftables
198 %\vfil\break
199 %\listofprelinklistings
200 %\vfil\break
201 %\listoffigures
202 %\vfil\break
203
204 \maketitle
205
206 \begin{center}
207 \begin{abstract}
208 \vspace*{.5\baselineskip}
209 \parbox{0.8\textwidth}{%
210 Prelink is a tool designed to speed up dynamic linking of ELF
211 programs on various Linux architectures.
212 It speeds up start up of OpenOffice.org 1.1 by 1.8s from 5.5s on 651MHz Pentium III.}
213 \end{abstract}
214 \end{center}
215
216 \ifx\isdraft\undefined
217   \relax
218 \else
219   \linenumbers
220   \linenumbersep4pt
221 \fi
222
223 \section{Preface}
224
225 In 1995, Linux changed its binary format from \tts{a.out} to \tts{ELF}.
226 The \tts{a.out} binary format was very inflexible and shared libraries
227 were pretty hard to build.  Linux's shared libraries in \tts{a.out} are position
228 dependent and each had to be given a unique virtual address space slot
229 at link time.  Maintaining these assignments was pretty hard even when
230 there were just a few shared libraries, there used to be a central address
231 registry maintained by humans in form of a text file, but it is certainly
232 impossible to do these days when there are thousands of different shared libraries
233 and their size, version and exported symbols are constantly changing.
234 On the other side, there was just minimum amount of work the dynamic
235 linker had to do in order to load these shared libraries, as relocation
236 handling and symbol lookup was only done at link time.  The dynamic linker
237 used the \tts{uselib} system call which just mapped the named library
238 into the address space (with no segment or section protection differences,
239 the whole mapping was writable and executable).
240
241 The \href{http://www.caldera.com/developers/devspecs/gabi41.pdf}%
242 {\tts{ELF}}
243 \footnote{As described in generic ABI document [1] and various processor
244 specific ABI supplements [2], [3], [4], [5], [6], [7], [8].}
245 binary format is one of the most flexible binary formats,
246 its shared libraries are easy to build and there is no need for a central
247 assignment of virtual address space slots.  Shared libraries are position
248 independent and relocation handling and symbol lookup are done partly
249 at the time the executable is created and partly at runtime.  Symbols in shared
250 libraries can be overridden at runtime by preloading a new shared
251 library defining those symbols or without relinking an executable by adding
252 symbols to a shared library which is searched up earlier during symbol
253 lookup or by adding new dependent shared libraries to a library used by the
254 program.  All these improvements have their price, which is a slower
255 program startup, more non-shareable memory per process and runtime cost
256 associated with position independent code in shared libraries.
257
258 Program startup of \tts{ELF} programs is slower than startup of \tts{a.out}
259 programs with shared libraries, because the dynamic linker has much more work
260 to do before calling program's entry point.  The cost of loading libraries
261 is just slightly bigger, as \tts{ELF} shared libraries have typically
262 separate read-only and writable segments, so the dynamic linker
263 has to use different memory protection for each segment.
264 The main difference is in relocation handling and associated symbol lookup.
265 In the \tts{a.out} format there was no relocation handling or symbol lookup at runtime.
266 In \tts{ELF}, this cost is much more important today than it used to be
267 during \tts{a.out} to \tts{ELF} transition in Linux, as especially GUI
268 programs keep constantly growing and start to use more and more shared
269 libraries.  5 years ago programs using more than 10 shared libraries
270 were very rare, these days most of the GUI programs link against around
271 40 or more shared and in extreme cases programs use even more than 90
272 shared libraries.  Every shared library adds its set of dynamic relocations
273 to the cost and enlarges symbol search scope,
274 \nomenclature{Symbol Search Scope}{The sequence of \tts{ELF} objects in
275 which a symbol is being looked up.  When a symbol definition is found,
276 the searching stops and the found symbol is returned.  Each program
277 has a global search scope, which starts by the executable, is typically
278 followed by the immediate dependencies of the executable and then their
279 dependencies in breadth search order (where only first occurrence
280 of each shared library is kept).  If \tts{DT\_FILTER}
281 or \tts{DT\_AUXILIARY} dynamic tags are used the order is slightly
282 different.  Each shared library loaded with \tts{dlopen} has its
283 own symbol search scope which contains that shared library and
284 its dependencies.  \tts{Prelink} operates also with natural
285 symbol search scope of each shared library, which is the global
286 symbol search scope the shared library would have if it were started
287 as the main program}
288 so in addition to doing more symbol lookups, each symbol
289 lookup the application has to perform is on average more expensive.
290 Another factor increasing the cost is the length of symbol names
291 which have to be compared when finding symbol in the symbol hash table of
292 a shared library.  C++ libraries tend to have extremely long symbol
293 names and unfortunately the new \href{http://www.codesourcery.com/cxx-abi/}%
294 {C++ ABI} puts namespaces and class names first and method names last
295 in the mangled names, so often symbol names differ only in last
296 few bytes of very long names.
297
298 Every time a relocation is applied the entire memory page
299 \nomenclature{Page}{Memory block of fixed size which virtual memory
300 subsystem deals with as a unit.  The size of the page depends on
301 the addressing hardware of the processor, typically pages are 4K or 8K,
302 in some cases bigger}
303 containing the address which is written to must be loaded into memory.
304 The operating system does a copy-on-write operation which also has the
305 consequence that the physical memory of the memory page cannot anymore
306 be shared with other processes.
307 With \tts{ELF}, typically all of program's Global Offset Table,
308 \nomenclature{Global Offset Table (\tts{GOT})}{When position independent
309 code needs to build address which requires dynamic relocation, instead
310 of building it as constant in registers and applying a dynamic relocation
311 against the read-only segment (which would mean that any pages of the
312 read-only segment where relocations are applied cannot be shared between
313 processes anymore), it loads the address from an offset table
314 private to each shared library, which is created by the linker.
315 The table is in writable segment and relocations are applied against it.
316 Position independent code uses on most architectures a special \tts{PIC}
317 register which points to the start of the Global Offset Table}
318 constants and variables containing pointers to objects in shared libraries, etc.
319 are written into before the dynamic linker passes control over to the program.
320
321 On most architectures (with some exceptions like \tts{AMD64} architecture)
322 position independent code requires that one register needs to be dedicated as
323 \tts{PIC} register and thus cannot be used in the functions for other purposes.
324 This especially degrades performance on register-starved
325 architectures like \tts{IA-32}.  Also, there needs to be some code to
326 set up the \tts{PIC} register, either invoked as part of function prologues,
327 or when using function descriptors in the calling sequence.
328
329 \tts{Prelink} is a tool which (together with corresponding dynamic linker
330 and linker changes) attempts to bring back some of the \tts{a.out}
331 advantages (such as the speed and less COW'd pages) to the \tts{ELF}
332 binary format while retaining all of its flexibility.  In a limited way
333 it also attempts to decrease number of non-shareable pages created by
334 relocations.
335 \tts{Prelink} works closely with the dynamic linker in the GNU C library,
336 but probably it wouldn't be too hard to port it to some other \tts{ELF}
337 using platforms where the dynamic linker can be modified in similar
338 ways.
339
340 \section{Caching of symbol lookup results}
341
342 Program startup can be speeded up by caching of symbol lookup
343 results\footnote{Initially, this has been implemented in the \tts{prelink}
344 tool and \tts{glibc} dynamic linker, where \tts{prelink} was sorting
345 relocation sections of existing executables and shared libraries.
346 When this has been implemented in the linker as well and most executables
347 and shared libraries are already built with \tts{-z combreloc},
348 the code from \tts{prelink} has been removed, as it was no longer
349 needed for most objects and just increasing the tool's complexity.}.
350 Many shared libraries need more than one lookup of a particular symbol.
351 This is especially true for C++ shared libraries, where e.g. the same method
352 is present in multiple virtual tables or {\sl RTTI} data structures.
353 \nomenclature{RTTI}{C++ runtime type identification}
354 Traditionally, each \tts{ELF} section which needs dynamic relocations has an
355 associated \tts{.rela*} or \tts{.rel*} section (depending on whether
356 the architecture is defined to use \tts{RELA} or \tts{REL} relocations).
357 \nomenclature{RELA}{Type of relocation structure which includes offset,
358 relocation type, symbol against which the relocation is and an integer
359 addend which is added to the symbol.  Memory at offset is not supposed
360 to be used by the relocation.  Some architectures got this implemented
361 incorrectly and memory at offset is for some relocation types used
362 by the relocation, either in addition to addend or addend is not used
363 at all.  \tts{RELA} relocations are generally better for \tts{prelink},
364 since when \tts{prelink} stores a pre-computed value into the memory location
365 at offset, the addend value is not lost}
366 \nomenclature{REL}{Type of relocation structure which includes just offset,
367 relocation type and symbol.  Addend is taken from memory location at
368 offset}
369 The relocations in those sections are typically sorted by ascending
370 \tts{r\_offset} values.
371 Symbol lookups are usually the most expensive operation during program
372 startup, so caching the symbol lookups has potential to decrease time
373 spent in the dynamic linker.
374 One way to decrease the cost of symbol lookups is to create a table with the
375 size equal to number of entries
376 in dynamic symbol table (\tts{.dynsym}) in the dynamic linker when resolving
377 a particular shared library, but that would in some cases need a lot of
378 memory and some time spent in initializing the table.  Another option
379 would be to use a hash table with chained lists, but that needs both
380 extra memory and would also take extra time for computation of the hash value
381 and walking up the chains when doing new lookups.
382 Fortunately, neither of this is really necessary if we modify the linker
383 to sort relocations so that relocations against the same symbol
384 are adjacent.  This has been done first in the \tts{Sun} linker and dynamic
385 linker, so the GNU linker and dynamic linker use the same \tts{ELF} extensions
386 and linker flags.  Particularly, the following new \tts{ELF} dynamic tags have been introduced:
387
388 \tts{\#define DT\_RELACOUNT    0x6ffffff9}\\
389 \tts{\#define DT\_RELCOUNT     0x6ffffffa}
390
391 New options \tts{-z combreloc} and \tts{-z nocombreloc} have been
392 added to the linker.  The latter causes the previous linker behavior,
393 i.e. each section requiring relocations has a corresponding relocation section,
394 which is sorted by ascending \tts{r\_offset}.  \tts{-z combreloc}
395 \footnote{\tts{-z combreloc} is the default in GNU linker versions
396 2.13 and later.} instructs the linker to create just one relocation
397 section for dynamic relocations other than symbol jump table (\tts{PLT})
398 relocations.
399 \nomenclature{PLT}{Process Linkage Table.  Stubs in \tts{ELF} shared
400 libraries and executables which allow lazy relocations of function calls.
401 They initially point to code which will do the symbol lookup.  The
402 result of this symbol lookup is then stored in the Process Linkage Table
403 and control transfered to the address symbol lookup returned.  All
404 following calls to the \tts{PLT} slot just branch to the already looked
405 up address directly, no further symbol lookup is needed}
406 This single relocation section (either \tts{.rela.dyn} or \tts{.rel.dyn})
407 is sorted, so that relative relocations come first (sorted by ascending
408 \tts{r\_offset}), followed by other relocations, sorted again by ascending
409 \tts{r\_offset}.  If more relocations are against the same
410 symbol, they immediately follow the first relocation against that symbol
411 with lowest \tts{r\_offset}.
412 \footnote{In fact the sorting needs to take into account also the type of
413 lookup.  Most of the relocations will resolve to a \tts{PLT} slot in the executable
414 if there is one for the lookup symbol, because the executable might have a
415 pointer against that symbol without any dynamic relocations.  But e.g.
416 relocations used for the \tts{PLT} slots must avoid these.}.
417 \nomenclature{relative relocation}{Relocation, which doesn't need a symbol
418 lookup, just adds a shared library load offset to certain memory location
419 (or locations)}
420 The number of relative relocations at the beginning of the section
421 is stored in the \tts{DT\_RELACOUNT} resp. \tts{DT\_RELCOUNT} dynamic tag.
422
423 The dynamic linker can use the new dynamic tag for two purposes.
424 If the shared library is successfully mapped at the same address
425 as the first \tts{PT\_LOAD} segment's virtual address, the load offset
426 is zero and the dynamic linker can avoid all the relative relocations which
427 would just add zero to various memory locations.  Normally shared libraries are
428 linked with first \tts{PT\_LOAD} segment's virtual address set to zero, so
429 the load offset is non-zero.  This can be changed through a linker script or by
430 using a special \tts{prelink} option \tts{--reloc-only} to change
431 the base address of a shared library.  All prelinked shared libraries
432 have non-zero base address as well.  If the load offset is non-zero, the
433 dynamic linker can still make use of this dynamic tag, as relative
434 relocation handling is typically way simpler than handling other
435 relocations (since symbol lookup is not necessary) and thus it can
436 handle all relative relocations in a tight loop in one place and
437 then handle the remaining relocations with the fully featured
438 relocation handling routine.  The second and more important point is
439 that if relocations against the same symbol are adjacent, the dynamic
440 linker can use a cache with single entry.
441
442 The dynamic linker in \tts{glibc}, if it sees \tts{statistics}
443 as part of the \tts{LD\_DEBUG} environment variable, displays statistics
444 which can show how useful this optimization is.
445 Let's look at some big C++ application, e.g. konqueror.
446 If not using the cache, the statistics looks like this:
447
448 \noindent{\small\begin{verbatim}
449 18000:     runtime linker statistics:
450 18000:       total startup time in dynamic loader: 270886059 clock cycles
451 18000:                 time needed for relocation: 266364927 clock cycles (98.3%)
452 18000:                      number of relocations: 79067
453 18000:           number of relocations from cache: 0
454 18000:             number of relative relocations: 31169
455 18000:                time needed to load objects: 4203631 clock cycles (1.5%)
456 \end{verbatim}}
457
458 This program run is with hot caches, on non-prelinked system, with lazy
459 binding.
460 \nomenclature{Lazy Binding}{A way to postpone symbol lookups for calls until
461 a function is called for the first time in particular shared library.
462 This decreases number of symbol lookups done during startup and symbols
463 which are never called don't need to be looked up at all.  Calls requiring
464 relocations jump into \tts{PLT}, which is initially set up so that a
465 function in the dynamic linker is called to do symbol lookup.  The looked
466 up address is then stored either into the \tts{PLT} slot directly
467 (if \tts{PLT} is writable) or into \tts{GOT} entry corresponding
468 to the \tts{PLT slot} and any subsequent calls already go directly to that
469 address.  Lazy binding can be turned off by setting \tts{LD\_BIND\_NOW=1}
470 in the environment.  Prelinked programs never use lazy binding for the
471 executable or any shared libraries not loaded using \tts{dlopen}}
472 The numbers show that the dynamic linker spent most of its time
473 in relocation handling and especially symbol lookups.  If using symbol
474 lookup cache, the numbers look different:
475
476 \noindent{\small\begin{verbatim}
477 18013:       total startup time in dynamic loader: 132922001 clock cycles
478 18013:                 time needed for relocation: 128399659 clock cycles (96.5%)
479 18013:                      number of relocations: 25473
480 18013:           number of relocations from cache: 53594
481 18013:             number of relative relocations: 31169
482 18013:                time needed to load objects: 4202394 clock cycles (3.1%)
483 \end{verbatim}}
484
485 On average, for one real symbol lookup there were two cache hits and total
486 time spent in the dynamic linker decreased by 50\%.
487
488 \section{Prelink design}
489
490 \tts{Prelink} was designed, so that it requires as few \tts{ELF} extensions
491 as possible.  It should not be tied to a particular architecture, but
492 should work on all \tts{ELF} architectures.  During program startup it
493 should avoid all symbol lookups which, as has been shown above, are
494 very expensive.  It needs to work in an environment where shared
495 libraries and executables are changing from time to time, whether it is
496 because of security updates or feature enhancements.  It should avoid big code
497 duplication between the dynamic linker and the tool.  And prelinked
498 shared libraries need to be usable even in non-prelinked executables,
499 or when one of the shared libraries is upgraded and the prelinking of the
500 executable has not been updated.
501
502 To minimize the number of performed relocations during startup,
503 the shared libraries (and executables) need to be relocated
504 already as much as possible.  For relative relocations this means the library
505 needs to be loaded always at the same base address, for other relocations
506 this means all shared libraries with definitions those relocations resolve
507 to (often this includes all shared libraries the library or executable depends on)
508 must always be loaded at the same addresses.  \tts{ELF} executables
509 (with the exception of {\sl Position Independent Executables})
510 \nomenclature{Position Independent Executable}{A hybrid between
511 classical \tts{ELF} executables and \tts{ELF} shared libraries.
512 It has a form of a \tts{ET\_DYN} object like shared libraries and should
513 contain position independent code, so that the kernel can load
514 the executable starting at random address to make certain security attacks
515 harder.  Unlike shared libraries it contains \tts{DT\_DEBUG} dynamic
516 tag, must have \tts{PT\_INTERP} segment with dynamic linker's path,
517 must have meaningful code at its \tts{e\_entry} and can use symbol
518 lookup assumptions normal executables can make, particularly that
519 no symbol defined in the executable can be overridden by a shared
520 library symbol} have their load address fixed already during linking.
521 For shared libraries, \tts{prelink} needs something similar to \tts{a.out}
522 registry of virtual address space slots.  Maintaining such registry
523 across all installations wouldn't scale well, so \tts{prelink} instead
524 assigns these virtual address space slots on the fly after looking at
525 all executables it is supposed to speed up and all their dependent shared
526 libraries.  The next step is to actually relocate shared libraries
527 to the assigned base address.
528
529 When this is done, the actual prelinking of shared libraries can be done.
530 First, all dependent shared libraries need to be prelinked (\tts{prelink}
531 doesn't support circular dependencies between shared libraries, will just
532 warn about them instead of prelinking the libraries in the cycle), then for each
533 relocation in the shared library \tts{prelink} needs to look up the symbol
534 in natural symbol search scope of the shared library (the shared library
535 itself first, then breadth first search of all dependent shared libraries) and
536 apply the relocation to the symbol's target section.  The symbol lookup code
537 in the dynamic linker is quite complex and big, so to avoid duplicating all
538 this, \tts{prelink} has chosen to use dynamic linker to do the symbol lookups.
539 Dynamic linker is told via a special environment variable it should print
540 all performed symbol lookups and their type and \tts{prelink} reads this
541 output through a pipe.  As one of the requirements was that
542 prelinked shared libraries must be usable even for non-prelinked executables
543 (duplicating all shared libraries so that there are pristine and prelinked
544 copies would be very unfriendly to RAM usage), \tts{prelink} has to ensure
545 that by applying the relocation no information is lost and thus relocation
546 processing can be cheaply done at startup time of non-prelinked executables.
547 For \tts{RELA} architectures this is easier, because the content
548 of the relocation's target memory is not needed when processing the relocation.
549 \footnote{Relative relocations on certain \tts{RELA} architectures use
550 relocation target's memory, either alone or together with \tts{r\_addend}
551 field.}  For \tts{REL} architectures this is not the case.
552 \tts{prelink} attempts some tricks described
553 later and if they fail, needs to convert the \tts{REL} relocation section
554 to \tts{RELA} format where addend is stored in the relocation section
555 instead of relocation target's memory.
556
557 When all shared libraries an executable (directly or indirectly) depends on
558 are prelinked, relocations in the executable are handled similarly to
559 relocations in shared libraries.  Unfortunately, not all symbols resolve the
560 same when looked up in a shared library's natural symbol search scope
561 (i.e. as it is done at the time the shared library is prelinked) and when
562 looked up in application's global symbol search scope.  Such symbols are
563 herein called {\sl conflicts} and the relocations against those symbols
564 {\sl conflicting relocations}.  Conflicts depend on the executable, all its
565 shared libraries and their respective order.  They are only computable
566 for the shared libraries linked to the executable (libraries mentioned in
567 \tts{DT\_NEEDED} dynamic tags and shared libraries they transitively need).
568 The set of shared libraries loaded via \tts{dlopen(3)} cannot be predicted
569 by \tts{prelink}, neither can the order in which this happened, nor the time
570 when they are unloaded.  When the dynamic linker prints symbol lookups
571 done in the executable, it also prints conflicts.  \tts{Prelink} then
572 takes all relocations against those symbols and builds a special
573 \tts{RELA} section with conflict fixups and stores it into the
574 prelinked executable.  Also a list of all dependent shared libraries
575 in the order they appear in the symbol search scope, together
576 with their checksums and times of prelinking is stored in another special
577 section.
578
579 The dynamic linker first checks if it is itself prelinked.  If yes,
580 it can avoid its preliminary relocation processing (this one is done
581 with just the dynamic linker itself in the search scope, so that
582 all routines in the dynamic linker can be used easily without too many
583 limitations).  When it is about to start a program, it first looks
584 at the library list section created by \tts{prelink} (if any) and
585 checks whether they are present in symbol search scope in the same
586 order, none have been modified since prelinking and that there aren't any
587 new shared libraries loaded either.  If all these conditions are
588 satisfied, prelinking can be used.  In that case the dynamic linker
589 processes the fixup section and skips all normal relocation handling.
590 If one or more of the conditions are not met, the dynamic linker continues
591 with normal relocation processing in the executable and all shared libraries.
592
593 \section{Collecting executables and libraries which should be prelinked}
594
595 Before the actual work can start the \tts{prelink} tool needs to collect the
596 filenames of executables and libraries it is supposed to prelink.
597 It doesn't make any sense to prelink a shared library if no executable is
598 linked against it because the prelinking information will not be used anyway.
599 Furthermore, when \tts{prelink} needs to do a \tts{REL} to \tts{RELA}
600 conversion of relocation sections in the shared library (see later)
601 or when it needs to convert \tts{SHT\_NOBITS} \tts{PLT} section to
602 \tts{SHT\_PROGBITS}, a prelinked shared library might grow in size and so
603 prelinking is only desirable if it will speed up startup of some
604 program.  The only change which might be useful even for shared libraries
605 which are never linked against, only loaded using \tts{dlopen}, is
606 relocating to a unique address.  This is useful if there are many relative
607 relocations and there are pages in the shared library's writable segment
608 which are never written into with the exception of those relative
609 relocations.  Such shared libraries are rare, so \tts{prelink} doesn't
610 handle these automatically, instead the administrator or developer can
611 use \tts{prelink --reloc-only={\sl ADDRESS}} to relocate it manually.
612 Prelinking an executable requires all shared libraries it is linked against
613 to be prelinked already.
614
615 \tts{Prelink} has two main modes in which it collects filenames.
616 One is {\sl incremental prelinking}, where \tts{prelink} is invoked without
617 the \tts{-a} option.  In this mode, \tts{prelink} queues for prelinking
618 all executables and shared libraries given on the command line, all executables
619 in directory trees specified on the command line, and all shared libraries
620 those executables and shared libraries are linked against.
621 For the reasons mentioned earlier a shared library is queued only if a
622 program is linked with it or the user tells the tool to do it anyway
623 by explicitly mentioning it on the command line.
624 The second mode is {\sl full prelinking}, where the \tts{-a} option is
625 given on the command line.  This in addition to incremental prelinking
626 queues all executables found in directory trees specified in \tts{prelink.conf}
627 (which typically includes all or most directories where system executables
628 are found).  For each directory subtree in the config file the user
629 can specify whether symbolic links to places outside of the tree are to be followed
630 or not and whether searching should continue even across filesystem
631 boundaries.
632
633 There is also an option to blacklist some executables or directory trees
634 so that the executables or anything in the directory trees will not
635 be prelinked.  This can be specified either on the command line or in
636 the config file.
637
638 \tts{Prelink} will not attempt to change executables which use a non-standard
639 dynamic linker
640 \footnote{Standard dynamic linker path is hardcoded in the executable for each
641 architecture.  It can be overridden from the command line, but only with
642 one dynamic linker name (normally, multiple standard dynamic linkers are
643 used when prelinking mixed architecture systems).}
644 for security reasons, because it actually needs to execute the dynamic
645 linker for symbol lookup and it needs to avoid executing some random
646 unknown executable with the permissions with which \tts{prelink} is run
647 (typically \tts{root}, with the permissions at least for changing all
648 executables and shared libraries in the system).  The administrator should
649 ensure that \tts{prelink.conf} doesn't contain world-writable directories
650 and such directories are not given to the tool on the command line either,
651 but the tool should be distrustful of the objects nevertheless.
652
653 Also, \tts{prelink} will not change shared libraries which are not specified
654 directly on the command line or located in the directory trees specified on the
655 command line or in the config file.  This is so that
656 e.g. \tts{prelink} doesn't try to change shared libraries on shared
657 networked filesystems, or at least it is possible to configure the tool
658 so that it doesn't do it.
659
660 For each executable and shared library it collects, \tts{prelink} executes
661 the dynamic linker to list all shared libraries it depends on, checks if
662 it is already prelinked and whether any of its dependencies changed.
663 Objects which are already prelinked and have no dependencies which changed
664 don't have to be prelinked again (with the exception when e.g. virtual
665 address space layout code finds out it needs to assign new virtual address space slots
666 for the shared library or one of its dependencies).  Running the dynamic
667 linker to get the symbol lookup information is a quite costly
668 operation especially on systems with many executables and shared libraries
669 installed, so \tts{prelink} offers a faster \tts{-q} mode.  In all modes,
670 \tts{prelink} stores modification and change times of each shared library
671 and executable together with all object dependencies and other information
672 into \tts{prelink.cache} file.  When prelinking in \tts{-q} mode, it
673 just compares modification and change times of the executables and shared
674 libraries (and all their dependencies).  Change time is needed because
675 \tts{prelink} preserves modification time when prelinking (as well as
676 permissions, owner and group).  If the times match, it assumes the
677 file has not changed since last prelinking.  Therefore the file can be
678 skipped if it is already prelinked and none of the dependencies changed.
679 If any time changed or one of the dependencies changed, it invokes the
680 dynamic linker the same way as in normal mode to find out real dependencies,
681 whether it has been prelinked or not etc.  The collecting phase in normal
682 mode can take a few minutes, while in quick mode usually takes just a few
683 seconds, as the only operation it does is it calls just lots of \tts{stat}
684 system calls.
685
686 \section{Assigning virtual address space slots}
687
688 \tts{Prelink} has to ensure at least that for all successfully prelinked
689 executables all shared libraries they are (transitively) linked against
690 have non-overlapping virtual address space slots (furthermore they
691 cannot overlap with the virtual address space range used by the executable
692 itself, its \tts{brk} area, typical stack location and \tts{ld.so.cache}
693 and other files mmaped by the dynamic linker in early stages of dynamic
694 linking (before all dependencies are mmaped).  If there were any overlaps,
695 the dynamic linker (which mmaps the shared libraries at the desired location
696 without \tts{MAP\_FIXED} mmap flag so that it is only soft requirement) would
697 not manage to mmap them at the assigned locations and the prelinking
698 information would be invalidated (the dynamic linker would have to do all
699 normal relocation handling and symbol lookups).  Executables are linked against
700 very wide variety of shared library combinations and that has to be taken
701 into account.
702
703 The simplest approach is to sort shared libraries by descending
704 usage count (so that most often used shared libraries like the dynamic
705 linker, \tts{libc.so} etc. are close to each other) and assign them
706 consecutive slots starting at some architecture specific base address
707 (with a page or two in between the shared libraries to allow for a limited
708 growth of shared libraries without having to reposition them).
709 \tts{Prelink} has to find out which shared libraries will need
710 a \tts{REL} to \tts{RELA} conversion of relocation sections
711 and for those which will need the conversion count with the increased size
712 of the library's loadable segments.  This is \tts{prelink} behavior without
713 \tts{-m} and \tts{-R} options.
714
715 The architecture specific base address is best located a few megabytes above
716 the location where \tts{mmap} with \tts{NULL} first argument and without
717 \tts{MAP\_FIXED} starts allocating memory areas (in Linux this is the value
718 of \tts{TASK\_UNMAPPED\_BASE} macro).
719 \footnote{\tts{TASK\_UNMAPPED\_BASE} has been chosen
720 on each platform so that there is enough virtual memory for both the
721 \tts{brk} area (between executable's end and this memory address) and \tts{mmap}
722 area (between this address and bottom of stack).}  The reason for not
723 starting to assign addresses in \tts{prelink} immediately at
724 \tts{TASK\_UNMAPPED\_BASE} is that \tts{ld.so.cache} and other mappings by
725 the dynamic linker will end up in the same range and could overlap with
726 the shared libraries.  Also, if some application uses \tts{dlopen} to load
727 a shared library which has been prelinked,
728 \footnote{Typically this is because some other executable is linked against that
729 shared library directly.}
730 those few megabytes above \tts{TASK\_UNMAPPED\_BASE} increase the probability
731 that the stack slot will be still unused (it can clash with e.g.
732 non-prelinked shared libraries loaded by \tts{dlopen} earlier
733 \footnote{If shared libraries have first \tts{PT\_LOAD} segment's virtual
734 address zero, the kernel typically picks first empty slot above
735 \tts{TASK\_UNMAPPED\_BASE} big enough for the mapping.} or other kinds
736 of mmap calls with \tts{NULL} first argument like \tts{malloc} allocating
737 big chunks of memory, mmaping of locale database, etc.).
738
739 This simplest approach is unfortunately problematic on 32-bit (or 31-bit)
740 architectures where the total virtual address space for a process is
741 somewhere between 2GB (S/390) and almost 4GB (Linux IA-32 4GB/4GB kernel
742 split, AMD64 running 32-bit processes, etc.).  Typical installations these
743 days contain thousands of shared libraries and if each of them is given a
744 unique address space slot, on average executables will have pretty sparse
745 mapping of its shared libraries and there will be less contiguous virtual
746 memory for application's own use
747 \footnote{Especially databases look these days for every byte of virtual
748 address space on 32-bit architectures.}.
749
750 \tts{Prelink} has a special mode, turned on with \tts{-m} option, in which
751 it computes what shared libraries are ever loaded together in some executable
752 (not considering \tts{dlopen}).  If two shared libraries are ever loaded
753 together, \tts{prelink} assigns them different virtual address space slots,
754 but if they never appear together, it can give them overlapping addresses.
755 For example applications using \tts{KDE} toolkit link typically against many
756 \tts{KDE} shared libraries, programs written using the \tts{Gtk+} toolkit
757 link typically against many \tts{Gtk+} shared libraries, but there are just
758 very few programs which link against both \tts{KDE} and \tts{Gtk+} shared
759 libraries, and even if they do, they link against very small subset of those
760 shared libraries.  So all \tts{KDE} shared libraries not in that subset can
761 use overlapping addresses with all \tts{Gtk+} shared libraries but the
762 few exceptions.  This leads to considerably smaller virtual address space
763 range used by all prelinked shared libraries, but it has its own
764 disadvantages too.  It doesn't work too well with incremental prelinking,
765 because then not all executables are investigated, just those which are given
766 on \tts{prelink}'s command line.  \tts{Prelink} also considers executables
767 in \tts{prelink.cache}, but it has no information about executables which have
768 not been prelinked yet.  If a new executable, which links against some shared
769 libraries which never appeared together before, is prelinked later,
770 \tts{prelink} has to assign them new, non-overlapping addresses.
771 This means that any executables, which linked against the library
772 that has been moved and re-prelinked, need to be prelinked again.
773 If this happened during incremental prelinking, \tts{prelink} will
774 fix up only the executables given on the command line, leaving other
775 executables untouched.  The untouched executables would not be able to
776 benefit from prelinking anymore.
777
778 Although with the above two layout schemes shared library addresses can
779 vary slightly between different hosts running the same distribution
780 (depending on the exact set of installed executables and libraries), especially
781 the most often used shared libraries will have identical base addresses
782 on different computers.  This is often not desirable for security reasons,
783 because it makes it slightly easier for various exploits to jump to routines
784 they want.  Standard Linux kernels assign always the same addresses to
785 shared libraries loaded by the application at each run, so with these
786 kernels \tts{prelink} doesn't make things worse.  But there are kernel
787 patches, such as Red Hat's \tts{Exec-Shield}, which randomize memory
788 mappings on each run.  If shared libraries are prelinked, they cannot
789 be assigned different addresses on each run (prelinking information can
790 be only used to speed up startup if they are mapped at the base addresses
791 which was used during prelinking), which
792 means prelinking might not be desirable on some edge servers.
793 \tts{Prelink} can assign different addresses on different hosts though,
794 which is almost the same as assigning random addresses on each run
795 for long running processes such as daemons.  Furthermore, the administrator
796 can force full prelinking and assignment of new random addresses every few
797 days (if he is also willing to restart the services, so that the old
798 shared libraries and executables don't have to be kept in memory).
799
800 To assign random addresses \tts{prelink} has the \tts{-R} option.
801 This causes a random starting address somewhere in the architecture specific
802 range in which shared libraries are assigned, and minor random reshuffling
803 in the queue of shared libraries which need address assignment (normally
804 it is sorted by descending usage count, with randomization shared libraries
805 which are not very far away from each other in the sorted list can be
806 swapped).  The \tts{-R} option should work orthogonally to the \tts{-m}
807 option.
808
809 Some architectures have special further requirements on shared library
810 address assignment.  On 32-bit PowerPC, if shared libraries are located
811 close to the executable, so that everything fits into 32MB area, \tts{PLT}
812 slots resolving to those shared libraries can use the branch relative
813 instruction instead of more expensive sequences involving memory load
814 and indirect branch.  If shared libraries are located in the
815 first 32MB of address space, \tts{PLT} slots resolving to those shared
816 libraries can use the branch absolute instruction (but already \tts{PLT}
817 slots in those shared libraries resolving to addresses in the executable
818 cannot be done cheaply).  This means for optimization \tts{prelink}
819 should assign addresses from a 24MB region below the executable first, assuming
820 most of the executables are smaller than those remaining 8MB.
821 \tts{prelink} assigns these from higher to lower addresses.  When this
822 region is full, \tts{prelink} starts from address 0x40000
823 \footnote{To leave some pages unmapped to catch \tts{NULL} pointer
824 dereferences.} up till the bottom of the first area.  Only when
825 all these areas are full, \tts{prelink} starts picking addresses high above
826 the executable, so that sufficient space is left in between to leave room
827 for \tts{brk}.
828 When \tts{-R} option is specified, \tts{prelink} needs to honor it, but
829 in a way which doesn't totally kill this optimization.  So it picks up
830 a random start base within each of the 3 regions separately, splitting
831 them into 6 regions.
832
833 Another architecture which needs to be handled specially is IA-32
834 when using \tts{Exec-Shield}.  The IA-32 architecture doesn't have an
835 bit to disable execution for each page, only for each segment.  All readable
836 pages are normally executable.  This means the stack is usually executable,
837 as is memory allocated by \tts{malloc}.  This is undesirable for security reasons,
838 exploits can then overflow a buffer on the stack to transfer control
839 to code it creates on the stack.
840 Only very few programs actually need an executable stack.  For example
841 programs using GCC trampolines for nested functions need it or when
842 an application itself creates executable code on the stack and calls it.
843 \tts{Exec-Shield} works around this IA-32 architecture deficiency
844 by using a separate code segment, which starts at address 0 and spans
845 address space until its limit, highest page which needs to
846 be executable.  This is dynamically changed when some page with higher
847 address than the limit needs to be executable (either because of \tts{mmap}
848 with \tts{PROT\_EXEC} bit set, or \tts{mprotect} with \tts{PROT\_EXEC}
849 of an existing mapping).  This kind of protection is of course only
850 effective if the limit is as low as possible.  The kernel tries to
851 put all new mappings with \tts{PROT\_EXEC} set and \tts{NULL} address low.
852 If possible into {\sl ASCII Shield area} (first 16MB of address space)
853 \nomenclature{ASCII Shield area}{First 16MB of address space on 32-bit
854 architectures.  These addresses have zeros in upper 8 bits,
855 which on little endian architectures are stored as last byte of the address
856 and on big endian architectures as first byte of the address.
857 A zero byte terminates string, so it is hard to control the exact
858 arguments of a function if they are placed on the stack above the
859 address.  On big endian machines, it is even hard to control the
860 low 24 bits of the address}, if not, at least below the executable.
861 If \tts{prelink} detects \tts{Exec-Shield}, it tries to do the same as
862 kernel when assigning addresses, i.e. prefers to assign addresses in
863 {\sl ASCII Shield area} and continues with other addresses below
864 the program.  It needs to leave first 1MB plus 4KB of address space
865 unallocated though, because that range is often used by programs
866 using \tts{vm86} system call.
867
868 \section{Relocation of libraries}
869
870 When a shared library has a base address assigned, it needs to be relocated
871 so that the base address is equal to the first \tts{PT\_LOAD} segment's
872 \tts{p\_vaddr}.  The effect of this operation should be bitwise identical
873 as if the library were linked with that base address originally.
874 That is, the following scripts should produce identical output:
875
876 \noindent{{\small\begin{verbatim}
877 $ gcc -g -shared -o libfoo.so.1.0.0 -Wl,-h,libfoo.so.1 \
878       input1.o input2.o somelib.a
879 $ prelink --reloc-only=0x54321000 libfoo.so.1.0.0
880 \end{verbatim}
881 \prelinklistingcaption{Script to relocate a shared library after linking using \tts{prelink}}}
882
883 and:
884 \noindent{\small\begin{verbatim}
885 $ gcc -shared -Wl,--verbose 2>&1 > /dev/null \
886   | sed -e '/^======/,/^======/!d' \
887         -e '/^======/d;s/0\( + SIZEOF_HEADERS\)/0x54321000\1/' \
888         > libfoo.so.lds
889 $ gcc -Wl,-T,libfoo.so.lds -g -shared -o libfoo.so.1.0.0 \
890       -Wl,-h,libfoo.so.1 input1.o input2.o somelib.a
891 \end{verbatim}}
892 \prelinklistingcaption{Script to link a shared library at non-standard base}}
893
894 The first script creates a normal shared library with the default
895 base address 0 and then uses \tts{prelink}'s special mode when it just
896 relocates a library to a given address.  The second script first modifies
897 a built-in GNU linker script for linking of shared libraries, so that
898 the base address is the one given instead of zero and stores it into a
899 temporary file.  Then it creates a shared library using that linker script.
900
901 The relocation operation involves mostly adding the difference between
902 old and new base address to all \tts{ELF} fields which contain values
903 representing virtual addresses of the shared library
904 (or in the program header table also representing physical addresses).
905 File offsets need to be unmodified.  Most places where the adjustments
906 need to be done are clear, \tts{prelink} just has to watch \tts{ELF} spec
907 to see which fields contain virtual addresses.
908
909 One problem is with absolute symbols.  \tts{Prelink} has no way to find
910 out if an absolute symbol in a shared library is really meant as
911 absolute and thus not changing during relocation, or if it is an address
912 of some place in the shared library outside of any section or on their
913 edge.  For instance symbols created in the GNU linker's script outside
914 of section directives have all \tts{SHN\_ABS} section, yet they can be
915 location in the library (e.g. \tts{symbolfoo~=~.}) or they can be absolute
916 (e.g. \tts{symbolbar~=~0x12345000}).  This distinction is lost at link
917 time.  But the dynamic linker when looking up symbols doesn't make any
918 distinction between them, all addresses during dynamic lookup have the
919 load offset added to it.  \tts{Prelink} chooses to relocate any absolute
920 symbols with value bigger than zero, that way \tts{prelink --reloc-only}
921 gets bitwise identical output with linking directly at the different base
922 in almost all real-world cases.  Thread Local Storage symbols (those with
923 \tts{STT\_TLS} type) are never relocated, as their values are relative
924 to start of shared library's thread local area.
925
926 When relocating the dynamic section there are no bits which tell if
927 a particular dynamic tag uses \tts{d\_un.d\_ptr} (which needs to
928 be adjusted) or \tts{d\_un.d\_val} (which needs to be left as is).
929 So \tts{prelink} has to hardcode a list of well known architecture
930 independent dynamic tags which need adjusting and have a hook for
931 architecture specific dynamic tag adjustment.  Sun came up with
932 \tts{DT\_ADDRRNGLO} to \tts{DT\_ADDRRNGHI} and \tts{DT\_VALRNGLO}
933 to \tts{DT\_VALRNGHI} dynamic tag number ranges, so at least as
934 long as these ranges are used for new dynamic tags \tts{prelink}
935 can relocate correctly even without listing them all explicitly.
936
937 When relocating \tts{.rela.*} or \tts{.rel.*} sections, which is
938 done in architecture specific code, relative relocations and on \tts{.got.plt}
939 using architectures also \tts{PLT} relocations typically need an
940 adjustment.  The adjustment needs to be done in either \tts{r\_addend} field
941 of the \tts{ElfNN\_Rela} structure, in the memory pointed by \tts{r\_offset},
942 or in both locations.
943 On some architectures what needs adjusting is not even the same for all relative relocations.
944 Relative relocations against some sections need to have \tts{r\_addend}
945 adjusted while others need to have memory adjusted.
946 On many architectures, first few words in \tts{GOT} are special and some
947 of them need adjustment.
948
949 The hardest part of the adjustment is handling the debugging sections.
950 These are non-allocated sections which typically have no corresponding
951 relocation section associated with them.  \tts{Prelink} has to match the various
952 debuggers in what fields it adjusts and what are skipped.
953 As of this writing \tts{prelink} should handle
954 \href{http://www.eagercon.com/dwarf/dwarf-2.0.0.pdf}%
955 {\tts{DWARF 2} [15]} standard as corrected (and extended) by
956 \href{http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf}%
957 {\tts{DWARF 3 draft} [16]},
958 \href{http://sources.redhat.com/cgi-bin/cvsweb.cgi/src/gdb/doc/stabs.texinfo?cvsroot=src}%
959 {\tts{Stabs} [17]} with GCC extensions and Alpha or MIPS \tts{Mdebug}.
960
961 \tts{DWARF 2} debugging information involves many separate sections,
962 each of them with a unique format which needs to be relocated differently.
963 For relocation of the \tts{.debug\_info} section compilation units \tts{prelink} has to
964 parse the corresponding part of the \tts{.debug\_abbrev} section, adjust all
965 values of attributes that are using the \tts{DW\_FORM\_addr} form and adjust embedded
966 location lists.  \tts{.debug\_ranges} and \tts{.debug\_loc} section
967 portions depend on the exact place in \tts{.debug\_info} section from
968 which they are referenced, so that \tts{prelink} can keep track of their
969 base address.  \tts{DWARF} debugging format is very extendable, so
970 \tts{prelink} needs to be very conservative when it sees unknown extensions.
971 It needs to fail prelinking instead of silently break debugging information
972 if it sees an unknown \tts{.debug\_*} section, unknown attribute form
973 or unknown attribute with one of the \tts{DW\_FORM\_block*} forms, as
974 they can potentially embed addresses which would need adjustment.
975
976 For \tts{stabs} \tts{prelink} tried to match GDB behavior.  For
977 \tts{N\_FUN}, it needs to differentiate between function start and
978 function address which are both encoded with this type, the rest of types
979 either always need relocating or never.  And similarly to \tts{DWARF 2}
980 handling, it needs to reject unknown types.
981
982 The relocation code in \tts{prelink} is a little bit more generic
983 than what is described above, as it is used also by other parts of
984 \tts{prelink}, when growing sections in a middle of the shared library
985 during \tts{REL} to \tts{RELA} conversion.  All adjustment functions
986 get passed both the offset it should add to virtual addresses and
987 a start address.  Adjustment is only done if the old virtual address
988 was bigger or equal than the start address.
989
990 \section{REL to RELA conversion}
991
992 On architectures which normally use the \tts{REL} format for relocations instead
993 of \tts{RELA} (IA-32, ARM and MIPS), if certain relocation types use the
994 memory \tts{r\_offset} points to during relocation, \tts{prelink} has to
995 either convert them to a different relocation type which doesn't use
996 the memory value, or the whole \tts{.rel.dyn} section needs to be converted
997 to \tts{RELA} format.  Let's describe it on an example on IA-32 architecture:
998
999 \noindent{{\small\begin{verbatim}
1000 $ cat > test1.c <<EOF
1001 extern int i[4];
1002 int *j = i + 2;
1003 EOF
1004 $ cat > test2.c <<EOF
1005 int i[4];
1006 EOF
1007 $ gcc -nostdlib -shared -fpic -s -o test2.so test2.c
1008 $ gcc -nostdlib -shared -fpic -o test1.so test1.c ./test2.so
1009 $ readelf -l test1.so | grep LOAD | head -1
1010   LOAD           0x000000 0x00000000 0x00000000 0x002b8 0x002b8 R E 0x1000
1011 $ readelf -l test2.so | grep LOAD | head -1
1012   LOAD           0x000000 0x00000000 0x00000000 0x00244 0x00244 R E 0x1000
1013 $ readelf -r test1.so
1014
1015 Relocation section '.rel.dyn' at offset 0x2b0 contains 1 entries:
1016  Offset     Info    Type            Sym.Value  Sym. Name
1017 000012b8  00000d01 R_386_32          00000000   i
1018 $ objdump -s -j .data test1.so
1019
1020 test1.so:     file format elf32-i386
1021
1022 Contents of section .data:
1023  12b8 08000000                             ....
1024 $ readelf -s test2.so | grep i\$
1025     11: 000012a8    16 OBJECT  GLOBAL DEFAULT    8 i
1026 $ prelink -N ./test1.so ./test2.so
1027 $ readelf -l test1.so | grep LOAD | head -1
1028   LOAD           0x000000 0x04dba000 0x04dba000 0x002bc 0x002bc R E 0x1000
1029 $ readelf -l test2.so | grep LOAD | head -1
1030   LOAD           0x000000 0x04db6000 0x04db6000 0x00244 0x00244 R E 0x1000
1031 $ readelf -r test1.so
1032
1033 Relocation section '.rel.dyn' at offset 0x2b0 contains 1 entries:
1034  Offset     Info    Type            Sym.Value  Sym. Name + Addend
1035 04dbb2bc  00000d01 R_386_32          00000000   i + 8
1036 $ objdump -s -j .data test1.so
1037
1038 test1.so:     file format elf32-i386
1039
1040 Contents of section .data:
1041  4dbb2bc b072db04                             .r..
1042 $ readelf -s test2.so | grep i\$
1043     11: 04db72a8    16 OBJECT  GLOBAL DEFAULT    8 i
1044 \end{verbatim}}
1045 \prelinklistingcaption{\tts{REL} to \tts{RELA} conversion example}}
1046
1047 This relocation is against {\sl i + 8}, where the addend is stored at the memory
1048 location pointed by \tts{r\_offset}.  \tts{Prelink} assigned base address
1049 0x4dba000 to \tts{test1.so} and 0x4db6000 to \tts{test2.so}.
1050 \tts{Prelink} above converted the \tts{REL} section in \tts{test1.so} to
1051 \tts{RELA}, but let's assume it did not.  All output containing {\sl 2bc}
1052 above would change to {\sl 2b8} (that changed above only because \tts{.rel.dyn}
1053 section grew up by 4 bytes during the conversion to \tts{RELA} format),
1054 the rest would stay unchanged.
1055 When some program linked against \tts{test1.so} was prelinked,
1056 the (only) relocation in \tts{test1.so} would not be used and {\sl j} would
1057 contain the right value, 0x4db72b0 (address of {\sl i + 8}; note that IA-32
1058 is little endian, so the values in .data section are harder to read
1059 for a human).  Now, let's assume one of the shared libraries the executable
1060 is linked against is upgraded.  This means prelink information cannot
1061 be used, as it is out of date.  Let's assume it was a library other
1062 than \tts{test2.so}.  Normal relocation processing for \tts{test1.so}
1063 needs to happen.  Standard \tts{R\_386\_32} calculation is \tts{S~+~A},
1064 in this case 0x4db72a8 + 0x4db72b0 = 0x9b6e558 and {\sl j} contains wrong
1065 value.  Either \tts{test2.so} could change and now the {\sl i} variable would
1066 have different address, or some other shared library linked to the executable
1067 could overload symbol {\sl i}.  Without additional information the dynamic
1068 linker cannot find out the addend is 8.
1069
1070 The original value of a symbol could perhaps be stored in some special
1071 allocated section and the dynamic linker could do some magic to locate it,
1072 but it would mean standard relocation handling code in the dynamic linker
1073 cannot be used for relocation processing of prelinked shared libraries
1074 where prelinking information cannot be used.
1075 So \tts{prelink} in this case converts the whole \tts{.rel.dyn} section
1076 into the \tts{RELA} format, the addend is stored in \tts{r\_addend} field
1077 and when doing relocation processing, it really doesn't matter what
1078 value is at the memory location pointed by \tts{r\_offset}.
1079 The disadvantage of this is that the relocation section
1080 grew by 50\%.  If prelinking information can be used, it shouldn't matter much,
1081 since the section is never loaded at runtime because it is not accessed.
1082 If prelinking cannot be used, whether because it is out of date or
1083 because the shared library has been
1084 loaded by \tts{dlopen}, it will increase memory footprint, but it is read-only
1085 memory which is typically not used after startup and can be discarded
1086 as it is backed out by the file containing the shared library.
1087
1088 At least on IA-32, \tts{REL} to \tts{RELA} conversion is not always
1089 necessary.  If \tts{R\_386\_32} added is originally 0, \tts{prelink}
1090 can instead change its type to \tts{R\_386\_GLOB\_DAT}, which is a
1091 similar dynamic relocation, but calculated as \tts{S} instead of
1092 \tts{S~+~A}.  There is no similar conversion for \tts{R\_386\_PC32}
1093 possible though, on the other side this relocation type should never
1094 appear in position independent shared libraries, only in position
1095 dependent code.  On ARM, the situation is the same, just using
1096 different relocation names (\tts{R\_ARM\_32}, \tts{R\_ARM\_GLOB\_DAT}
1097 and \tts{R\_ARM\_PC24}).
1098
1099 The \tts{.rel.plt} section doesn't have to be converted to \tts{RELA}
1100 format on either of these architectures, if the conversion is needed,
1101 all other \tts{.rel.*} allocated sections, which have to be adjacent
1102 as they are pointed to by \tts{DT\_REL} and \tts{DT\_RELSZ} dynamic tags,
1103 have to be converted together.  The conversion itself is fairly easy,
1104 some architecture specific code just has to fetch the original addend
1105 from memory pointed by the relocation and store it into \tts{r\_addend}
1106 field (or clear \tts{r\_addend} if the particular relocation type
1107 never uses the addend).  The main problem is that when the conversion
1108 happens, the \tts{.rel.dyn} section grows by 50\% and there needs to be
1109 room for that in the read-only loadable segment of the shared library.
1110
1111 In shared libraries it is always possible to grow the first read-only
1112 \tts{PT\_LOAD} segment by adding the additional data at the beginning
1113 of the read-only segment, as the shared library is relocatable.
1114 \tts{Prelink} can relocate the whole shared library to a higher address
1115 than it has assigned for it.  The file offsets of all sections
1116 and the section header table file offset need to be increased,
1117 but the \tts{ELF} header and program headers need to stay at the beginning
1118 of the file.  The relocation section can then be moved to the newly created
1119 space between the end of the program header table and the first section.
1120
1121 Moving the section from the old location to the newly created space
1122 would leave often very big gap in virtual address space as well as in
1123 the file at the old location of the relocation section.  Fortunately the
1124 linker typically puts special \tts{ELF} sections including allocated
1125 relocation section before the code section and other read-only sections
1126 under user's control.  These special sections are intended for dynamic
1127 linking only.  Their addresses are stored just in the \tts{.dynamic} section
1128 and \tts{prelink} can easily adjust them there.  There is no need for
1129 a shared library to store address of one of the special sections
1130 into its code or data sections and existing linkers in fact don't create
1131 such references.  When growing the relocation section, \tts{prelink}
1132 checks whether all sections before the relocation section are
1133 special
1134 \footnote{As special sections \tts{prelink} considers sections with
1135 \tts{SHT\_NOTE}, \tts{SHT\_HASH}, \tts{SHT\_DYNSYM}, \tts{SHT\_STRTAB},
1136 \tts{SHT\_GNU\_verdef}, \tts{SHT\_GNU\_verneed}, \tts{SHT\_GNU\_versym},
1137 \tts{SHT\_REL} or \tts{SHT\_RELA} type or the \tts{.interp} section.}
1138 and if they are, just moves them to lower addresses, so that the
1139 newly created space is right above the relocation section.
1140 The advantage is that instead of moving all sections by the size of
1141 the new relocation section they can be adjusted ideally just by the
1142 difference between old and new relocation section size.
1143
1144 There are two factors which can increase the necessary adjustment of
1145 all higher sections.  The first is required section alignment of any
1146 allocated section above the relocation section.  \tts{Prelink} needs
1147 to find the highest section alignment among those sections and
1148 increase the adjustment from the difference between old and new
1149 relocation section up to the next multiple of that alignment.
1150
1151 The second factor is only relevant to shared libraries where linker
1152 optimized the data segment placement.  Traditionally linker assigned
1153 the end address of the read-only segment plus the architecture's
1154 maximum \tts{ELF} page size as the start address of the read-write
1155 segment.  While this created smallest file sizes of the shared libraries,
1156 it often wasted one page in the read-write segment because of partial
1157 pages.  When linker optimizes such that less space is wasted in partial
1158 pages, the distance between read-only and read-write segments can be
1159 smaller than architecture specific maximum \tts{ELF} page size.
1160 \tts{Prelink} has to take this into account, so that when adjusting
1161 the sections the read-only and read-write segment don't end up on the
1162 same page.  Unfortunately \tts{prelink} cannot increase or decrease
1163 the distance between the read-only and read-write segments, since
1164 it is possible that the shared library has relative addresses of
1165 any allocated code, data or \tts{.bss} sections
1166 stored in its sections without any relocations which would allow
1167 \tts{prelink} to change them.  \tts{Prelink} has to move all sections
1168 starting with the first allocated \tts{SHT\_PROGBITS} section other
1169 than \tts{.interp} up to the last allocated \tts{SHT\_PROGBITS} or
1170 \tts{SHT\_NOBITS} section as a block and thus needs to increase
1171 the adjustment in steps of the highest section alignment as many times
1172 times as needed so that the segments end up in different pages.
1173 Below are 3 examples:
1174
1175 \noindent{{\small\begin{verbatim}
1176 $ cat > test1.c <<EOF
1177 int i[2] __attribute__((aligned (32)));
1178 #define J1(N) int *j##N = &i[1];
1179 #define J2(N) J1(N##0) J1(N##1) J1(N##2) J1(N##3) J1(N##4)
1180 #define J3(N) J2(N##0) J2(N##1) J2(N##2) J2(N##3) J2(N##4)
1181 #define J4(N) J3(N##0) J3(N##1) J3(N##2) J3(N##3) J3(N##4)
1182 J4(0) J4(1) J3(2) J3(3) J1(4)
1183 const int l[256] = { [10] = 1 };
1184 /* Put a zero sized section at the end of read-only segment,
1185    so that the end address of the segment is printed.  */
1186 asm (".section ro_seg_end, \"a\"; .previous");
1187 EOF
1188 $ gcc -shared -O2 -nostdlib -fpic -o test1.so test1.c
1189 $ readelf -S test1.so | grep '^  \['
1190   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
1191   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
1192   [ 1] .hash             HASH            000000b4 0000b4 000930 04   A  2   0  4
1193   [ 2] .dynsym           DYNSYM          000009e4 0009e4 001430 10   A  3   d  4
1194   [ 3] .dynstr           STRTAB          00001e14 001e14 000735 00   A  0   0  1
1195   [ 4] .rel.dyn          REL             0000254c 00254c 000968 08   A  2   0  4
1196   [ 5] .text             PROGBITS        00002eb4 002eb4 000000 00  AX  0   0  4
1197   [ 6] .rodata           PROGBITS        00002ec0 002ec0 000400 00   A  0   0 32
1198   [ 7] ro_seg_end        PROGBITS        000032c0 0032c0 000000 00   A  0   0  1
1199   [ 8] .data             PROGBITS        000042c0 0032c0 0004b4 00  WA  0   0  4
1200   [ 9] .dynamic          DYNAMIC         00004774 003774 000070 08  WA  3   0  4
1201   [10] .got              PROGBITS        000047e4 0037e4 00000c 04  WA  0   0  4
1202   [11] .bss              NOBITS          00004800 003800 000008 00  WA  0   0 32
1203   [12] .comment          PROGBITS        00000000 003800 000033 00      0   0  1
1204   [13] .shstrtab         STRTAB          00000000 003833 000075 00      0   0  1
1205   [14] .symtab           SYMTAB          00000000 003b28 001470 10     15  11  4
1206   [15] .strtab           STRTAB          00000000 004f98 000742 00      0   0  1
1207 $ readelf -l test1.so | grep LOAD
1208   LOAD           0x000000 0x00000000 0x00000000 0x032c0 0x032c0 R E 0x1000
1209   LOAD           0x0032c0 0x000042c0 0x000042c0 0x00530 0x00548 RW  0x1000
1210 $ prelink -N ./test1.so
1211 $ readelf -l test1.so | grep LOAD
1212   LOAD           0x000000 0x02000000 0x02000000 0x03780 0x03780 R E 0x1000
1213   LOAD           0x003780 0x02004780 0x02004780 0x00530 0x00548 RW  0x1000
1214 $ readelf -S test1.so | grep '^  \['
1215   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
1216   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
1217   [ 1] .hash             HASH            020000b4 0000b4 000930 04   A  2   0  4
1218   [ 2] .dynsym           DYNSYM          020009e4 0009e4 001430 10   A  3   d  4
1219   [ 3] .dynstr           STRTAB          02001e14 001e14 000735 00   A  0   0  1
1220   [ 4] .rel.dyn          RELA            0200254c 00254c 000e1c 0c   A  2   0  4
1221   [ 5] .text             PROGBITS        02003374 003374 000000 00  AX  0   0  4
1222   [ 6] .rodata           PROGBITS        02003380 003380 000400 00   A  0   0 32
1223   [ 7] ro_seg_end        PROGBITS        02003780 003780 000000 00   A  0   0  1
1224   [ 8] .data             PROGBITS        02004780 003780 0004b4 00  WA  0   0  4
1225   [ 9] .dynamic          DYNAMIC         02004c34 003c34 000070 08  WA  3   0  4
1226   [10] .got              PROGBITS        02004ca4 003ca4 00000c 04  WA  0   0  4
1227   [11] .bss              NOBITS          02004cc0 003cc0 000008 00  WA  0   0 32
1228   [12] .comment          PROGBITS        00000000 003cc0 000033 00      0   0  1
1229   [13] .gnu.liblist      GNU_LIBLIST     00000000 003cf3 000000 14     14   0  4
1230   [14] .gnu.libstr       STRTAB          00000000 003cf3 000000 00      0   0  1
1231   [15] .gnu.prelink_undo PROGBITS        00000000 003cf4 00030c 01      0   0  4
1232   [16] .shstrtab         STRTAB          00000000 004003 0000a0 00      0   0  1
1233   [17] .symtab           SYMTAB          00000000 0043a0 001470 10     18  11  4
1234   [18] .strtab           STRTAB          00000000 005810 000742 00      0   0  1
1235 \end{verbatim}}
1236 \prelinklistingcaption{Growing read-only segment with segment distance one page}}
1237
1238 \begin{figure}[!ht]
1239 \centering
1240 \includegraphics[width=0.8\textwidth]{dso1}
1241 \caption{Growing read-only segment with segment distance one page}
1242 \end{figure}
1243
1244 In this example the read-write segment starts at address \tts{0x42c0}, which
1245 is one page above the end of read-only segment.  \tts{Prelink} needs to grow
1246 the read-only \tts{PT\_LOAD} segment by 50\% of \tts{.rel.dyn} size, i.e.
1247 \tts{0x4b4} bytes.  \tts{Prelink} just needs to round that up for the
1248 highest alignment (32 bytes required by \tts{.rodata} or \tts{.bss}
1249 sections) and moves all sections above \tts{.rel.dyn} by \tts{0x4c0} bytes.
1250
1251 \noindent{{\small\begin{verbatim}
1252 $ cat > test2.c <<EOF
1253 int i[2] __attribute__((aligned (32)));
1254 #define J1(N) int *j##N = &i[1];
1255 #define J2(N) J1(N##0) J1(N##1) J1(N##2) J1(N##3) J1(N##4)
1256 #define J3(N) J2(N##0) J2(N##1) J2(N##2) J2(N##3) J2(N##4)
1257 #define J4(N) J3(N##0) J3(N##1) J3(N##2) J3(N##3) J3(N##4)
1258 J4(0) J4(1) J3(2) J3(3) J1(4)
1259 const int l[256] = { [10] = 1 };
1260 int k[670];
1261 asm (".section ro_seg_end, \"a\"; .previous");
1262 EOF
1263 $ gcc -shared -O2 -nostdlib -fpic -o test2.so test2.c
1264 $ readelf -S test2.so | grep '^  \['
1265   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
1266   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
1267   [ 1] .hash             HASH            000000b4 0000b4 000934 04   A  2   0  4
1268   [ 2] .dynsym           DYNSYM          000009e8 0009e8 001440 10   A  3   d  4
1269   [ 3] .dynstr           STRTAB          00001e28 001e28 000737 00   A  0   0  1
1270   [ 4] .rel.dyn          REL             00002560 002560 000968 08   A  2   0  4
1271   [ 5] .text             PROGBITS        00002ec8 002ec8 000000 00  AX  0   0  4
1272   [ 6] .rodata           PROGBITS        00002ee0 002ee0 000400 00   A  0   0 32
1273   [ 7] ro_seg_end        PROGBITS        000032e0 0032e0 000000 00   A  0   0  1
1274   [ 8] .data             PROGBITS        00004000 004000 0004b4 00  WA  0   0  4
1275   [ 9] .dynamic          DYNAMIC         000044b4 0044b4 000070 08  WA  3   0  4
1276   [10] .got              PROGBITS        00004524 004524 00000c 04  WA  0   0  4
1277   [11] .bss              NOBITS          00004540 004540 000a88 00  WA  0   0 32
1278   [12] .comment          PROGBITS        00000000 004540 000033 00      0   0  1
1279   [13] .shstrtab         STRTAB          00000000 004573 000075 00      0   0  1
1280   [14] .symtab           SYMTAB          00000000 004868 001480 10     15  11  4
1281   [15] .strtab           STRTAB          00000000 005ce8 000744 00      0   0  1
1282 $ readelf -l test2.so | grep LOAD
1283   LOAD           0x000000 0x00000000 0x00000000 0x032e0 0x032e0 R E 0x1000
1284   LOAD           0x004000 0x00004000 0x00004000 0x00530 0x00fc8 RW  0x1000
1285 $ prelink -N ./test2.so
1286 $ readelf -l test2.so | grep LOAD
1287   LOAD           0x000000 0x02000000 0x02000000 0x037a0 0x037a0 R E 0x1000
1288   LOAD           0x0044c0 0x020044c0 0x020044c0 0x00530 0x00fc8 RW  0x1000
1289 $ readelf -S test2.so | grep '^  \['
1290   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
1291   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
1292   [ 1] .hash             HASH            020000b4 0000b4 000934 04   A  2   0  4
1293   [ 2] .dynsym           DYNSYM          020009e8 0009e8 001440 10   A  3   d  4
1294   [ 3] .dynstr           STRTAB          02001e28 001e28 000737 00   A  0   0  1
1295   [ 4] .rel.dyn          RELA            02002560 002560 000e1c 0c   A  2   0  4
1296   [ 5] .text             PROGBITS        02003388 003388 000000 00  AX  0   0  4
1297   [ 6] .rodata           PROGBITS        020033a0 0033a0 000400 00   A  0   0 32
1298   [ 7] ro_seg_end        PROGBITS        020037a0 0037a0 000000 00   A  0   0  1
1299   [ 8] .data             PROGBITS        020044c0 0044c0 0004b4 00  WA  0   0  4
1300   [ 9] .dynamic          DYNAMIC         02004974 004974 000070 08  WA  3   0  4
1301   [10] .got              PROGBITS        020049e4 0049e4 00000c 04  WA  0   0  4
1302   [11] .bss              NOBITS          02004a00 004a00 000a88 00  WA  0   0 32
1303   [12] .comment          PROGBITS        00000000 004a00 000033 00      0   0  1
1304   [13] .gnu.liblist      GNU_LIBLIST     00000000 004a33 000000 14     14   0  4
1305   [14] .gnu.libstr       STRTAB          00000000 004a33 000000 00      0   0  1
1306   [15] .gnu.prelink_undo PROGBITS        00000000 004a34 00030c 01      0   0  4
1307   [16] .shstrtab         STRTAB          00000000 004d43 0000a0 00      0   0  1
1308   [17] .symtab           SYMTAB          00000000 0050e0 001480 10     18  11  4
1309   [18] .strtab           STRTAB          00000000 006560 000744 00      0   0  1
1310 \end{verbatim}}
1311 \prelinklistingcaption{Growing read-only segment not requiring additional padding}}
1312
1313 \begin{figure}[!ht]
1314 \centering
1315 \includegraphics[width=0.8\textwidth]{dso2}
1316 \caption{Growing read-only segment not requiring additional padding}
1317 \end{figure}
1318
1319 In the second example \tts{prelink} can grow by just \tts{0x4c0} bytes as
1320 well, eventhough the distance between read-write and read-only segment
1321 is just \tts{0xd20} bytes.  With this distance, hypothetical adjustment
1322 by any size less than \tts{0xd21} bytes (modulo 4096) would need just
1323 rounding up to the next multiple of 32 bytes, while adjustments
1324 from \tts{0xd21} up to \tts{0xfe0} would require adjustments in
1325 multiples of 4096 bytes.
1326
1327 \noindent{{\small\begin{verbatim}
1328 $ cat > test3.c <<EOF
1329 int i[2] __attribute__((aligned (32)));
1330 #define J1(N) int *j##N = &i[1];
1331 #define J2(N) J1(N##0) J1(N##1) J1(N##2) J1(N##3) J1(N##4)
1332 #define J3(N) J2(N##0) J2(N##1) J2(N##2) J2(N##3) J2(N##4)
1333 #define J4(N) J3(N##0) J3(N##1) J3(N##2) J3(N##3) J3(N##4)
1334 J4(0) J4(1) J3(2) J3(3) J1(4)
1335 int k[670];
1336 asm (".section ro_seg_end, \"a\"; .previous");
1337 EOF
1338 $ gcc -shared -O2 -nostdlib -fpic -o test3.so test3.c
1339 $ readelf -S test3.so | grep '^  \['
1340   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
1341   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
1342   [ 1] .hash             HASH            000000b4 0000b4 00092c 04   A  2   0  4
1343   [ 2] .dynsym           DYNSYM          000009e0 0009e0 001420 10   A  3   c  4
1344   [ 3] .dynstr           STRTAB          00001e00 001e00 000735 00   A  0   0  1
1345   [ 4] .rel.dyn          REL             00002538 002538 000968 08   A  2   0  4
1346   [ 5] .text             PROGBITS        00002ea0 002ea0 000000 00  AX  0   0  4
1347   [ 6] ro_seg_end        PROGBITS        00002ea0 002ea0 000000 00   A  0   0  1
1348   [ 7] .data             PROGBITS        00003000 003000 0004b4 00  WA  0   0  4
1349   [ 8] .dynamic          DYNAMIC         000034b4 0034b4 000070 08  WA  3   0  4
1350   [ 9] .got              PROGBITS        00003524 003524 00000c 04  WA  0   0  4
1351   [10] .bss              NOBITS          00003540 003540 000a88 00  WA  0   0 32
1352   [11] .comment          PROGBITS        00000000 003540 000033 00      0   0  1
1353   [12] .shstrtab         STRTAB          00000000 003573 00006d 00      0   0  1
1354   [13] .symtab           SYMTAB          00000000 003838 001460 10     14  10  4
1355   [14] .strtab           STRTAB          00000000 004c98 000742 00      0   0  1
1356 $ readelf -l test3.so | grep LOAD
1357   LOAD           0x000000 0x00000000 0x00000000 0x02ea0 0x02ea0 R E 0x1000
1358   LOAD           0x003000 0x00003000 0x00003000 0x00530 0x00fc8 RW  0x1000
1359 $ prelink -N ./test3.so
1360 $ readelf -l test3.so | grep LOAD
1361   LOAD           0x000000 0x02000000 0x02000000 0x03ea0 0x03ea0 R E 0x1000
1362   LOAD           0x004000 0x02004000 0x02004000 0x00530 0x00fc8 RW  0x1000
1363 $ readelf -S test3.so | grep '^  \['
1364   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
1365   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
1366   [ 1] .hash             HASH            020000b4 0000b4 00092c 04   A  2   0  4
1367   [ 2] .dynsym           DYNSYM          020009e0 0009e0 001420 10   A  3   c  4
1368   [ 3] .dynstr           STRTAB          02001e00 001e00 000735 00   A  0   0  1
1369   [ 4] .rel.dyn          RELA            02002538 002538 000e1c 0c   A  2   0  4
1370   [ 5] .text             PROGBITS        02003ea0 003ea0 000000 00  AX  0   0  4
1371   [ 6] ro_seg_end        PROGBITS        02003ea0 003ea0 000000 00   A  0   0  1
1372   [ 7] .data             PROGBITS        02004000 004000 0004b4 00  WA  0   0  4
1373   [ 8] .dynamic          DYNAMIC         020044b4 0044b4 000070 08  WA  3   0  4
1374   [ 9] .got              PROGBITS        02004524 004524 00000c 04  WA  0   0  4
1375   [10] .bss              NOBITS          02004540 004540 000a88 00  WA  0   0 32
1376   [11] .comment          PROGBITS        00000000 004540 000033 00      0   0  1
1377   [12] .gnu.liblist      GNU_LIBLIST     00000000 004573 000000 14     13   0  4
1378   [13] .gnu.libstr       STRTAB          00000000 004573 000000 00      0   0  1
1379   [14] .gnu.prelink_undo PROGBITS        00000000 004574 0002e4 01      0   0  4
1380   [15] .shstrtab         STRTAB          00000000 00485b 000098 00      0   0  1
1381   [16] .symtab           SYMTAB          00000000 004bc8 001460 10     17  10  4
1382   [17] .strtab           STRTAB          00000000 006028 000742 00      0   0  1
1383 \end{verbatim}}
1384 \prelinklistingcaption{Growing read-only segment if page padding needed}}
1385
1386 \begin{figure}[!ht]
1387 \centering
1388 \includegraphics[width=0.8\textwidth]{dso3}
1389 \caption{Growing read-only segment if page padding needed}
1390 \end{figure}
1391
1392 In the last example the distance between \tts{PT\_LOAD} segments is very
1393 small, just \tts{0x160} bytes and the adjustment had to be done by 4096
1394 bytes.
1395
1396 % Fortunately, shared libraries are position independent, so all absolute
1397 % values in them are either stored in well known \tts{ELF} structures,
1398 % or have corresponding dynamic relocations.  The only problem might be
1399 % with relative relocations, which are resolved at link time.
1400 % The start of read-only \tts{PT\_LOAD} segment of shared libraries is
1401 % typically used by special sections used by the dynamic linker
1402 % (\tts{.hash}, \tts{.dynsym}, \tts{.dynstr}, \tts{.gnu.version*},
1403 % \tts{.rel*}, \tts{.note*}).  It makes no sense for a shared library to
1404 % have relocations against these sections or some addresses inside of them,
1405 % furthermore it is impossible to do it without specially crafted
1406 % linker script.  So \tts{prelink} makes the assumption that it can grow
1407 % freely the shared library after \tts{.rel.dyn} section, as long
1408 % as only sections mentioned above come before \tts{.rel.dyn} (it actually
1409 % checks section types, not names).  \tts{Prelink} certainly can grow the shared library
1410 % size in multiplies of \tts{ELF} architecture specific maximum page size,
1411 % but usually it can do better.  Particularly, \tts{prelink} can grow by the 50\% size
1412 % of \tts{.rel.dyn} section rounded up to the largest section alignment
1413 % in all sections following it, but it has to make sure that two
1414 % different \tts{PT\_LOAD} segments (typically the read-only and read-write)
1415 % will not share the same page, otherwise it needs to grow it more in
1416 % multiplies of the maximum section alignment until they are on different
1417 % pages.  Growing is done by using the shared library relocation code with
1418 % start address set to end of \tts{.rel.dyn} section.  \tts{.rel.plt}
1419 % section is then moved right to the end of \tts{.rel.dyn} section,
1420 % \tts{.dynamic} section needs updating all addresses, type of
1421 % relocation section, segment table needs to be adjusted accordingly
1422 % and file offsets in section header table as well.
1423
1424 \section{Conflicts}
1425
1426 As said earlier, if symbol lookup of some symbol in particular shared
1427 library results in different values when that shared library's natural
1428 search scope is used and when using search scope of the application the
1429 DSO is used in, this is considered a {\sl conflict}.
1430 Here is an example of a conflict on IA-32:
1431
1432 \noindent{{\small\begin{verbatim}
1433 $ cat > test1.c <<EOF
1434 int i;
1435 int *j = &i;
1436 int *foo (void) { return &i; }
1437 EOF
1438 $ cat > test2.c <<EOF
1439 int i;
1440 int *k = &i;
1441 int *bar (void) { return &i; }
1442 EOF
1443 $ cat > test.c <<EOF
1444 #include <stdio.h>
1445 extern int i, *j, *k, *foo (void), bar (void);
1446 int main (void)
1447 {
1448 #ifdef PRINT_I
1449   printf ("%p\n", &i);
1450 #endif
1451   printf ("%p %p %p %p\n", j, k, foo (), bar ());
1452 }
1453 EOF
1454 $ gcc -nostdlib -shared -fpic -s -o test1.so test1.c
1455 $ gcc -nostdlib -shared -fpic -o test2.so test2.c ./test1.so
1456 $ gcc -o test test.c ./test2.so ./test1.so
1457 $ ./test
1458 0x16137c 0x16137c 0x16137c 0x16137c
1459 $ readelf -r ./test1.so
1460
1461 Relocation section '.rel.dyn' at offset 0x2bc contains 2 entries:
1462  Offset     Info    Type            Sym.Value  Sym. Name
1463 000012e4  00000d01 R_386_32          00001368   i
1464 00001364  00000d06 R_386_GLOB_DAT    00001368   i
1465 $ prelink -N ./test ./test1.so ./test2.so
1466 $ LD_WARN= LD_TRACE_PRELINKING=1 LD_BIND_NOW=1 /lib/ld-linux.so.2 ./test1.so
1467         ./test1.so => ./test1.so (0x04db6000, 0x00000000)
1468 $ LD_WARN= LD_TRACE_PRELINKING=1 LD_BIND_NOW=1 /lib/ld-linux.so.2 ./test2.so
1469         ./test2.so => ./test2.so (0x04dba000, 0x00000000)
1470         ./test1.so => ./test1.so (0x04db6000, 0x00000000)
1471 $ LD_WARN= LD_TRACE_PRELINKING=1 LD_BIND_NOW=1 /lib/ld-linux.so.2 ./test \
1472   | sed 's/^[[:space:]]*/  /'
1473   ./test => ./test (0x08048000, 0x00000000)
1474   ./test2.so => ./test2.so (0x04dba000, 0x00000000)
1475   ./test1.so => ./test1.so (0x04db6000, 0x00000000)
1476   libc.so.6 => /lib/tls/libc.so.6 (0x00b22000, 0x00000000) TLS(0x1, 0x00000028)
1477   /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x00b0a000, 0x00000000)
1478 $ readelf -S ./test1.so | grep '\.data\|\.got'
1479   [ 6] .data             PROGBITS        04db72e4 0002e4 000004 00  WA  0   0  4
1480   [ 8] .got              PROGBITS        04db7358 000358 000010 04  WA  0   0  4
1481 $ readelf -r ./test1.so
1482
1483 Relocation section '.rel.dyn' at offset 0x2bc contains 2 entries:
1484  Offset     Info    Type            Sym.Value  Sym. Name
1485 04db72e4  00000d06 R_386_GLOB_DAT    04db7368   i
1486 04db7364  00000d06 R_386_GLOB_DAT    04db7368   i
1487 $ objdump -s -j .got -j .data test1.so
1488
1489 test1.so:     file format elf32-i386
1490
1491 Contents of section .data:
1492  4db72e4 6873db04                             hs..
1493 Contents of section .got:
1494  4db7358 e8120000 00000000 00000000 6873db04  ............hs..
1495 $ readelf -r ./test | sed '/\.gnu\.conflict/,$!d'
1496 Relocation section '.gnu.conflict' at offset 0x7ac contains 18 entries:
1497  Offset     Info    Type            Sym.Value  Sym. Name + Addend
1498 04db72e4  00000001 R_386_32                                     04dbb37c
1499 04db7364  00000001 R_386_32                                     04dbb37c
1500 00c56874  00000001 R_386_32                                     fffffff0
1501 00c56878  00000001 R_386_32                                     00000001
1502 00c568bc  00000001 R_386_32                                     fffffff4
1503 00c56900  00000001 R_386_32                                     ffffffec
1504 00c56948  00000001 R_386_32                                     ffffffdc
1505 00c5695c  00000001 R_386_32                                     ffffffe0
1506 00c56980  00000001 R_386_32                                     fffffff8
1507 00c56988  00000001 R_386_32                                     ffffffe4
1508 00c569a4  00000001 R_386_32                                     ffffffd8
1509 00c569c4  00000001 R_386_32                                     ffffffe8
1510 00c569d8  00000001 R_386_32                                     080485b8
1511 00b1f510  00000007 R_386_JUMP_SLOT                              00b91460
1512 00b1f514  00000007 R_386_JUMP_SLOT                              00b91080
1513 00b1f518  00000007 R_386_JUMP_SLOT                              00b91750
1514 00b1f51c  00000007 R_386_JUMP_SLOT                              00b912c0
1515 00b1f520  00000007 R_386_JUMP_SLOT                              00b91200
1516 $ ./test
1517 0x4dbb37c 0x4dbb37c 0x4dbb37c 0x4dbb37c
1518 \end{verbatim}}
1519 \prelinklistingcaption{Conflict example}}
1520
1521 In the example, among some conflicts caused by the dynamic linker and the C library,
1522 \footnote{Particularly in the example, the 5 \tts{R\_386\_JUMP\_SLOT} fixups
1523 are \tts{PLT} slots in the dynamic linker for memory allocator functions
1524 resolving to C library functions instead of dynamic linker's own trivial
1525 implementation.  First 10 \tts{R\_386\_32} fixups at offsets 0xc56874
1526 to 0xc569c4 are Thread Local Storage fixups in the C library and
1527 the fixup at 0xc569d8 is for {\sl \_IO\_stdin\_used} weak undefined symbol
1528 in the C library, resolving to a symbol with the same name in the executable.}
1529 there is a conflict for the symbol {\sl i} in \tts{test1.so} shared library.
1530 \tts{test1.so} has just itself in its natural symbol lookup scope (as proved
1531 by
1532
1533 \tts{LD\_WARN= LD\_TRACE\_PRELINKING=1 LD\_BIND\_NOW=1 /lib/ld-linux.so.2 ./test1.so}
1534
1535 command output), so when looking up symbol {\sl i} in this
1536 scope the definition in \tts{test1.so} is chosen.  \tts{test1.so} has two
1537 relocations against the symbol {\sl i}, one \tts{R\_386\_32} against \tts{.data}
1538 section and one \tts{R\_386\_GLOB\_DAT} against \tts{.got} section.  When
1539 prelinking \tts{test1.so} library, the dynamic linker stores the address of
1540 {\sl i} (0x4db7368) into both locations (at offsets 0x4db72e4 and 0x4db7364).
1541 The global symbol search scope in \tts{test} executable contains the executable
1542 itself, \tts{test2.so} and \tts{test1.so} libraries, \tts{libc.so.6} and
1543 the dynamic linker in the listed order.
1544 When doing symbol lookup for symbol {\sl i}
1545 in \tts{test1.so} when doing relocation processing of the whole executable,
1546 address of {\sl i} in \tts{test2.so} is returned as that symbol comes earlier
1547 in the global search scope.  So, when none of the libraries nor the executable
1548 is prelinked, the program prints 4 identical addresses.  If prelink didn't
1549 create conflict fixups for the two relocations against the symbol {\sl i}
1550 in \tts{test1.so}, prelinked executable (which bypasses normal relocation
1551 processing on startup) would print instead of the desired
1552
1553 \tts{0x4dbb37c 0x4dbb37c 0x4dbb37c 0x4dbb37c}
1554
1555 different addresses,
1556
1557 \tts{0x4db7368 0x4dbb37c 0x4db7368 0x4dbb37c}
1558
1559 That is a functionality change that \tts{prelink} cannot be permitted to
1560 make, so instead it fixes up the two locations by storing the desired
1561 value in there.  In this case \tts{prelink} really cannot avoid that
1562 - \tts{test1.so} shared library could be also used without \tts{test2.so}
1563 in some other executable's symbol search scope.
1564 Or there could be some executable linked with:
1565
1566 \noindent{{\small\begin{verbatim}
1567 $ gcc -o test2 test.c ./test1.so ./test2.so
1568 \end{verbatim}}
1569 \prelinklistingcaption{Conflict example with swapped order of libraries}}
1570
1571 where {\sl i} lookup in \tts{test1.so} and \tts{test2.so} is supposed
1572 to resolve to {\sl i} in \tts{test1.so}.
1573
1574 Now consider what happens if the executable is linked with \tts{-DPRINT\_I}:
1575
1576 \noindent{{\small\begin{verbatim}
1577 $ gcc -DPRINT_I -o test3 test.c ./test2.so ./test1.so
1578 $ ./test3
1579 0x804972c
1580 0x804972c 0x804972c 0x804972c 0x804972c
1581 $ prelink -N ./test3 ./test1.so ./test2.so
1582 $ readelf -S ./test2.so | grep '\.data\|\.got'
1583   [ 6] .data             PROGBITS        04dbb2f0 0002f0 000004 00  WA  0   0  4
1584   [ 8] .got              PROGBITS        04dbb36c 00036c 000010 04  WA  0   0  4
1585 $ readelf -r ./test2.so
1586
1587 Relocation section '.rel.dyn' at offset 0x2c8 contains 2 entries:
1588  Offset     Info    Type            Sym.Value  Sym. Name
1589 04dbb2f0  00000d06 R_386_GLOB_DAT    04dbb37c   i
1590 04dbb378  00000d06 R_386_GLOB_DAT    04dbb37c   i
1591 $ objdump -s -j .got -j .data test2.so
1592
1593 test2.so:     file format elf32-i386
1594
1595 Contents of section .data:
1596  4dbb2f0 7cb3db04                             |...            
1597 Contents of section .got:
1598  4dbb36c f4120000 00000000 00000000 7cb3db04  ............|...
1599 $ readelf -r ./test3
1600
1601 Relocation section '.rel.dyn' at offset 0x370 contains 4 entries:
1602  Offset     Info    Type            Sym.Value  Sym. Name
1603 08049720  00000e06 R_386_GLOB_DAT    00000000   __gmon_start__
1604 08049724  00000105 R_386_COPY        08049724   j
1605 08049728  00000305 R_386_COPY        08049728   k
1606 0804972c  00000405 R_386_COPY        0804972c   i
1607
1608 Relocation section '.rel.plt' at offset 0x390 contains 4 entries:
1609  Offset     Info    Type            Sym.Value  Sym. Name
1610 08049710  00000607 R_386_JUMP_SLOT   080483d8   __libc_start_main
1611 08049714  00000707 R_386_JUMP_SLOT   080483e8   printf
1612 08049718  00000807 R_386_JUMP_SLOT   080483f8   foo
1613 0804971c  00000c07 R_386_JUMP_SLOT   08048408   bar
1614
1615 Relocation section '.gnu.conflict' at offset 0x7f0 contains 20 entries:
1616  Offset     Info    Type            Sym.Value  Sym. Name + Addend
1617 04dbb2f0  00000001 R_386_32                                     0804972c
1618 04dbb378  00000001 R_386_32                                     0804972c
1619 04db72e4  00000001 R_386_32                                     0804972c
1620 04db7364  00000001 R_386_32                                     0804972c
1621 00c56874  00000001 R_386_32                                     fffffff0
1622 00c56878  00000001 R_386_32                                     00000001
1623 00c568bc  00000001 R_386_32                                     fffffff4
1624 00c56900  00000001 R_386_32                                     ffffffec
1625 00c56948  00000001 R_386_32                                     ffffffdc
1626 00c5695c  00000001 R_386_32                                     ffffffe0
1627 00c56980  00000001 R_386_32                                     fffffff8
1628 00c56988  00000001 R_386_32                                     ffffffe4
1629 00c569a4  00000001 R_386_32                                     ffffffd8
1630 00c569c4  00000001 R_386_32                                     ffffffe8
1631 00c569d8  00000001 R_386_32                                     080485f0
1632 00b1f510  00000007 R_386_JUMP_SLOT                              00b91460
1633 00b1f514  00000007 R_386_JUMP_SLOT                              00b91080
1634 00b1f518  00000007 R_386_JUMP_SLOT                              00b91750
1635 00b1f51c  00000007 R_386_JUMP_SLOT                              00b912c0
1636 00b1f520  00000007 R_386_JUMP_SLOT                              00b91200
1637 $ ./test3
1638 0x804972c
1639 0x804972c 0x804972c 0x804972c 0x804972c
1640 \end{verbatim}}
1641 \prelinklistingcaption{Conflict example with COPY relocation for conflicting symbol}}
1642
1643 Because the executable is not compiled as position independent code and
1644 \tts{main} function takes address of {\sl i} variable, the object
1645 file for \tts{test3.c} contains a \tts{R\_386\_32} relocation against
1646 {\sl i}.  The linker cannot make dynamic relocations against read-only
1647 segment in the executable, so the address of {\sl i} must be constant.
1648 This is accomplished by creating a new object {\sl i} in the executable's
1649 \tts{.dynbss} section and creating a dynamic \tts{R\_386\_COPY} relocation
1650 for it.  The relocation ensures that during startup the content of
1651 {\sl i} object earliest in the search scope without the executable
1652 is copied to this {\sl i} object in executable.  Now, unlike \tts{test}
1653 executable, in \tts{test3} executable {\sl i} lookups in both \tts{test1.so}
1654 and \tts{test2.so} libraries result in address of {\sl i} in the executable
1655 (instead of \tts{test2.so}).  This means that two conflict fixups
1656 are needed again for \tts{test1.so} (but storing 0x804972c instead of
1657 0x4dbb37c) and two new fixups are needed for \tts{test2.so}.
1658
1659 If the executable is compiled as position independent code,
1660
1661 \noindent{{\small\begin{verbatim}
1662 $ gcc -fpic -DPRINT_I -o test4 test.c ./test2.so ./test1.so
1663 $ ./test4
1664 0x4dbb37c
1665 0x4dbb37c 0x4dbb37c 0x4dbb37c 0x4dbb37c
1666 \end{verbatim}}
1667 \prelinklistingcaption{Conflict example with position independent code in the executable}}
1668
1669 the address of {\sl i} is stored in executable's \tts{.got} section,
1670 which is writable and thus can have dynamic relocation against it.
1671 So the linker creates a \tts{R\_386\_GLOB\_DAT} relocation against
1672 the \tts{.got} section, the symbol {\sl i} is undefined in the executable
1673 and no copy relocations are needed.  In this case, only \tts{test1.so}
1674 will need 2 fixups, \tts{test2.so} will not need any.
1675
1676 There are various reasons for conflicts:
1677 \begin{itemize}
1678 \item Improperly linked shared libraries.  If a shared library always needs
1679 symbols from some particular shared library, it should be linked against
1680 that library, usually by adding \tts{-lLIBNAME} to \tts{gcc -shared} command
1681 line used during linking of the shared library.  This both reduces conflict
1682 fixups in \tts{prelink} and makes the library easier to load using
1683 \tts{dlopen}, because applications don't have to remember that they have
1684 to load some other library first.  The best place to record the dependency
1685 is in the shared library itself.  Another reason is if the needed library
1686 uses symbol versioning for its symbols.  Not linking against that library
1687 can result in malfunctioning shared library.  \tts{Prelink} issues a warning for
1688 such libraries - \tts{Warning: {\sl library} has undefined non-weak symbols}.
1689 When linking a shared library, the \tts{-Wl,-z,defs} option can be used to
1690 ensure there are no such undefined non-weak symbols.  There are exceptions,
1691 when undefined non-weak symbols in shared libraries are desirable.
1692 One exception is when there are multiple shared libraries providing the
1693 same functionality, and a shared library doesn't care which one is used.
1694 An example can be e.g. \tts{libreadline.so.4}, which needs some terminal
1695 handling functions, which are provided be either \tts{libtermcap.so.2},
1696 or \tts{libncurses.so.5}.  Another exception is with plugins or other
1697 shared libraries which expect some symbols to be resolved to symbols
1698 defined in the executable.
1699 \item A library overriding functionality of some other library.  One example
1700 is e.g. C library and POSIX thread library.  Older versions of the GNU C library
1701 did not provide cancelable entry points required by the standard.  This is
1702 not needed for non-threaded applications.  So only the \tts{libpthread.so.0} shared
1703 library which provides POSIX threading support then overrode the
1704 cancellation entry points required by the standard by wrapper functions
1705 which provided the required functionality.  Although most recent versions
1706 of the GNU C library handle cancellation even in entry points in \tts{libc.so.6}
1707 (this was needed for cases when \tts{libc.so.6} comes earlier before
1708 \tts{libpthread.so.0} in symbol search scope and used to be worked around
1709 by non-standard handling of weak symbols in the dynamic linker), because
1710 of symbol versioning the symbols had to stay in \tts{libpthread.so.0}
1711 as well as in \tts{libc.so.6}.  This means every program using POSIX
1712 threads on Linux will have a couple of conflict fixups because of this.
1713 \item Programs which need copy relocations.  Although \tts{prelink} will
1714 resolve the copy relocations at prelinking time, if any shared library
1715 has relocations against the symbol which needed copy relocation, all such
1716 relocations will need conflict fixups.  Generally, it is better to not
1717 export variables from shared libraries in their APIs, instead provide
1718 accessor functions.
1719 \item Function pointer equality requirement for functions called from
1720 executables.  When address of some global function is taken, at least
1721 C and C++ require that this pointer is the same in the whole program.
1722 Executables typically contain position dependent code, so when code in the
1723 executable takes address of some function not defined in the executable itself,
1724 that address must be link time constant.  Linker accomplishes this by
1725 creating a \tts{PLT} slot for the function unless there was one already
1726 and resolving to the address of \tts{PLT} slot.  The symbol for the function
1727 is created with \tts{st\_value} equal to address of the \tts{PLT} slot,
1728 but \tts{st\_shndx} set to \tts{SHN\_UNDEF}.  Such symbols are treated
1729 specially by the dynamic linker, in that \tts{PLT} relocations
1730 resolve to first symbol in the global search scope after the executable,
1731 while symbol lookups for all other relocation types return the
1732 address of the symbol in the executable.  Unfortunately, GNU linker doesn't
1733 differentiate between taking address of a function in an executable (especially
1734 one for which no dynamic relocation is possible in case it is in read-only
1735 segment) and just calling the function, but never taking its address.
1736 If it cleared the \tts{st\_value} field of the \tts{SHN\_UNDEF} function symbols
1737 in case nothing in the executable takes the function's address, several \tts{prelink}
1738 conflict could disappear (\tts{SHN\_UNDEF} symbols with \tts{st\_value} set
1739 to 0 are treated always as real undefined symbols by the dynamic linker).
1740 \item \tts{COMDAT} code and data in C++.  C++ language has several places where
1741 it may need to emit some code or data without a clear unique
1742 compilation unit owning it.  Examples include taking address of an
1743 \tts{inline} function, local static variable in \tts{inline} functions,
1744 virtual tables for some classes (this depends on \tts{\#pragma interface}
1745 or \tts{\#pragma implementation} presence, presence of non-inline
1746 non-pure-virtual member function in the class, etc.), {\sl RTTI} info for them.
1747 Compilers and linkers handle these using various \tts{COMDAT} schemes,
1748 e.g. GNU linker's \tts{.gnu.linkonce*} special sections or using
1749 \tts{SHT\_GROUP}.  Unfortunately, all these duplicate merging schemes
1750 work only during linking of shared libraries or executables, no duplicate
1751 removal is done across shared libraries.  Shared libraries typically
1752 have relocations against their \tts{COMDAT} code or data objects (otherwise
1753 they wouldn't be at least in most cases emitted at all), so if there are
1754 \tts{COMDAT} duplicates across shared libraries or the executable, they
1755 lead to conflict fixups.  The linker theoretically could try to
1756 merge \tts{COMDAT} duplicates across shared libraries if specifically
1757 requested by the user (if a \tts{COMDAT} symbol is already present in
1758 one of the dependent shared libraries and is \tts{STB\_WEAK}, the linker
1759 could skip it).  Unfortunately, this only works as long as the user has
1760 full control over the dependent shared libraries, because the \tts{COMDAT}
1761 symbol could be exported from them just as a side effect of their
1762 implementation (e.g. they use some class internally).  When such libraries
1763 are rebuilt even with minor changes in their implementation (unfortunately
1764 with C++ shared libraries it is usually not very clear what part is exported
1765 ABI and what is not), some of those \tts{COMDAT} symbols in them could go
1766 away (e.g. because suddenly they use a different class internally and
1767 the previously used class is not referenced anywhere).  When \tts{COMDAT}
1768 objects are not merged across shared libraries, this makes no problems,
1769 as each library which needs the \tts{COMDAT} has its own copy.  But with
1770 \tts{COMDAT} duplicate removal between shared libraries there could suddenly
1771 be unresolved references and the shared libraries would need to be relinked.
1772 The only place where this could work safely is when a single package
1773 includes several C++ shared libraries which depend on each other.  They are
1774 then shipped always together and when one changes, all others need changing
1775 too.
1776 \end{itemize}
1777
1778 \section{Prelink optimizations to reduce number of conflict fixups}
1779
1780 \tts{Prelink} can optimize out some conflict fixups if it can prove that
1781 the changes are not observable by the application at runtime (opening its
1782 executable and reading it doesn't count).  If there is a data object in some
1783 shared library with a symbol that is overridden by a symbol in a different
1784 shared library earlier in global symbol lookup scope or in the executable, then
1785 that data object is likely never referenced and it shouldn't matter what it
1786 contains.  Examine the following example:
1787
1788 \noindent{{\small\begin{verbatim}
1789 $ cat > test1.c <<EOF
1790 int i, j, k;
1791 struct A { int *a; int *b; int *c; } x = { &i, &j, &k };
1792 struct A *y = &x;
1793 EOF
1794 $ cat > test2.c <<EOF
1795 int i, j, k;
1796 struct A { int *a; int *b; int *c; } x = { &i, &j, &k };
1797 struct A *z = &x;
1798 EOF
1799 $ cat > test.c <<EOF
1800 #include <stdio.h>
1801 extern struct A { int *a; int *b; int *c; } *y, *z;
1802 int main (void)
1803 {
1804   printf ("%p: %p %p %p\n", y, y->a, y->b, y->c);
1805   printf ("%p: %p %p %p\n", z, z->a, z->b, z->c);
1806 }
1807 EOF
1808 $ gcc -nostdlib -shared -fpic -s -o test1.so test1.c
1809 $ gcc -nostdlib -shared -fpic -o test2.so test2.c ./test1.so
1810 $ gcc -o test test.c ./test2.so ./test1.so
1811 $ ./test
1812 0xaf3314: 0xaf33b0 0xaf33a8 0xaf33ac
1813 0xaf3314: 0xaf33b0 0xaf33a8 0xaf33ac
1814 \end{verbatim}}
1815 \prelinklistingcaption{C example where conflict fixups could be optimized out}}
1816
1817 In this example there are 3 conflict fixups pointing into the 12 byte
1818 long {\sl x} object in \tts{test1.so} shared library (among other
1819 conflicts).  And nothing in the program can poke at {\sl x} content
1820 in \tts{test1.so}, simply because it has to look at it through
1821 {\sl x} symbol which resolves to \tts{test2.so}.  So in this
1822 case \tts{prelink} could skip those 3 conflicts.  Unfortunately
1823 it is not that easy:
1824
1825 \noindent{{\small\begin{verbatim}
1826 $ cat > test3.c <<EOF
1827 int i, j, k;
1828 static struct A { int *a; int *b; int *c; } local = { &i, &j, &k };
1829 extern struct A x;
1830 struct A *y = &x;
1831 struct A *y2 = &local;
1832 extern struct A x __attribute__((alias ("local")));
1833 EOF
1834 $ cat > test4.c <<EOF
1835 #include <stdio.h>
1836 extern struct A { int *a; int *b; int *c; } *y, *y2, *z;
1837 int main (void)
1838 {
1839   printf ("%p: %p %p %p\n", y, y->a, y->b, y->c);
1840   printf ("%p: %p %p %p\n", y2, y2->a, y2->b, y2->c);
1841   printf ("%p: %p %p %p\n", z, z->a, z->b, z->c);
1842 }
1843 EOF
1844 $ gcc -nostdlib -shared -fpic -s -o test3.so test3.c
1845 $ gcc -nostdlib -shared -fpic -o test4.so test2.c ./test3.so
1846 $ gcc -o test4 test4.c ./test4.so ./test3.so
1847 $ ./test4
1848 0x65a314: 0x65a3b0 0x65a3a8 0x65a3ac
1849 0xbd1328: 0x65a3b0 0x65a3a8 0x65a3ac
1850 0x65a314: 0x65a3b0 0x65a3a8 0x65a3ac
1851 \end{verbatim}}
1852 \prelinklistingcaption{Modified C example where conflict fixups cannot be removed}}
1853
1854 In this example, there are again 3 conflict fixups pointing into the
1855 12 byte long {\sl x} object in \tts{test3.so} shared library.
1856 The fact that variable local is located at the same 12 bytes
1857 is totally invisible to prelink, as local is a \tts{STB\_LOCAL}
1858 symbol which doesn't show up in \tts{.dynsym} section.  But if those
1859 3 conflict fixups are removed, then suddenly program's observable
1860 behavior changes (the last 3 addresses on second line would be
1861 different than those on first or third line).
1862
1863 Fortunately, there are at least some objects where \tts{prelink}
1864 can be reasonably sure they will never be referenced through some
1865 local alias.  Those are various compiler generated objects with
1866 well defined meaning which is \tts{prelink} able to identify
1867 in shared libraries.  The most important ones are C++ virtual tables
1868 and {\sl RTTI} data.  They are emitted as COMDAT data by the compiler,
1869 in GCC into \tts{.gnu.linkonce.d.*} sections.  Data or code in these
1870 sections can be accessed only through global symbols, otherwise linker
1871 might create unexpected results when two or more of these sections
1872 are merged together (all but one deleted).  When \tts{prelink} is checking
1873 for such data, it first checks whether the shared library in question
1874 is linked against \tts{libstdc++.so}.  If not, it is not a C++ library
1875 (or incorrectly built one) and thus it makes no sense to search any further.
1876 It looks only in \tts{.data} section, for \tts{STB\_WEAK} \tts{STT\_OBJECT}
1877 symbols whose names start with certain prefixes
1878 \footnote{\tts{\_\_vt\_} for GCC 2.95.x and 2.96-RH virtual tables,
1879 \tts{\_ZTV} for GCC 3.x virtual tables and \tts{\_ZTI} for GCC 3.x {\sl RTTI} data.}
1880 and where no other symbols (in dynamic symbol table) point into the objects.
1881 If these objects are unused because there is a conflict on their symbol,
1882 all conflict fixups pointing into the virtual table or {\sl RTTI} structure
1883 can be discarded.
1884
1885 Another possible optimization is again related to C++ virtual tables.
1886 Function addresses in them are not intended for pointer comparisons.
1887 C++ code only loads them from the virtual tables and calls through
1888 the pointer.  Pointers to member functions are handled differently.
1889 As pointer equivalence is the only reason why all function pointers
1890 resolve to \tts{PLT} slots in the executable even when the executable doesn't
1891 include implementation of the function (i.e. has \tts{SHN\_UNDEF} symbol
1892 with non-zero \tts{st\_value} pointing at the \tts{PLT} slot in the
1893 executable), \tts{prelink} can resolve method addresses in virtual tables
1894 to the actual method implementation.  In many cases this is in the same
1895 library as the virtual table (or in one of libraries in its natural
1896 symbol lookup scope), so a conflict fixup is unnecessary.
1897 This optimization speeds up programs also after control is transfered
1898 to the application and not just the time to start up the application,
1899 although just a few cycles per method call.
1900
1901 The conflict fixup reduction is quite big on some programs.
1902 Below is statistics for \tts{kmail} program on completely unprelinked box:
1903
1904 \noindent{{\small\begin{verbatim}
1905 $ LD_DEBUG=statistics /usr/bin/kmail 2>&1 | sed '2,8!d;s/^ *//'
1906 10621:       total startup time in dynamic loader: 240724867 clock cycles
1907 10621:                 time needed for relocation: 234049636 clock cycles (97.2%)
1908 10621:                      number of relocations: 34854
1909 10621:           number of relocations from cache: 74364
1910 10621:             number of relative relocations: 35351
1911 10621:                time needed to load objects: 6241678 clock cycles (2.5%)
1912 $ ls -l /usr/bin/kmail
1913 -rwxr-xr-x    1 root     root      2149084 Oct  2 12:05 /usr/bin/kmail
1914 $ ( Xvfb :3 & ) >/dev/null 2>&1 </dev/null; sleep 20
1915 $ ( DISPLAY=:3 kmail& ) >/dev/null 2>&1 </dev/null; sleep 10; killall kmail
1916 $ ( DISPLAY=:3 kmail& ) >/dev/null 2>&1 </dev/null; sleep 10
1917 $ cat /proc/`/sbin/pidof kmail`/statm
1918 4164 4164 3509 224 33 3907 655
1919 $ killall Xvfb kdeinit kmail
1920 \end{verbatim}}
1921 \prelinklistingcaption{Statistics for unprelinked \tts{kmail}}}
1922
1923 \tts{statm} special file for a process contains its memory statistics.
1924 The numbers in it mean in order total number of used pages (on IA-32
1925 Linux a page is 4KB), number of resident pages (i.e. not swapped out),
1926 number of shared pages, number of text pages, number of library pages,
1927 number of stack and other pages and number of dirty pages used by the
1928 process.  Distinction between text and library pages is very rough,
1929 so those numbers aren't that much useful.  Of interest are mainly
1930 first number, third number and last number.
1931
1932 Statistics for \tts{kmail} on completely prelinked box:
1933
1934 \noindent{{\small\begin{verbatim}
1935 $ LD_DEBUG=statistics /usr/bin/kmail 2>&1 | sed '2,8!d;s/^ *//'
1936 14864:       total startup time in dynamic loader: 8409504 clock cycles
1937 14864:                 time needed for relocation: 3024720 clock cycles (35.9%)
1938 14864:                      number of relocations: 0
1939 14864:           number of relocations from cache: 8961
1940 14864:             number of relative relocations: 0
1941 14864:                time needed to load objects: 4897336 clock cycles (58.2%)
1942 $ ls -l /usr/bin/kmail
1943 -rwxr-xr-x    1 root     root      2269500 Oct  2 12:05 /usr/bin/kmail
1944 $ ( Xvfb :3 & ) >/dev/null 2>&1 </dev/null; sleep 20
1945 $ ( DISPLAY=:3 kmail& ) >/dev/null 2>&1 </dev/null; sleep 10; killall kmail
1946 $ ( DISPLAY=:3 kmail& ) >/dev/null 2>&1 </dev/null; sleep 10
1947 $ cat /proc/`/sbin/pidof kmail`/statm
1948 3803 3803 3186 249 33 3521 617
1949 $ killall Xvfb kdeinit kmail
1950 \end{verbatim}}
1951 \prelinklistingcaption{Statistics for prelinked \tts{kmail}}}
1952
1953 Statistics for \tts{kmail} on completely prelinked box with C++ conflict fixup
1954 optimizations turned off:
1955
1956 \noindent{{\small\begin{verbatim}
1957 $ LD_DEBUG=statistics /usr/bin/kmail 2>&1 | sed '2,8!d;s/^ *//'
1958 20645:       total startup time in dynamic loader: 9704168 clock cycles
1959 20645:                 time needed for relocation: 4734715 clock cycles (48.7%)
1960 20645:                      number of relocations: 0
1961 20645:           number of relocations from cache: 59871
1962 20645:             number of relative relocations: 0
1963 20645:                time needed to load objects: 4487971 clock cycles (46.2%)
1964 ls -l /usr/bin/kmail
1965 -rwxr-xr-x    1 root     root      2877360 Oct  2 12:05 /usr/bin/kmail
1966 $ ( Xvfb :3 & ) >/dev/null 2>&1 </dev/null; sleep 20
1967 $ ( DISPLAY=:3 kmail& ) >/dev/null 2>&1 </dev/null; sleep 10; killall kmail
1968 $ ( DISPLAY=:3 kmail& ) >/dev/null 2>&1 </dev/null; sleep 10
1969 $ cat /proc/`/sbin/pidof kmail`/statm
1970 3957 3957 3329 398 33 3526 628
1971 $ killall Xvfb kdeinit kmail
1972 \end{verbatim}}
1973 \prelinklistingcaption{Statistics for prelinked \tts{kmail} without conflict fixup reduction}}
1974
1975 On this application, C++ conflict fixup optimizations saved 50910 unneeded
1976 conflict fixups, speeded up startup by 13.3\% and decreased number of dirty
1977 pages by 11, which means the application needs 44KB less memory per-process.
1978
1979 \section{Thread Local Storage support}
1980
1981 Thread Local Storage ([12], [13], [14]) support has been recently added to
1982 GCC, GNU binutils and GNU C Library.  \tts{TLS} support is a set of new
1983 relocations which together with dynamic linker and POSIX thread library
1984 additions provide faster and easier to use alternative to traditional
1985 POSIX thread local data API (\tts{pthread\_getspecific},
1986 \tts{pthread\_setspecific}, \tts{pthread\_key\_*}).
1987
1988 \tts{TLS} necessitated several changes to \tts{prelink}.  Thread Local
1989 symbols (with type \tts{STT\_TLS}) must not be relocated, as they are
1990 relative to the start of \tts{PT\_TLS} segment and thus not virtual
1991 addresses.  The dynamic linker had to be enhanced so that it tells
1992 \tts{prelink} at \tts{LD\_TRACE\_PRELINKING} time what \tts{TLS} module
1993 IDs have been assigned and what addresses relative to start of \tts{TLS}
1994 block have been given to \tts{PT\_TLS} segment of each library or executable.
1995 There are 3 classes of new \tts{TLS} dynamic relocations \tts{prelink}
1996 is interested in (with different names on different architectures).
1997
1998 In first class are module ID relocations, which are used for \tts{TLS}
1999 Global Dynamic and Local Dynamic models (for Global Dynamic model
2000 they are supposed to resolve to module ID of the executable or shared library
2001 of particular \tts{STT\_TLS} symbol, for Local Dynamic model this
2002 resolves to module ID of the containing shared library).  These
2003 relocations are hard to prelink in any useful way without moving
2004 \tts{TLS} module ID assignment from the dynamic linker to \tts{prelink}.
2005 Although \tts{prelink} can find out what shared library will contain
2006 particular \tts{STT\_TLS} symbol unless there will be conflicts
2007 for that symbol, it doesn't know how many shared libraries with
2008 \tts{PT\_TLS} segment will precede it or whether executable will or
2009 will not have \tts{PT\_TLS} segment.  Until \tts{TLS} is widely
2010 deployed by many libraries, \tts{prelink} could guess that
2011 only \tts{libc.so} will have \tts{PT\_TLS} and store 1 (first module ID
2012 the dynamic linker assigns), but given that \tts{libc.so} uses just
2013 one such relocation it is not probably worth doing this when soon other
2014 shared libraries besides \tts{libc.so} and \tts{libGL.so} start using
2015 it heavily.  Because of this \tts{prelink} doesn't do anything special
2016 when prelinking shared libraries with these relocations and for each
2017 relocations in this class creates one conflict fixup.
2018
2019 In second class are relocations which resolve to \tts{st\_value}
2020 of some \tts{STT\_TLS} symbol.  These relocations are used in
2021 Global Dynamic \tts{TLS} model (in Local Dynamic they are resolved
2022 at link time already) and from \tts{prelink} point of view they are
2023 much more similar to normal relocations than the other two classes.
2024 When the \tts{STT\_TLS} symbol is looked up successfully in shared library's
2025 natural search scope, \tts{prelink} just stores its \tts{st\_value}
2026 into the relocation.  The chances there will be a conflict are even
2027 smaller than with normal symbol lookups, since overloading \tts{TLS}
2028 symbols means wasted memory in each single thread and thus library
2029 writers will try to avoid it if possible.
2030
2031 The third class includes relocations which resolve to offsets within
2032 program's initial \tts{TLS} block
2033 \footnote{Negative on architectures which have
2034 \tts{TLS} block immediately below thread pointer (e.g. IA-32, AMD64,
2035 SPARC, S/390) and positive on architectures which have \tts{TLS} block
2036 at thread pointer or a few bytes above it (e.g. PowerPC, Alpha, IA-64,
2037 SuperH).}
2038 Relocation in this class are used in Initial Exec \tts{TLS} model
2039 (or in Local Exec model if this model is supported in shared libraries).
2040 These offsets are even harder to predict than module IDs and unlike
2041 module IDs it wouldn't be very helpful if they were assigned by
2042 \tts{prelink} instead of dynamic linker (which would just read them
2043 from some dynamic tag).  That's because \tts{TLS} block needs to be
2044 packed tightly and any assignments in \tts{prelink} couldn't take
2045 into account other shared libraries linked into the same executable
2046 and the executable itself.  Similarly to module ID relocations,
2047 \tts{prelink} doesn't do anything about them when prelinking shared
2048 libraries and for each such relocation creates a conflict fixup.
2049
2050 \section{Prelinking of executables and shared libraries}
2051
2052 Rewriting of executables is harder than for shared libraries, both because
2053 there are more changes necessary and because shared libraries are
2054 relocatable and thus have dynamic relocations for all absolute addresses.
2055
2056 After collecting all information from the dynamic linker and assigning
2057 virtual address space slots to all shared libraries, prelinking of shared
2058 libraries involves following steps:
2059 \begin{itemize}
2060 \item Relocation of the shared library to the assigned base address.
2061 \item \tts{REL} to \tts{RELA} conversion if needed (the only step which
2062 changes sizes of allocated sections in the middle).
2063 \item On architectures which have \tts{SHT\_NOBITS} \tts{.plt} sections,
2064 before relocations are applied the section needs to be converted to
2065 \tts{SHT\_PROGBITS}.  As the section needs to be at the end (or after it)
2066 of file backed part of some \tts{PT\_LOAD} segment, this just means that
2067 the file backed up part needs to be enlarged, the file filled with zeros
2068 and all following section file offsets or program header entry file
2069 offsets adjusted.  All \tts{SHT\_NOBITS} sections in the same \tts{PT\_LOAD}
2070 segment with virtual addresses lower than the \tts{.plt} start address
2071 need to be converted from \tts{SHT\_NOBITS} to \tts{SHT\_PROGBITS} too.
2072 Without making the section \tts{SHT\_PROGBITS}, \tts{prelink} cannot
2073 apply relocations against it as such sections contain only zeros.
2074 Architectures with \tts{SHT\_NOBITS} \tts{.plt} section supported by
2075 \tts{prelink} are PowerPC and PowerPC64.
2076 \item Applying relocations.  For each dynamic relocation in the shared
2077 library, address of relocation's symbol looked up in natural symbol lookup
2078 search scope of the shared library (or 0 if the symbol is not found in
2079 that search scope) is stored in an architecture and relocation type
2080 dependent way to memory pointed by \tts{r\_offset} field of the relocation.
2081 This step uses symbol lookup information provided by dynamic linker.
2082 \item Addition or modification of \tts{DT\_CHECKSUM} and
2083 \tts{DT\_GNU\_PRELINKED} dynamic tags.
2084 \footnote{\tts{Prelink} is not able to grow \tts{.dynamic} section, so it
2085 needs some spare dynamic tags (DT\_NULL) at the end of \tts{.dynamic}
2086 section.  GNU linker versions released after August 2001 leave space by
2087 default.}  The former is set to checksum of allocated sections in the
2088 shared library, the latter to time of prelinking.
2089 \item On architectures which don't use writable \tts{.plt}, but instead use
2090 \tts{.got.plt} (this section is merged during linking into \tts{.got})
2091 section, \tts{prelink} typically stores address into the first PLT slot
2092 in \tts{.plt} section to the reserved second word of \tts{.got} section.
2093 On these architectures, the dynamic linker has to initialize \tts{.plt}
2094 section if lazy binding.  On non-prelinked executables or shared libraries
2095 this typically means adding load offset to the values in \tts{.got.plt}
2096 section,  for prelinked shared libraries or executables if prelinking
2097 information cannot be used it needs to compute the right values in
2098 \tts{.got.plt} section without looking at this section's content
2099 (since it contains prelinking information).  The second word in \tts{.got}
2100 section is used for this computation.
2101 \item Addition of \tts{.gnu\_prelink\_undo} unallocated section if not
2102 present yet.  This section is used by \tts{prelink} internally during
2103 undo operation.
2104 \item Addition of \tts{.gnu\_liblist} and \tts{.gnu\_libstr} unallocated
2105 sections or, if they are already present, their update including possible
2106 growing or shrinking.  These sections are used only by \tts{prelink} to
2107 compare the dependent libraries (and their order) at the time when the
2108 shared library was prelinked against current dependencies.  If a shared
2109 library has no dependencies (e.g. dynamic linker), these sections are not
2110 present.
2111 \end{itemize}
2112
2113 Adding or resizing unallocated section needs just file offsets of following
2114 unallocated sections recomputed (ensuring proper alignment), growing section
2115 header table and \tts{.shstrtab} and adding new section names to that section.
2116
2117 Prelinking of executables involves following steps:
2118 \begin{itemize}
2119 \item \tts{REL} to \tts{RELA} conversion if needed.
2120 \item \tts{SHT\_NOBITS} to \tts{SHT\_PROGBITS} conversion of \tts{.plt} section
2121 if needed.
2122 \item Applying relocations.
2123 \item Addition or resizing of allocated \tts{.gnu.conflict} section containing
2124 list of conflict fixups.
2125 \item Addition or resizing of allocated \tts{.gnu.liblist} section which is used
2126 by the dynamic linker at runtime to see if none of the dependencies changed
2127 or were reordered.  If they were, it continues normal relocation processing,
2128 otherwise they can be skipped and only conflict fixups applied.
2129 \item Growing of allocated \tts{.dynstr} section, where strings referenced from
2130 \tts{.gnu.liblist} section need to be added.
2131 \item If there are any COPY relocations (which \tts{prelink} wants to handle
2132 rather than deferring them as conflict fixups to runtime), they need to be applied.
2133 \item Modifying second word in \tts{.got} section for \tts{.got.plt} using
2134 architectures.
2135 \item Addition or adjusting of dynamic tags which allow the dynamic linker
2136 to find the \tts{.gnu.liblist} and \tts{.gnu.conflict} sections and their
2137 sizes.  \tts{DT\_GNU\_CONFLICT} and \tts{DT\_GNU\_CONFLICTSZ} should be present
2138 if there are any conflict fixups.  It should contain the virtual address of
2139 the \tts{.gnu.conflict} section start resp. its size in bytes. 
2140 \tts{DT\_GNU\_LIBLIST} and \tts{DT\_GNU\_LIBLISTSZ} need to be present in
2141 all prelinked executables and must be equal the to virtual address of
2142 the \tts{.gnu.liblist} section and its size in bytes.
2143 \item Addition of \tts{.gnu\_prelink\_undo} unallocated section if not present.
2144 \end{itemize}
2145
2146 Executables can have absolute relocations already applied (and without a
2147 dynamic relocation) to virtually any allocated \tts{SHT\_PROGBITS} section
2148 \footnote{One exception is \tts{.interp} special section.  It shouldn't have
2149 relocations applied to it, nor any other section should reference it.},
2150 against almost all allocated \tts{SHT\_PROGBITS} and \tts{SHT\_NOBITS}
2151 sections.  This means that when growing, adding or shrinking allocated
2152 sections in executables, all \tts{SHT\_PROGBITS} and \tts{SHT\_NOBITS} section
2153 must keep their original virtual addresses and sizes
2154 \footnote{With a notable exception of splitting one section into two
2155 covering the same virtual address range.}. \tts{Prelink} tries various
2156 places where to put allocated sections which were added or grew:
2157 \begin{itemize}
2158 \item In the unlikely case if there is already some gap between
2159 sections in read-only \tts{PT\_LOAD} segment where the section fits.
2160 \item If the \tts{SHT\_NOBITS} sections are small enough to fit
2161 into a page together with the preceding \tts{SHT\_PROGBITS} section and there
2162 is still some space in the page after the \tts{SHT\_NOBITS} sections.
2163 In this case, \tts{prelink} converts the \tts{SHT\_NOBITS} sections into
2164 \tts{SHT\_PROGBITS} sections, fills them with zeros and adds the new section
2165 after it.  This doesn't increase number of \tts{PT\_LOAD} segments, but
2166 unfortunately those added sections are writable.  This doesn't matter
2167 much for e.g. \tts{.gnu.conflict} section which is only used before control
2168 is transfered to the program, but could matter for \tts{.dynstr} which is
2169 used even during \tts{dlopen}.
2170 \item On IA-32, executables have for historical reasons base address 0x8048000.
2171 The reason for this was that when stack was put immediately below executables,
2172 stack and the executable could coexist in the same second level page table.
2173 Linux puts the stack typically at the end of virtual address space and so
2174 keeping this exact base address is not really necessary.  \tts{Prelink} can
2175 decrease the base address and thus increase size of read-only \tts{PT\_LOAD}
2176 segment while \tts{SHT\_PROGBITS} and \tts{SHT\_NOBITS} section can stay
2177 at their previous addresses.  Just their file offsets need to be increased.
2178 All these segment header adjustments need to be done in multiplies of
2179 \tts{ELF} page sizes, so even if \tts{prelink} chose to do similar things
2180 on architectures other than IA-32 which typically start executables on some address
2181 which is a power of 2, it would be only reasonable if \tts{ELF} page size
2182 on that architecture (which can be much bigger than page size used by the
2183 operating system) is very small.
2184 \item Last possibility is to create a new \tts{PT\_LOAD} segment.
2185 \footnote{Linux kernels before 2.4.10 loaded executables which had middle \tts{PT\_LOAD}
2186 segment with \tts{p\_memsz} bigger than \tts{p\_filesz} incorrectly, so
2187 \tts{prelink} should be only used on systems with 2.4.10 or later kernels.}
2188 Section immediately above program header table (typically \tts{.interp})
2189 has to be moved somewhere else, but if possible close to the beginning
2190 of the executable.  The new \tts{PT\_LOAD} segment is then added after the
2191 last \tts{PT\_LOAD} segment.  The segment has to be writable even when
2192 all the sections in it are read-only, unless it ends exactly on a page
2193 boundary, because \tts{brk} area starts immediately after the end of last
2194 \tts{PT\_LOAD} segment and the executable expects it to be writable.
2195 \end{itemize}
2196
2197 So that verification works properly, if there is \tts{.gnu.prelink\_undo}
2198 section in the executable, \tts{prelink} first reshuffles the sections and
2199 segments for the purpose of finding places for the sections to the original
2200 sequence as recorded in the \tts{.gnu.prelink\_undo} section.
2201 Examples of the above mentioned cases:
2202
2203 \noindent{{\small\begin{verbatim}
2204 $ SEDCMD='s/^.* \.plt.*$/.../;/\[.*\.text/,/\[.*\.got/d'
2205 $ SEDCMD2='/Section to Segment/,$d;/^Key to/,/^Program/d;/^[A-Z]/d;/^ *$/d'
2206 $ cat > test1.c <<EOF
2207 int main (void) { return 0; }
2208 EOF
2209 $ gcc -Wl,--verbose 2>&1 \
2210   | sed '/^===/,/^===/!d;/^===/d;s/\.rel\.dyn/. += 512; &/' > test1.lds
2211 $ gcc -s -O2 -o test1 test1.c -Wl,-T,test1.lds
2212 $ readelf -Sl ./test1 | sed -e "$SEDCMD" -e "$SEDCMD2"
2213   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2214   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2215   [ 1] .interp           PROGBITS        08048114 000114 000013 00   A  0   0  1
2216   [ 2] .note.ABI-tag     NOTE            08048128 000128 000020 00   A  0   0  4
2217   [ 3] .hash             HASH            08048148 000148 000024 04   A  4   0  4
2218   [ 4] .dynsym           DYNSYM          0804816c 00016c 000040 10   A  5   1  4
2219   [ 5] .dynstr           STRTAB          080481ac 0001ac 000045 00   A  0   0  1
2220   [ 6] .gnu.version      VERSYM          080481f2 0001f2 000008 02   A  4   0  2
2221   [ 7] .gnu.version_r    VERNEED         080481fc 0001fc 000020 00   A  5   1  4
2222   [ 8] .rel.dyn          REL             0804841c 00041c 000008 08   A  4   0  4
2223   [ 9] .rel.plt          REL             08048424 000424 000008 08   A  4   b  4
2224   [10] .init             PROGBITS        0804842c 00042c 000017 00  AX  0   0  4
2225 ...
2226   [22] .bss              NOBITS          080496f8 0006f8 000004 00  WA  0   0  4
2227   [23] .comment          PROGBITS        00000000 0006f8 000132 00      0   0  1
2228   [24] .shstrtab         STRTAB          00000000 00082a 0000be 00      0   0  1
2229   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2230   PHDR           0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4
2231   INTERP         0x000114 0x08048114 0x08048114 0x00013 0x00013 R   0x1
2232       [Requesting program interpreter: /lib/ld-linux.so.2]
2233   LOAD           0x000000 0x08048000 0x08048000 0x005fc 0x005fc R E 0x1000
2234   LOAD           0x0005fc 0x080495fc 0x080495fc 0x000fc 0x00100 RW  0x1000
2235   DYNAMIC        0x000608 0x08049608 0x08049608 0x000c8 0x000c8 RW  0x4
2236   NOTE           0x000128 0x08048128 0x08048128 0x00020 0x00020 R   0x4
2237   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2238 $ prelink -N ./test1
2239 $ readelf -Sl ./test1 | sed -e "$SEDCMD" -e "$SEDCMD2"
2240   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2241   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2242   [ 1] .interp           PROGBITS        08048114 000114 000013 00   A  0   0  1
2243   [ 2] .note.ABI-tag     NOTE            08048128 000128 000020 00   A  0   0  4
2244   [ 3] .hash             HASH            08048148 000148 000024 04   A  4   0  4
2245   [ 4] .dynsym           DYNSYM          0804816c 00016c 000040 10   A  8   1  4
2246   [ 5] .gnu.liblist      GNU_LIBLIST     080481ac 0001ac 000028 14   A  8   0  4
2247   [ 6] .gnu.version      VERSYM          080481f2 0001f2 000008 02   A  4   0  2
2248   [ 7] .gnu.version_r    VERNEED         080481fc 0001fc 000020 00   A  8   1  4
2249   [ 8] .dynstr           STRTAB          0804821c 00021c 000058 00   A  0   0  1
2250   [ 9] .gnu.conflict     RELA            08048274 000274 0000c0 0c   A  4   0  4
2251   [10] .rel.dyn          REL             0804841c 00041c 000008 08   A  4   0  4
2252   [11] .rel.plt          REL             08048424 000424 000008 08   A  4   d  4
2253   [12] .init             PROGBITS        0804842c 00042c 000017 00  AX  0   0  4
2254 ...
2255   [24] .bss              NOBITS          080496f8 0006f8 000004 00  WA  0   0  4
2256   [25] .comment          PROGBITS        00000000 0006f8 000132 00      0   0  1
2257   [26] .gnu.prelink_undo PROGBITS        00000000 00082c 0004d4 01      0   0  4
2258   [27] .shstrtab         STRTAB          00000000 000d00 0000eb 00      0   0  1
2259   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2260   PHDR           0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4
2261   INTERP         0x000114 0x08048114 0x08048114 0x00013 0x00013 R   0x1
2262       [Requesting program interpreter: /lib/ld-linux.so.2]
2263   LOAD           0x000000 0x08048000 0x08048000 0x005fc 0x005fc R E 0x1000
2264   LOAD           0x0005fc 0x080495fc 0x080495fc 0x000fc 0x00100 RW  0x1000
2265   DYNAMIC        0x000608 0x08049608 0x08049608 0x000c8 0x000c8 RW  0x4
2266   NOTE           0x000128 0x08048128 0x08048128 0x00020 0x00020 R   0x4
2267   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2268 \end{verbatim}}
2269 \prelinklistingcaption{Reshuffling of an executable with a gap between sections}}
2270
2271 \begin{figure}[!ht]
2272 \centering
2273 \includegraphics[width=\textwidth]{gap}
2274 \caption{Reshuffling of an executable with a gap between sections}
2275 \end{figure}
2276
2277 In the above sample, there was enough space between sections (particularly
2278 between the end of the \tts{.gnu.version\_r} section and the start of \tts{.rel.dyn})
2279 that the new sections could be added there.
2280
2281 \noindent{{\small\begin{verbatim}
2282 $ SEDCMD='s/^.* \.plt.*$/.../;/\[.*\.text/,/\[.*\.got/d'
2283 $ SEDCMD2='/Section to Segment/,$d;/^Key to/,/^Program/d;/^[A-Z]/d;/^ *$/d'
2284 $ cat > test2.c <<EOF
2285 int main (void) { return 0; }
2286 EOF
2287 $ gcc -s -O2 -o test2 test2.c
2288 $ readelf -Sl ./test2 | sed -e "$SEDCMD" -e "$SEDCMD2"
2289   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2290   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2291   [ 1] .interp           PROGBITS        08048114 000114 000013 00   A  0   0  1
2292   [ 2] .note.ABI-tag     NOTE            08048128 000128 000020 00   A  0   0  4
2293   [ 3] .hash             HASH            08048148 000148 000024 04   A  4   0  4
2294   [ 4] .dynsym           DYNSYM          0804816c 00016c 000040 10   A  5   1  4
2295   [ 5] .dynstr           STRTAB          080481ac 0001ac 000045 00   A  0   0  1
2296   [ 6] .gnu.version      VERSYM          080481f2 0001f2 000008 02   A  4   0  2
2297   [ 7] .gnu.version_r    VERNEED         080481fc 0001fc 000020 00   A  5   1  4
2298   [ 8] .rel.dyn          REL             0804821c 00021c 000008 08   A  4   0  4
2299   [ 9] .rel.plt          REL             08048224 000224 000008 08   A  4   b  4
2300   [10] .init             PROGBITS        0804822c 00022c 000017 00  AX  0   0  4
2301 ...
2302   [22] .bss              NOBITS          080494f8 0004f8 000004 00  WA  0   0  4
2303   [23] .comment          PROGBITS        00000000 0004f8 000132 00      0   0  1
2304   [24] .shstrtab         STRTAB          00000000 00062a 0000be 00      0   0  1
2305   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2306   PHDR           0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4
2307   INTERP         0x000114 0x08048114 0x08048114 0x00013 0x00013 R   0x1
2308       [Requesting program interpreter: /lib/ld-linux.so.2]
2309   LOAD           0x000000 0x08048000 0x08048000 0x003fc 0x003fc R E 0x1000
2310   LOAD           0x0003fc 0x080493fc 0x080493fc 0x000fc 0x00100 RW  0x1000
2311   DYNAMIC        0x000408 0x08049408 0x08049408 0x000c8 0x000c8 RW  0x4
2312   NOTE           0x000128 0x08048128 0x08048128 0x00020 0x00020 R   0x4
2313   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2314 $ prelink -N ./test2
2315 $ readelf -Sl ./test2 | sed -e "$SEDCMD" -e "$SEDCMD2"
2316   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2317   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2318   [ 1] .interp           PROGBITS        08048114 000114 000013 00   A  0   0  1
2319   [ 2] .note.ABI-tag     NOTE            08048128 000128 000020 00   A  0   0  4
2320   [ 3] .hash             HASH            08048148 000148 000024 04   A  4   0  4
2321   [ 4] .dynsym           DYNSYM          0804816c 00016c 000040 10   A 23   1  4
2322   [ 5] .gnu.liblist      GNU_LIBLIST     080481ac 0001ac 000028 14   A 23   0  4
2323   [ 6] .gnu.version      VERSYM          080481f2 0001f2 000008 02   A  4   0  2
2324   [ 7] .gnu.version_r    VERNEED         080481fc 0001fc 000020 00   A 23   1  4
2325   [ 8] .rel.dyn          REL             0804821c 00021c 000008 08   A  4   0  4
2326   [ 9] .rel.plt          REL             08048224 000224 000008 08   A  4   b  4
2327   [10] .init             PROGBITS        0804822c 00022c 000017 00  AX  0   0  4
2328 ...
2329   [22] .bss              PROGBITS        080494f8 0004f8 000004 00  WA  0   0  4
2330   [23] .dynstr           STRTAB          080494fc 0004fc 000058 00   A  0   0  1
2331   [24] .gnu.conflict     RELA            08049554 000554 0000c0 0c   A  4   0  4
2332   [25] .comment          PROGBITS        00000000 000614 000132 00      0   0  1
2333   [26] .gnu.prelink_undo PROGBITS        00000000 000748 0004d4 01      0   0  4
2334   [27] .shstrtab         STRTAB          00000000 000c1c 0000eb 00      0   0  1
2335   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2336   PHDR           0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4
2337   INTERP         0x000114 0x08048114 0x08048114 0x00013 0x00013 R   0x1
2338       [Requesting program interpreter: /lib/ld-linux.so.2]
2339   LOAD           0x000000 0x08048000 0x08048000 0x003fc 0x003fc R E 0x1000
2340   LOAD           0x0003fc 0x080493fc 0x080493fc 0x00218 0x00218 RW  0x1000
2341   DYNAMIC        0x000408 0x08049408 0x08049408 0x000c8 0x000c8 RW  0x4
2342   NOTE           0x000128 0x08048128 0x08048128 0x00020 0x00020 R   0x4
2343   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2344 \end{verbatim}}
2345 \prelinklistingcaption{Reshuffling of an executable with small \tts{.bss}}}
2346
2347 \begin{figure}[!ht]
2348 \centering
2349 \includegraphics[width=\textwidth]{bss}
2350 \caption{Reshuffling of an executable with small \tts{.bss}}
2351 \end{figure}
2352
2353 In this case \tts{.bss} section was small enough that \tts{prelink}
2354 converted it to \tts{SHT\_PROGBITS}.
2355
2356 \noindent{{\small\begin{verbatim}
2357 $ SEDCMD='s/^.* \.plt.*$/.../;/\[.*\.text/,/\[.*\.got/d'
2358 $ SEDCMD2='/Section to Segment/,$d;/^Key to/,/^Program/d;/^[A-Z]/d;/^ *$/d'
2359 $ cat > test3.c <<EOF
2360 int foo [4096];
2361 int main (void) { return 0; }
2362 EOF
2363 $ gcc -s -O2 -o test3 test3.c
2364 $ readelf -Sl ./test3 | sed -e "$SEDCMD" -e "$SEDCMD2"
2365   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2366   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2367   [ 1] .interp           PROGBITS        08048114 000114 000013 00   A  0   0  1
2368   [ 2] .note.ABI-tag     NOTE            08048128 000128 000020 00   A  0   0  4
2369   [ 3] .hash             HASH            08048148 000148 000024 04   A  4   0  4
2370   [ 4] .dynsym           DYNSYM          0804816c 00016c 000040 10   A  5   1  4
2371   [ 5] .dynstr           STRTAB          080481ac 0001ac 000045 00   A  0   0  1
2372   [ 6] .gnu.version      VERSYM          080481f2 0001f2 000008 02   A  4   0  2
2373   [ 7] .gnu.version_r    VERNEED         080481fc 0001fc 000020 00   A  5   1  4
2374   [ 8] .rel.dyn          REL             0804821c 00021c 000008 08   A  4   0  4
2375   [ 9] .rel.plt          REL             08048224 000224 000008 08   A  4   b  4
2376   [10] .init             PROGBITS        0804822c 00022c 000017 00  AX  0   0  4
2377 ...
2378   [22] .bss              NOBITS          08049500 000500 004020 00  WA  0   0 32
2379   [23] .comment          PROGBITS        00000000 000500 000132 00      0   0  1
2380   [24] .shstrtab         STRTAB          00000000 000632 0000be 00      0   0  1
2381   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2382   PHDR           0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4
2383   INTERP         0x000114 0x08048114 0x08048114 0x00013 0x00013 R   0x1
2384       [Requesting program interpreter: /lib/ld-linux.so.2]
2385   LOAD           0x000000 0x08048000 0x08048000 0x003fc 0x003fc R E 0x1000
2386   LOAD           0x0003fc 0x080493fc 0x080493fc 0x000fc 0x04124 RW  0x1000
2387   DYNAMIC        0x000408 0x08049408 0x08049408 0x000c8 0x000c8 RW  0x4
2388   NOTE           0x000128 0x08048128 0x08048128 0x00020 0x00020 R   0x4
2389   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2390 $ prelink -N ./test3
2391 $ readelf -Sl ./test3 | sed -e "$SEDCMD" -e "$SEDCMD2"
2392   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2393   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2394   [ 1] .interp           PROGBITS        08047114 000114 000013 00   A  0   0  1
2395   [ 2] .note.ABI-tag     NOTE            08047128 000128 000020 00   A  0   0  4
2396   [ 3] .dynstr           STRTAB          08047148 000148 000058 00   A  0   0  1
2397   [ 4] .gnu.liblist      GNU_LIBLIST     080471a0 0001a0 000028 14   A  3   0  4
2398   [ 5] .gnu.conflict     RELA            080471c8 0001c8 0000c0 0c   A  7   0  4
2399   [ 6] .hash             HASH            08048148 001148 000024 04   A  7   0  4
2400   [ 7] .dynsym           DYNSYM          0804816c 00116c 000040 10   A  3   1  4
2401   [ 8] .gnu.version      VERSYM          080481f2 0011f2 000008 02   A  7   0  2
2402   [ 9] .gnu.version_r    VERNEED         080481fc 0011fc 000020 00   A  3   1  4
2403   [10] .rel.dyn          REL             0804821c 00121c 000008 08   A  7   0  4
2404   [11] .rel.plt          REL             08048224 001224 000008 08   A  7   d  4
2405   [12] .init             PROGBITS        0804822c 00122c 000017 00  AX  0   0  4
2406 ...
2407   [24] .bss              NOBITS          08049500 0014f8 004020 00  WA  0   0 32
2408   [25] .comment          PROGBITS        00000000 0014f8 000132 00      0   0  1
2409   [26] .gnu.prelink_undo PROGBITS        00000000 00162c 0004d4 01      0   0  4
2410   [27] .shstrtab         STRTAB          00000000 001b00 0000eb 00      0   0  1
2411   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2412   PHDR           0x000034 0x08047034 0x08047034 0x000e0 0x000e0 R E 0x4
2413   INTERP         0x000114 0x08047114 0x08047114 0x00013 0x00013 R   0x1
2414       [Requesting program interpreter: /lib/ld-linux.so.2]
2415   LOAD           0x000000 0x08047000 0x08047000 0x013fc 0x013fc R E 0x1000
2416   LOAD           0x0013fc 0x080493fc 0x080493fc 0x000fc 0x04124 RW  0x1000
2417   DYNAMIC        0x001408 0x08049408 0x08049408 0x000c8 0x000c8 RW  0x4
2418   NOTE           0x000128 0x08047128 0x08047128 0x00020 0x00020 R   0x4
2419   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2420 \end{verbatim}}
2421 \prelinklistingcaption{Reshuffling of an executable with decreasing of base address}}
2422
2423 \begin{figure}[!ht]
2424 \centering
2425 \includegraphics[width=\textwidth]{basemove}
2426 \caption{Reshuffling of an executable with decreasing of the base address}
2427 \end{figure}
2428
2429 In \tts{test3} the base address of the executable was decreased by one page and
2430 the new sections added there.
2431
2432 \noindent{{\small\begin{verbatim}
2433 $ SEDCMD='s/^.* \.plt.*$/.../;/\[.*\.text/,/\[.*\.got/d'
2434 $ SEDCMD2='/Section to Segment/,$d;/^Key to/,/^Program/d;/^[A-Z]/d;/^ *$/d'
2435 $ cat > test4.c <<EOF
2436 int foo [4096];
2437 int main (void) { return 0; }
2438 EOF
2439 $ gcc -Wl,--verbose 2>&1 \
2440   | sed '/^===/,/^===/!d;/^===/d;s/0x08048000/0x08000000/' > test4.lds
2441 $ gcc -s -O2 -o test4 test4.c -Wl,-T,test4.lds
2442 $ readelf -Sl ./test4 | sed -e "$SEDCMD" -e "$SEDCMD2"
2443   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2444   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2445   [ 1] .interp           PROGBITS        08000114 000114 000013 00   A  0   0  1
2446   [ 2] .note.ABI-tag     NOTE            08000128 000128 000020 00   A  0   0  4
2447   [ 3] .hash             HASH            08000148 000148 000024 04   A  4   0  4
2448   [ 4] .dynsym           DYNSYM          0800016c 00016c 000040 10   A  5   1  4
2449   [ 5] .dynstr           STRTAB          080001ac 0001ac 000045 00   A  0   0  1
2450   [ 6] .gnu.version      VERSYM          080001f2 0001f2 000008 02   A  4   0  2
2451   [ 7] .gnu.version_r    VERNEED         080001fc 0001fc 000020 00   A  5   1  4
2452   [ 8] .rel.dyn          REL             0800021c 00021c 000008 08   A  4   0  4
2453   [ 9] .rel.plt          REL             08000224 000224 000008 08   A  4   b  4
2454   [10] .init             PROGBITS        0800022c 00022c 000017 00  AX  0   0  4
2455 ...
2456   [22] .bss              NOBITS          08001500 000500 004020 00  WA  0   0 32
2457   [23] .comment          PROGBITS        00000000 000500 000132 00      0   0  1
2458   [24] .shstrtab         STRTAB          00000000 000632 0000be 00      0   0  1
2459   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2460   PHDR           0x000034 0x08000034 0x08000034 0x000e0 0x000e0 R E 0x4
2461   INTERP         0x000114 0x08000114 0x08000114 0x00013 0x00013 R   0x1
2462       [Requesting program interpreter: /lib/ld-linux.so.2]
2463   LOAD           0x000000 0x08000000 0x08000000 0x003fc 0x003fc R E 0x1000
2464   LOAD           0x0003fc 0x080013fc 0x080013fc 0x000fc 0x04124 RW  0x1000
2465   DYNAMIC        0x000408 0x08001408 0x08001408 0x000c8 0x000c8 RW  0x4
2466   NOTE           0x000128 0x08000128 0x08000128 0x00020 0x00020 R   0x4
2467   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2468 $ prelink -N ./test4
2469 $ readelf -Sl ./test4 | sed -e "$SEDCMD" -e "$SEDCMD2"
2470   [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
2471   [ 0]                   NULL            00000000 000000 000000 00      0   0  0
2472   [ 1] .interp           PROGBITS        08000134 000134 000013 00   A  0   0  1
2473   [ 2] .note.ABI-tag     NOTE            08000148 000148 000020 00   A  0   0  4
2474   [ 3] .hash             HASH            08000168 000168 000024 04   A  4   0  4
2475   [ 4] .dynsym           DYNSYM          0800018c 00018c 000040 10   A 22   1  4
2476   [ 5] .gnu.version      VERSYM          080001f2 0001f2 000008 02   A  4   0  2
2477   [ 6] .gnu.version_r    VERNEED         080001fc 0001fc 000020 00   A 22   1  4
2478   [ 7] .rel.dyn          REL             0800021c 00021c 000008 08   A  4   0  4
2479   [ 8] .rel.plt          REL             08000224 000224 000008 08   A  4   a  4
2480   [ 9] .init             PROGBITS        0800022c 00022c 000017 00  AX  0   0  4
2481 ...
2482   [21] .bss              NOBITS          08001500 0004f8 004020 00  WA  0   0 32
2483   [22] .dynstr           STRTAB          080064f8 0004f8 000058 00   A  0   0  1
2484   [23] .gnu.liblist      GNU_LIBLIST     08006550 000550 000028 14   A 22   0  4
2485   [24] .gnu.conflict     RELA            08006578 000578 0000c0 0c   A  4   0  4
2486   [25] .comment          PROGBITS        00000000 000638 000132 00      0   0  1
2487   [26] .gnu.prelink_undo PROGBITS        00000000 00076c 0004d4 01      0   0  4
2488   [27] .shstrtab         STRTAB          00000000 000c40 0000eb 00      0   0  1
2489   Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
2490   PHDR           0x000034 0x08000034 0x08000034 0x000e0 0x000e0 R E 0x4
2491   INTERP         0x000134 0x08000134 0x08000134 0x00013 0x00013 R   0x1
2492       [Requesting program interpreter: /lib/ld-linux.so.2]
2493   LOAD           0x000000 0x08000000 0x08000000 0x003fc 0x003fc R E 0x1000
2494   LOAD           0x0003fc 0x080013fc 0x080013fc 0x000fc 0x04124 RW  0x1000
2495   LOAD           0x0004f8 0x080064f8 0x080064f8 0x00140 0x00140 RW  0x1000
2496   DYNAMIC        0x000408 0x08001408 0x08001408 0x000c8 0x000c8 RW  0x4
2497   NOTE           0x000148 0x08000148 0x08000148 0x00020 0x00020 R   0x4
2498   STACK          0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
2499 \end{verbatim}}
2500 \prelinklistingcaption{Reshuffling of an executable with addition of a new segment}}
2501
2502 \begin{figure}[!ht]
2503 \centering
2504 \includegraphics[width=\textwidth]{newseg}
2505 \caption{Reshuffling of an executable with addition of a new segment}
2506 \end{figure}
2507
2508 In the last example, base address was not decreased but instead a new
2509 \tts{PT\_LOAD} segment has been added.
2510
2511 \tts{R\_<arch>\_COPY} relocations are typically against first part of the
2512 \tts{SHT\_NOBITS} \tts{.bss} section.  So that \tts{prelink} can apply them,
2513 it needs to first change their section to \tts{SHT\_PROGBITS}, but as \tts{.bss}
2514 section typically occupies much larger part of memory, it is not desirable
2515 to convert \tts{.bss} section into \tts{SHT\_PROGBITS} as whole.  A section
2516 cannot be partly \tts{SHT\_PROGBITS} and partly \tts{SHT\_NOBITS}, so \tts{prelink}
2517 first splits the section into two parts, first \tts{.dynbss} which covers area
2518 from the start of \tts{.bss} section up to highest byte to which some COPY
2519 relocation is applied and then the old \tts{.bss}.  The first is converted
2520 to \tts{SHT\_PROGBITS} and its size is decreased, the latter stays \tts{SHT\_NOBITS}
2521 and its start address and file offset are adjusted as well as its size decreased.
2522 The dynamic linker handles relocations in the executable last, so \tts{prelink}
2523 cannot just copy memory from the shared library where the symbol of the COPY
2524 relocation has been looked up in.  There might be relocations applied by the
2525 dynamic linker in normal relocation processing to the objects, so \tts{prelink}
2526 has to first process the relocations against that memory area.  Relocations
2527 which don't need conflict fixups are already applied, so \tts{prelink} just
2528 needs to apply conflict fixups against the memory area, then copy it
2529 to the newly created \tts{.dynbss} section.
2530
2531 Here is an example which shows various things which COPY relocation handling
2532 in \tts{prelink} needs to deal with:
2533
2534 \noindent{{\small\begin{verbatim}
2535 $ cat > test1.c <<EOF
2536 struct A { char a; struct A *b; int *c; int *d; };
2537 int bar, baz;
2538 struct A foo = { 1, &foo, &bar, &baz };
2539 int *addr (void) { return &baz; }
2540 EOF
2541 $ cat > test.c <<EOF
2542 #include <stdio.h>
2543 struct A { char a; struct A *b; int *c; int *d; };
2544 int bar, *addr (void), big[8192];
2545 extern struct A foo;
2546 int main (void)
2547 {
2548   printf ("%p: %d %p %p %p %p %p\n", &foo, foo.a, foo.b, foo.c, foo.d,
2549           &bar, addr ());
2550 }
2551 EOF
2552 $ gcc -nostdlib -shared -fpic -s -o test1.so test1.c
2553 $ gcc -s -o test test.c ./test1.so
2554 $ ./test
2555 0x80496c0: 1 0x80496c0 0x80516e0 0x4833a4 0x80516e0 0x4833a4
2556 $ readelf -r test | sed '/\.rel\.dyn/,/\.rel\.plt/!d;/^0/!d'
2557 080496ac  00000c06 R_386_GLOB_DAT    00000000   __gmon_start__
2558 080496c0  00000605 R_386_COPY        080496c0   foo
2559 $ readelf -S test | grep bss
2560   [22] .bss              NOBITS          080496c0 0006c0 008024 00  WA  0   0 32
2561 $ prelink -N ./test ./test1.so
2562 $ readelf -s test | grep foo
2563      6: 080496c0    16 OBJECT  GLOBAL DEFAULT   25 foo
2564 $ readelf -s test1.so | grep foo
2565     15: 004a9314    16 OBJECT  GLOBAL DEFAULT    6 foo
2566 $ readelf -r test | sed '/.gnu.conflict/,/\.rel\.dyn/!d;/^0/!d'
2567 004a9318  00000001 R_386_32                                     080496c0
2568 004a931c  00000001 R_386_32                                     080516e0
2569 005f9874  00000001 R_386_32                                     fffffff0
2570 005f9878  00000001 R_386_32                                     00000001
2571 005f98bc  00000001 R_386_32                                     fffffff4
2572 005f9900  00000001 R_386_32                                     ffffffec
2573 005f9948  00000001 R_386_32                                     ffffffdc
2574 005f995c  00000001 R_386_32                                     ffffffe0
2575 005f9980  00000001 R_386_32                                     fffffff8
2576 005f9988  00000001 R_386_32                                     ffffffe4
2577 005f99a4  00000001 R_386_32                                     ffffffd8
2578 005f99c4  00000001 R_386_32                                     ffffffe8
2579 005f99d8  00000001 R_386_32                                     08048584
2580 004c2510  00000007 R_386_JUMP_SLOT                              00534460
2581 004c2514  00000007 R_386_JUMP_SLOT                              00534080
2582 004c2518  00000007 R_386_JUMP_SLOT                              00534750
2583 004c251c  00000007 R_386_JUMP_SLOT                              005342c0
2584 004c2520  00000007 R_386_JUMP_SLOT                              00534200
2585 $ objdump -s -j .dynbss test
2586
2587 test:     file format elf32-i386
2588
2589 Contents of section .dynbss:
2590  80496c0 01000000 c0960408 e0160508 a4934a00  ..............J.
2591 $ objdump -s -j .data test1.so
2592
2593 test1.so:     file format elf32-i386
2594
2595 Contents of section .data:
2596  4a9314 01000000 14934a00 a8934a00 a4934a00  ......J...J...J.
2597 $ readelf -S test | grep bss
2598   [24] .dynbss           PROGBITS        080496c0 0016c0 000010 00  WA  0   0 32
2599   [25] .bss              NOBITS          080496d0 0016d0 008014 00  WA  0   0 32
2600 $ sed 's/8192/1/' test.c > test2.c
2601 $ gcc -s -o test2 test2.c ./test1.so
2602 $ readelf -S test2 | grep bss
2603   [22] .bss              NOBITS          080496b0 0006b0 00001c 00  WA  0   0  8
2604 $ prelink -N ./test2 ./test1.so
2605 $ readelf -S test2 | grep bss
2606   [22] .dynbss           PROGBITS        080496b0 0006b0 000010 00  WA  0   0  8
2607   [23] .bss              PROGBITS        080496c0 0006c0 00000c 00  WA  0   0  8
2608 \end{verbatim}}
2609 \prelinklistingcaption{Relocation handling of \tts{.dynbss} objects}}
2610
2611 Because \tts{test.c} executable is not compiled as position independent code and
2612 takes address of {\sl foo} variable, a COPY relocation is needed to avoid
2613 dynamic relocation against executable's read-only \tts{PT\_LOAD} segment.
2614 The {\sl foo} object in \tts{test1.so} has one field with no relocations
2615 applied at all, one relocation against the variable itself, one relocation
2616 which needs a conflict fixup (as it is overridden by the variable in the
2617 executable) and one with relocation which doesn't need any fixups.
2618 The first and last field contain already the right values in prelinked
2619 \tts{test1.so}, while second and third one need to be changed for symbol
2620 addresses in the executable (as shown in the \tts{objdump} output).
2621 The conflict fixups against {\sl foo} in \tts{test1.so} need to stay
2622 (unless it is a C++ virtual table or {\sl RTTI} data, i.e. not in this testcase).
2623 In \tts{test}, \tts{prelink} changed \tts{.dynbss} to \tts{SHT\_PROGBITS}
2624 and kept \tts{SHT\_NOBITS} \tts{.bss}, while in slightly modified testcase
2625 (\tts{test2}) the size of \tts{.bss} was small enough that \tts{prelink}
2626 chose to make it \tts{SHT\_PROGBITS} too and grow the read-write
2627 \tts{PT\_LOAD} segment and put \tts{.dynstr} and \tts{.gnu.conflict}
2628 sections after it.
2629
2630 \section{Prelink undo operation}
2631
2632 Prelinking of shared libraries and executables is designed to be reversible,
2633 so that prelink operation followed by undo operation generates bitwise
2634 identical file to the original before prelinking.  For this operation
2635 \tts{prelink} stores the original \tts{ELF} header, all the program and
2636 all section headers into a \tts{.gnu.prelink\_undo} section before it starts prelinking
2637 an unprelinked executable or shared library.  When undoing the modifications,
2638 \tts{prelink} has to convert \tts{RELA} back to \tts{REL} first if \tts{REL}
2639 to \tts{RELA} conversion was done during prelinking and all allocated
2640 sections above it relocated down to adjust for the section shrink.
2641 Relocation types which were changed when trying to avoid \tts{REL} to
2642 \tts{RELA} conversion need to be changed back (e.g. on IA-32, it is
2643 assumed \tts{R\_386\_GLOB\_DAT} relocations should be only those
2644 against \tts{.got} section and \tts{R\_386\_32} relocations in the
2645 remaining places).  On \tts{RELA} architectures, the memory pointed
2646 by \tts{r\_offset} field of the relocations needs to be reinitialized
2647 to the values stored there by the linker originally.
2648 For \tts{prelink} it doesn't matter much what this value is (e.g.
2649 always 0, copy of \tts{r\_addend}, etc.), as long as it is computable
2650 from the information \tts{prelink} has during undo operation
2651 \footnote{Such as relocation type, \tts{r\_addend} value,
2652 type, binding, flags or other attributes of relocation's symbol,
2653 what section the relocation points into or the offset within
2654 section it points to.}.  The GNU linker had to be changed on several
2655 architectures, so that it stores there such a value, as in several places
2656 the value e.g. depended on original addend before final link (which is
2657 not available anywhere after final link time, since \tts{r\_addend}
2658 field could be adjusted during the final link).
2659 If second word of \tts{.got} section has been modified, it needs
2660 to be reverted back to the original value (on most architectures zero).
2661 In executables, sections which were moved during prelinking need to be
2662 put back and segments added while prelinking must be removed.
2663
2664 There are 3 different ways how an undo operation can be performed:
2665 \begin{itemize}
2666 \item Undoing individual executables or shared libraries specified on the
2667 command line in place (i.e. when the undo operation is successful,
2668 the prelinked executable or library is atomically replaced with the
2669 undone object).
2670 \item With \tts{-o} option, only a single executable or shared library
2671 given on the command line is undone and stored to the file specified
2672 as \tts{-o} option's argument.
2673 \item With \tts{-ua} options, \tts{prelink} builds a list of executables
2674 in paths written in its config file (plus directories and executables
2675 or libraries from command line) and all shared libraries these executables
2676 depend on.  All executables and libraries in the list are then unprelinked.
2677 This option is used to unprelink the whole system.  It is not perfect
2678 and needs to be worked on, since e.g. if some executable uses some shared
2679 library which no other executable links against, this executable (and shared
2680 library) is prelinked, then the executable is removed (e.g. uninstalled)
2681 but the shared library is kept, then the shared library is not
2682 unprelinked unless specifically mentioned on the command line.
2683 \end{itemize}
2684
2685 \section{Verification of prelinked files}
2686
2687 As \tts{prelink} needs to modify executables and shared libraries installed
2688 on a system, it complicates system integrity verification (e.g. \tts{rpm -V},
2689 TripWire).  These systems store checksums of installed files into some
2690 database and during verification compute them again and compare to the
2691 values stored in the database.  On a prelinked system most of the executables
2692 and shared libraries would be reported as modified.  \tts{Prelink} offers
2693 a special mode for these systems, in which it verifies that unprelinking
2694 the executable or shared library followed by immediate prelinking (with the
2695 same base address) creates bitwise identical output with the executable
2696 or shared library that's being verified.  Furthermore, depending on
2697 other \tts{prelink} options, it either writes the unprelinked image
2698 to its standard output or computes MD5 or SHA1 digest from this unprelinked
2699 image.  Mere undo operation to a file and checksumming it is not good
2700 enough, since an intruder could have modified e.g. conflict fixups or
2701 memory which relocations point at, changing a behavior of the program
2702 while file after unprelinking would be unmodified.
2703
2704 During verification, both \tts{prelink} executable and the dynamic linker
2705 are used, so a proper system integrity verification first checks whether
2706 \tts{prelink} executable (which is statically linked for this reason) hasn't
2707 been modified, then uses \tts{prelink --verify} to verify the dynamic linker
2708 (when verificating \tts{ld.so} the dynamic linker is not executed)
2709 followed by verification of other executables and libraries.
2710
2711 Verification requires all dependencies of checked object to be unmodified
2712 since last prelinking.  If some dependency has been changed or is missing,
2713 \tts{prelink} will report it and return with non-zero exit status.
2714 This is because prelinking depends on their content and so if they are
2715 modified, the executable or shared library might be different to one after
2716 unprelinking followed by prelinking again.  In the future, perhaps it
2717 would be possible to even verify executables or shared libraries without
2718 unmodified dependencies, under the assumption that in such case the prelink
2719 information will not be used.  It would just need to verify that nothing
2720 else but the information only used when dependencies are up to date
2721 has changed between the executable or library on the filesystem and file
2722 after unprelink followed by prelink cycle.  The prelink operation
2723 would need to be modified in this case, so that no information is
2724 collected from the dynamic linker, the list of dependencies is assumed
2725 to be the one stored in the executable and expect it to have identical
2726 number of conflict fixups.
2727
2728 \section{Measurements}
2729
2730 There are two areas where \tts{prelink} can speed things up noticeably.
2731 The primary is certainly startup time of big GUI applications where the
2732 dynamic linker spends from 100ms up to a few seconds before giving control
2733 to the application.  Another area is when lots of small programs are started
2734 up, but their execution time is rather short, so the startup time which
2735 \tts{prelink} optimizes is a noticeable fraction of the total time.
2736 This is typical for shell scripting.
2737
2738 First numbers are from \tts{lmbench} benchmark, version 3.0-a3.
2739 Most of the benchmarks in \tts{lmbench} suite measure kernel speed,
2740 so it doesn't matter much whether \tts{prelink} is used or not.
2741 Only in \tts{lat\_proc} benchmark \tts{prelink} shows up visibly.
2742 This benchmark measures 3 different things:
2743 \begin{itemize}
2744 \item {\sl fork proc}, which is \tts{fork()} followed by immediate
2745 \tts{exit(1)} in the child and \tts{wait(0)} in the parent.  The results
2746 are (as expected) about the same between unprelinked and prelinked systems.
2747 \item {\sl exec proc}, i.e. \tts{fork()} followed by immediate
2748 \tts{close(1)} and \tts{execve()} of a simple hello world program (this
2749 program is compiled and linked during the benchmark into a temporary
2750 directory and is never prelinked).  The numbers are 160$\mu$s to 200$\mu$s
2751 better on prelinked systems, because there is no relocation processing needed
2752 initially in the dynamic linker and because all relative relocations
2753 in \tts{libc.so.6} can be skipped.
2754 \item {\sl sh proc}, i.e. \tts{fork()} followed by immediate \tts{close(1)}
2755 and \tts{execlp("/bin/sh", "sh", "-c", "/tmp/hello", 0)}.  Although
2756 the hello world program is not prelinked in this case either, the shell is,
2757 so out of the 900$\mu$s to 1000$\mu$s speedup less than 200$\mu$s can be
2758 accounted on the speed up of the hello world program as in {\sl exec proc}
2759 benchmark and the rest to the speedup of shell startup.
2760 \end{itemize}
2761
2762 First 4 rows are from running the benchmark on a fully unprelinked system,
2763 the last 4 rows on the same system, but fully prelinked.
2764
2765 \noindent{{\small\begin{verbatim}
2766                  L M B E N C H  3 . 0   S U M M A R Y
2767                  ------------------------------------
2768                  (Alpha software, do not distribute)
2769
2770 Processor, Processes - times in microseconds - smaller is better
2771 -------------------------------------------------------------------------
2772 Host           OS  Mhz null null      open slct sig  sig  fork exec sh  
2773                        call  I/O stat clos TCP  inst hndl proc proc proc
2774 ---- ------------ ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
2775 pork Linux 2.4.22  651 0.53 0.97 6.20 8.10 41.2 1.44 4.30 276. 1497 5403
2776 pork Linux 2.4.22  651 0.53 0.95 6.14 7.91 37.8 1.43 4.34 274. 1486 5391
2777 pork Linux 2.4.22  651 0.56 0.94 6.18 8.09 43.4 1.41 4.30 251. 1507 5423
2778 pork Linux 2.4.22  651 0.53 0.94 6.12 8.09 41.0 1.43 4.40 256. 1497 5385
2779 pork Linux 2.4.22  651 0.56 0.94 5.79 7.58 39.1 1.41 4.30 271. 1319 4460
2780 pork Linux 2.4.22  651 0.56 0.92 5.76 7.40 38.9 1.41 4.30 253. 1304 4417
2781 pork Linux 2.4.22  651 0.56 0.95 6.20 7.83 37.7 1.41 4.37 248. 1323 4481
2782 pork Linux 2.4.22  651 0.56 1.01 6.04 7.77 37.9 1.43 4.32 256. 1324 4457
2783 \end{verbatim}}
2784 \prelinklistingcaption{\tts{lmbench} results without and with prelinking}}
2785
2786 Below is a sample timing of a 239K long configure shell script from GCC
2787 on both unprelinked and prelinked system.  Preparation step was following:
2788
2789 \noindent{{\small\begin{verbatim}
2790 cd; cvs -d :pserver:anoncvs@subversions.gnu.org:/cvsroot/gcc login
2791 # Empty password
2792 cvs -d :pserver:anoncvs@subversions.gnu.org:/cvsroot/gcc -z3 co -D20031103 gcc
2793 mkdir ~/gcc/obj
2794 cd ~/gcc/obj; ../configure i386-redhat-linux; make configure-gcc
2795 \end{verbatim}}
2796 \prelinklistingcaption{Preparation script for shell script tests}}
2797
2798 On an unprelinked system, the results were:
2799
2800 \noindent{{\small\begin{verbatim}
2801 cd ~/gcc/obj/gcc
2802 for i in 1 2; do ./config.status --recheck > /dev/null 2>&1; done
2803 for i in 1 2 3 4; do time ./config.status --recheck > /dev/null 2>&1; done
2804
2805 real    0m4.436s
2806 user    0m1.730s
2807 sys     0m1.260s
2808
2809 real    0m4.409s
2810 user    0m1.660s
2811 sys     0m1.340s
2812
2813 real    0m4.431s
2814 user    0m1.810s
2815 sys     0m1.300s
2816
2817 real    0m4.432s
2818 user    0m1.670s
2819 sys     0m1.210s
2820 \end{verbatim}}
2821 \prelinklistingcaption{Shell script test results on unprelinked system}}
2822
2823 and on a fully prelinked system:
2824
2825 \noindent{{\small\begin{verbatim}
2826 cd ~/gcc/obj/gcc
2827 for i in 1 2; do ./config.status --recheck > /dev/null 2>&1; done
2828 for i in 1 2 3 4; do time ./config.status --recheck > /dev/null 2>&1; done
2829
2830 real    0m4.126s
2831 user    0m1.590s
2832 sys     0m1.240s
2833
2834 real    0m4.151s
2835 user    0m1.620s
2836 sys     0m1.230s
2837
2838 real    0m4.161s
2839 user    0m1.600s
2840 sys     0m1.190s
2841
2842 real    0m4.122s
2843 user    0m1.570s
2844 sys     0m1.230s
2845 \end{verbatim}}
2846 \prelinklistingcaption{Shell script test results on prelinked system}}
2847
2848 Now timing of a few big GUI programs.  All timings were done without X
2849 server running and with \tts{DISPLAY} environment variable not set
2850 (so that when control is transfered to the application, it very soon
2851 finds out there is no X server it can talk to and bail out).  The
2852 measurements are done by the dynamic linker in ticks on a 651MHz
2853 dual Pentium III machine, i.e. ticks have to be divided by 651000000
2854 to get times in seconds.  Each application has been run 4 times
2855 and the results with smallest total time spent in the dynamic
2856 linker was chosen.  Epiphany WWW browser and Evolution mail client
2857 were chosen as examples of \tts{Gtk+} applications (typically they use
2858 really many shared libraries, but many of them are quite small,
2859 there aren't really many relocations nor conflict fixups and most
2860 of the libraries are written in C) and Konqueror WWW browser and
2861 KWord word processor were chosen as examples of \tts{KDE} applications
2862 (typically they use slightly fewer shared libraries, though
2863 still a lot, most of the shared libraries are written in C++,
2864 have many relocations and cause many conflict fixups, especially
2865 without C++ conflict fixup optimizations in \tts{prelink}).
2866 On non-prelinked system, the timings are done with lazy binding,
2867 i.e. without \tts{LD\_BIND\_NOW=1} set in the environment.
2868 This is because that's how people generally run programs, on the other
2869 side it is not exact apples to apples comparison, since on prelinked
2870 system there is no lazy binding with the exception of shared libraries
2871 loaded through \tts{dlopen}.  So when control is passed to the application,
2872 prelinked programs should be slightly faster for a while since non-prelinked
2873 programs will have to do symbol lookups and processing relocations
2874 (and on various architectures flushing instruction caches) whenever
2875 they call some function they haven't called before in particular shared
2876 library or in the executable.
2877
2878 \noindent{{\small\begin{verbatim}
2879 $ ldd `which epiphany-bin` | wc -l
2880      64
2881 $ # Unprelinked system
2882 $ LD_DEBUG=statistics epiphany-bin 2>&1 | sed 's/^ *//'
2883 18960:
2884 18960:     runtime linker statistics:
2885 18960:       total startup time in dynamic loader: 67336593 clock cycles
2886 18960:                 time needed for relocation: 58119983 clock cycles (86.3%)
2887 18960:                      number of relocations: 6999
2888 18960:           number of relocations from cache: 4770
2889 18960:             number of relative relocations: 31494
2890 18960:                time needed to load objects: 8696104 clock cycles (12.9%)
2891
2892 (epiphany-bin:18960): Gtk-WARNING **: cannot open display:
2893 18960:
2894 18960:     runtime linker statistics:
2895 18960:                final number of relocations: 7692
2896 18960:     final number of relocations from cache: 4770
2897 $ # Prelinked system
2898 $ LD_DEBUG=statistics epiphany-bin 2>&1 | sed 's/^ *//'
2899 25697:
2900 25697:  runtime linker statistics:
2901 25697:    total startup time in dynamic loader: 7313721 clock cycles
2902 25697:              time needed for relocation: 565680 clock cycles (7.7%)
2903 25697:                   number of relocations: 0
2904 25697:        number of relocations from cache: 1205
2905 25697:          number of relative relocations: 0
2906 25697:             time needed to load objects: 6179467 clock cycles (84.4%)
2907
2908 (epiphany-bin:25697): Gtk-WARNING **: cannot open display:
2909 25697:
2910 25697:  runtime linker statistics:
2911 25697:             final number of relocations: 31
2912 25697:  final number of relocations from cache: 1205
2913
2914 $ ldd `which evolution` | wc -l
2915      68
2916 $ # Unprelinked system
2917 $ LD_DEBUG=statistics evolution 2>&1 | sed 's/^ *//'
2918 19042:
2919 19042:  runtime linker statistics:
2920 19042:    total startup time in dynamic loader: 54382122 clock cycles
2921 19042:              time needed for relocation: 43403190 clock cycles (79.8%)
2922 19042:                   number of relocations: 3452
2923 19042:        number of relocations from cache: 2885
2924 19042:          number of relative relocations: 34957
2925 19042:             time needed to load objects: 10450142 clock cycles (19.2%)
2926
2927 (evolution:19042): Gtk-WARNING **: cannot open display:
2928 19042:
2929 19042:  runtime linker statistics:
2930 19042:             final number of relocations: 4075
2931 19042:  final number of relocations from cache: 2885
2932 $ # Prelinked system
2933 $ LD_DEBUG=statistics evolution 2>&1 | sed 's/^ *//'
2934 25723:
2935 25723:  runtime linker statistics:
2936 25723:    total startup time in dynamic loader: 9176140 clock cycles
2937 25723:              time needed for relocation: 203783 clock cycles (2.2%)
2938 25723:                   number of relocations: 0
2939 25723:        number of relocations from cache: 525
2940 25723:          number of relative relocations: 0
2941 25723:             time needed to load objects: 8405157 clock cycles (91.5%)
2942
2943 (evolution:25723): Gtk-WARNING **: cannot open display:
2944 25723:
2945 25723:  runtime linker statistics:
2946 25723:             final number of relocations: 31
2947 25723:  final number of relocations from cache: 525
2948
2949 $ ldd `which konqueror` | wc -l
2950      37
2951 $ # Unprelinked system
2952 $ LD_DEBUG=statistics konqueror 2>&1 | sed 's/^ *//'
2953 18979:
2954 18979:  runtime linker statistics:
2955 18979:    total startup time in dynamic loader: 131985703 clock cycles
2956 18979:              time needed for relocation: 127341077 clock cycles (96.4%)
2957 18979:                   number of relocations: 25473
2958 18979:        number of relocations from cache: 53594
2959 18979:          number of relative relocations: 31171
2960 18979:             time needed to load objects: 4318803 clock cycles (3.2%)
2961 konqueror: cannot connect to X server
2962 18979:
2963 18979:  runtime linker statistics:
2964 18979:             final number of relocations: 25759
2965 18979:  final number of relocations from cache: 53594
2966 $ # Prelinked system
2967 $ LD_DEBUG=statistics konqueror 2>&1 | sed 's/^ *//'
2968 25733:
2969 25733:  runtime linker statistics:
2970 25733:    total startup time in dynamic loader: 5533696 clock cycles
2971 25733:              time needed for relocation: 1941489 clock cycles (35.0%)
2972 25733:                   number of relocations: 0
2973 25733:        number of relocations from cache: 2066
2974 25733:          number of relative relocations: 0
2975 25733:             time needed to load objects: 3217736 clock cycles (58.1%)
2976 konqueror: cannot connect to X server
2977 25733:
2978 25733:  runtime linker statistics:
2979 25733:             final number of relocations: 0
2980 25733:  final number of relocations from cache: 2066
2981
2982 $ ldd `which kword` | wc -l
2983      40
2984 $ # Unprelinked system
2985 $ LD_DEBUG=statistics kword 2>&1 | sed 's/^ *//'
2986 19065:
2987 19065:  runtime linker statistics:
2988 19065:    total startup time in dynamic loader: 153684591 clock cycles
2989 19065:              time needed for relocation: 148255294 clock cycles (96.4%)
2990 19065:                   number of relocations: 26231
2991 19065:        number of relocations from cache: 55833
2992 19065:          number of relative relocations: 30660
2993 19065:             time needed to load objects: 5068746 clock cycles (3.2%)
2994 kword: cannot connect to X server
2995 19065:
2996 19065:  runtime linker statistics:
2997 19065:             final number of relocations: 26528
2998 19065:  final number of relocations from cache: 55833
2999 $ # Prelinked system
3000 $ LD_DEBUG=statistics kword 2>&1 | sed 's/^ *//'
3001 25749:
3002 25749:  runtime linker statistics:
3003 25749:    total startup time in dynamic loader: 6516635 clock cycles
3004 25749:              time needed for relocation: 2106856 clock cycles (32.3%)
3005 25749:                   number of relocations: 0
3006 25749:        number of relocations from cache: 2130
3007 25749:          number of relative relocations: 0
3008 25749:             time needed to load objects: 4008585 clock cycles (61.5%)
3009 kword: cannot connect to X server
3010 25749:
3011 25749:  runtime linker statistics:
3012 25749:             final number of relocations: 0
3013 25749:  final number of relocations from cache: 2130
3014 \end{verbatim}}
3015 \prelinklistingcaption{Dynamic linker statistics for unprelinked and prelinked GUI programs}}
3016
3017 In the case of above mentioned \tts{Gtk+} applications, the original startup
3018 time spent in the dynamic linker decreased into 11\% to 17\% of the original
3019 times, with \tts{KDE} applications it decreased even into around 4.2\% of original
3020 times.
3021
3022 The startup time reported by the dynamic linker is only part of the total
3023 startup time of a GUI program.  Unfortunately it cannot be measured very
3024 accurately without patching each application separately, so that it would
3025 print current process CPU time at the point when all windows are painted and
3026 the process starts waiting for user input.  The following table contains
3027 values reported by \tts{time(1)} command on each of the 4 GUI programs
3028 running under X, both on unprelinked and fully prelinked system.
3029 As soon as each program painted its windows, it was killed by
3030 application's quit hot key
3031 \footnote{\tts{Ctrl+W} for Epiphany, \tts{Ctrl+Q} for Evolution and
3032 Konqueror and \tts{Enter} in Kword's document type choice dialog.}.
3033 Especially the \tts{real} time values depend also on the speed of
3034 human reactions, so each measurement was repeated 10 times.  All timings
3035 were done with hot caches, after running the applications two times
3036 before measurement.
3037
3038 \noindent{\small\begin{center}
3039 \begin{longtable}{l|llllllllll|ll}
3040 {\bf Type} & \multicolumn{10}{l|}{\bf Values (in seconds)} & {\bf Average} & {\bf Std.Dev.} \\
3041 \hline
3042 \endhead
3043 & \multicolumn{10}{l|}{unprelinked epiphany} && \\
3044 \hline
3045 {real} & {3.053} & {2.84} & {2.996} & {2.901} & {3.019} & {2.929} & {2.883} & {2.975} & {2.922} & {3.026} & {2.954} & {0.0698} \\
3046 {user} & {2.33} & {2.31} & {2.28} & {2.32} & {2.44} & {2.37} & {2.29} & {2.35} & {2.34} & {2.41} & {2.344} & {0.0508} \\
3047 {sys} & {0.2} & {0.23} & {0.23} & {0.19} & {0.19} & {0.12} & {0.25} & {0.16} & {0.14} & {0.14} & {0.185} & {0.0440} \\
3048 \hline
3049 & \multicolumn{10}{l|}{prelinked epiphany} && \\
3050 \hline
3051 {real} & {2.773} & {2.743} & {2.833} & {2.753} & {2.753} & {2.644} & {2.717} & {2.897} & {2.68} & {2.761} & {2.755} & {0.0716} \\
3052 {user} & {2.18} & {2.17} & {2.17} & {2.12} & {2.23} & {2.26} & {2.13} & {2.17} & {2.15} & {2.15} & {2.173} & {0.0430} \\
3053 {sys} & {0.13} & {0.15} & {0.18} & {0.15} & {0.11} & {0.04} & {0.18} & {0.14} & {0.1} & {0.15} & {0.133} & {0.0416} \\
3054 \hline
3055 & \multicolumn{10}{l|}{unprelinked evolution} && \\
3056 \hline
3057 {real} & {2.106} & {1.886} & {1.828} & {2.12} & {1.867} & {1.871} & {2.242} & {1.871} & {1.862} & {2.241} & {1.989} & {0.1679} \\
3058 {user} & {1.12} & {1.09} & {1.15} & {1.19} & {1.17} & {1.23} & {1.15} & {1.11} & {1.17} & {1.14} & {1.152} & {0.0408} \\
3059 {sys} & {0.1} & {0.11} & {0.13} & {0.07} & {0.1} & {0.05} & {0.11} & {0.11} & {0.09} & {0.08} & {0.095} & {0.0232} \\
3060 \hline
3061 & \multicolumn{10}{l|}{prelinked evolution} && \\
3062 \hline
3063 {real} & {1.684} & {1.621} & {1.686} & {1.72} & {1.694} & {1.691} & {1.631} & {1.697} & {1.668} & {1.535} & {1.663} & {0.0541} \\
3064 {user} & {0.92} & {0.87} & {0.92} & {0.95} & {0.79} & {0.86} & {0.94} & {0.87} & {0.89} & {0.86} & {0.887} & {0.0476} \\
3065 {sys} & {0.06} & {0.1} & {0.06} & {0.05} & {0.11} & {0.08} & {0.07} & {0.1} & {0.12} & {0.07} & {0.082} & {0.0239} \\
3066 \hline
3067 & \multicolumn{10}{l|}{unprelinked kword} && \\
3068 \hline
3069 {real} & {2.111} & {1.414} & {1.36} & {1.356} & {1.259} & {1.383} & {1.28} & {1.321} & {1.252} & {1.407} & {1.414} & {0.2517} \\
3070 {user} & {1.04} & {0.9} & {0.93} & {0.88} & {0.89} & {0.89} & {0.87} & {0.89} & {0.9} & {0.8} & {0.899} & {0.0597} \\
3071 {sys} & {0.07} & {0.04} & {0.06} & {0.05} & {0.06} & {0.1} & {0.09} & {0.08} & {0.08} & {0.12} & {0.075} & {0.0242} \\
3072 \hline
3073 & \multicolumn{10}{l|}{prelinked kword} && \\
3074 \hline
3075 {real} & {1.59} & {1.052} & {0.972} & {1.064} & {1.106} & {1.087} & {1.066} & {1.087} & {1.065} & {1.005} & {1.109} & {0.1735} \\
3076 {user} & {0.61} & {0.53} & {0.58} & {0.6} & {0.6} & {0.58} & {0.59} & {0.61} & {0.57} & {0.6} & {0.587} & {0.0241} \\
3077 {sys} & {0.08} & {0.08} & {0.06} & {0.06} & {0.03} & {0.07} & {0.06} & {0.03} & {0.06} & {0.04} & {0.057} & {0.0183} \\
3078 \hline
3079 & \multicolumn{10}{l|}{unprelinked konqueror} && \\
3080 \hline
3081 {real} & {1.306} & {1.386} & {1.27} & {1.243} & {1.227} & {1.286} & {1.262} & {1.322} & {1.345} & {1.332} & {1.298} & {0.0495} \\
3082 {user} & {0.88} & {0.86} & {0.88} & {0.9} & {0.87} & {0.83} & {0.83} & {0.86} & {0.86} & {0.89} & {0.866} & {0.0232} \\
3083 {sys} & {0.07} & {0.11} & {0.12} & {0.1} & {0.12} & {0.08} & {0.13} & {0.12} & {0.09} & {0.08} & {0.102} & {0.0210} \\
3084 \hline
3085 & \multicolumn{10}{l|}{prelinked konqueror} && \\
3086 \hline
3087 {real} & {1.056} & {0.962} & {0.961} & {0.906} & {0.927} & {0.923} & {0.933} & {0.958} & {0.955} & {1.142} & {0.972} & {0.0722} \\
3088 {user} & {0.56} & {0.6} & {0.56} & {0.52} & {0.57} & {0.58} & {0.5} & {0.57} & {0.61} & {0.55} & {0.562} & {0.0334} \\
3089 {sys} & {0.1} & {0.13} & {0.08} & {0.15} & {0.07} & {0.09} & {0.09} & {0.09} & {0.1} & {0.08} & {0.098} & {0.0244} \\
3090 \hline
3091 \multicolumn{13}{l}{} \\
3092 \caption{GUI program start up times without and with prelinking} \\
3093 \end{longtable}
3094 \end{center}}
3095
3096 \tts{OpenOffice.org} is probably the largest program these days in Linux,
3097 mostly written in C++.  In \tts{OpenOffice.org} 1.1, the main executable,
3098 \tts{soffice.bin}, links directly against 34 shared libraries, but typically
3099 during startup it loads using \tts{dlopen} many others.  As has been
3100 mentioned earlier, \tts{prelink} cannot speed up loading shared libraries
3101 using \tts{dlopen}, since it cannot predict in which order and what
3102 shared libraries will be loaded (and thus cannot compute conflict fixups).
3103 The \tts{soffice.bin} is typically started through a wrapper script
3104 and depending on what arguments are passed to it, different
3105 \tts{OpenOffice.org} application is started.  With no options, it starts
3106 just empty window with menu from which the applications can be started,
3107 with say \tts{private:factory/swriter} argument it starts
3108 a word processor, with \tts{private:factory/scalc} it starts a spreadsheet
3109 etc.  When \tts{soffice.bin} is already running, if you start another
3110 copy of it, it just instructs the already running copy to pop up a new
3111 window and exits.
3112
3113 In an experiment, \tts{soffice.bin} has been invoked 7 times against running
3114 X server, with no arguments, \tts{private:factory/swriter},
3115 \tts{private:factory/scalc}, \tts{private:factory/sdraw},
3116 \tts{private:factory/simpress}, \tts{private:factory/smath} arguments
3117 (in all these cases nothing was pressed at all) and last with
3118 the \tts{private:factory/swriter} argument where the menu item \tts{New Presentation}
3119 was selected and the word processor window closed.
3120 In all these cases, \tts{/proc/`pidof soffice.bin`/maps} file was
3121 captured and the application then killed.  This file contains among
3122 other things list of all shared libraries mmapped by the process at
3123 the point where it started waiting for user input after loading up.
3124 These lists were then summarized, to get number of the runs in
3125 which particular shared library was loaded up out of the total 7
3126 runs.  There were 38 shared libraries shipped as part of \tts{OpenOffice.org}
3127 package which have been loaded in all 7 times, another 3 shared
3128 libraries included in \tts{OpenOffice.org} (and also one shared
3129 library shipped in another package, \tts{libdb\_cxx-4.1.so})
3130 which were loaded 6 times.
3131 \footnote{In all runs but when ran without
3132 arguments.  But when the application is started without any
3133 arguments, it cannot do any useful work, so one loads one of the
3134 applications afterward anyway.}  There was one shared library
3135 loaded in 5 runs, but was locale specific and thus not worth
3136 considering.  Inspecting \tts{OpenOffice.org} source, these shared
3137 libraries are never unloaded with \tts{dlclose}, so \tts{soffice.bin}
3138 can be made much more \tts{prelink} friendly and thus save substantial
3139 amount of startup time by linking against all those 76 shared libraries
3140 instead of just 34 shared libraries it is linked against.
3141 In the timings below, \tts{soffice1.bin} is the original \tts{soffice.bin}
3142 as created by the \tts{OpenOffice.org} makefiles and \tts{soffice3.bin} is
3143 the same executable linked dynamically against additional 42 shared libraries.
3144 The ordering of those 42 shared libraries matters for the number of conflict
3145 fixups, unfortunately with large C++ shared libraries there is no obvious rule
3146 for ordering them as sometimes it is more useful when a shared library precedes
3147 its dependency and sometimes vice versa, so a few different orderings were
3148 tried in several steps and always the one with smallest number of conflict
3149 fixups was chosen.  Still, the number of conflict fixups is quite high
3150 and big part of the fixups are storing addresses of \tts{PLT} slots in
3151 the executable into various places in shared libraries
3152 \footnote{This might get better when the linker is modified to handle
3153 calls without ever taking address of the function in executables specially,
3154 but only testing it will actually show it up.}
3155 \tts{soffice2.bin} is another experiment, where the executable itself is empty
3156 source file, all objects which were originally in \tts{soffice.bin}
3157 executable with the exception of start files were recompiled as position independent
3158 code and linked into a new shared library.  This reduced number of conflicts
3159 a lot and speeded up start up times against \tts{soffice3.bin} when caches
3160 are hot.  It is a little bit slower than \tts{soffice3.bin} when running
3161 with cold caches (e.g. for the first time after bootup), as there is one
3162 more shared library to load etc.
3163
3164 In the timings below, numbers for \tts{soffice1.bin} and \tts{soffice2.bin}
3165 resp. \tts{soffice3.bin} cannot be easily compared, as \tts{soffice1.bin}
3166 loads less than half of the needed shared libraries which the remaining
3167 two executables load and the time to load those shared libraries doesn't
3168 show up there.  Still, when it is prelinked it takes just slightly more
3169 than two times longer to load \tts{soffice2.bin} than \tts{soffice1.bin}
3170 and the times are still less than 7\% of how long it takes to load
3171 just the initial 34 shared libraries when not prelinking.
3172
3173 \noindent{{\small\begin{verbatim}
3174 $ S='s/^ *//'
3175 $ ldd /usr/lib/openoffice/program/soffice1.bin | wc -l
3176      34
3177 $ # Unprelinked system
3178 $ LD_DEBUG=statistics /usr/lib/openoffice/program/soffice1.bin 2>&1 | sed "$S"
3179 19095:
3180 19095:  runtime linker statistics:
3181 19095:    total startup time in dynamic loader: 159833582 clock cycles
3182 19095:              time needed for relocation: 155464174 clock cycles (97.2%)
3183 19095:                   number of relocations: 31136
3184 19095:        number of relocations from cache: 31702
3185 19095:          number of relative relocations: 18284
3186 19095:             time needed to load objects: 3919645 clock cycles (2.4%)
3187 /usr/lib/openoffice/program/soffice1.bin X11 error: Can't open display:
3188 Set DISPLAY environment variable, use -display option
3189 or check permissions of your X-Server
3190 (See "man X" resp. "man xhost" for details)
3191 19095:
3192 19095:  runtime linker statistics:
3193 19095:             final number of relocations: 31715
3194 19095:  final number of relocations from cache: 31702
3195 $ # Prelinked system
3196 $ LD_DEBUG=statistics /usr/lib/openoffice/program/soffice1.bin 2>&1 | sed "$S"
3197 25759:
3198 25759:  runtime linker statistics:
3199 25759:    total startup time in dynamic loader: 4252397 clock cycles
3200 25759:              time needed for relocation: 1189840 clock cycles (27.9%)
3201 25759:                   number of relocations: 0
3202 25759:        number of relocations from cache: 2142
3203 25759:          number of relative relocations: 0
3204 25759:             time needed to load objects: 2604486 clock cycles (61.2%)
3205 /usr/lib/openoffice/program/soffice1.bin X11 error: Can't open display:
3206 Set DISPLAY environment variable, use -display option
3207 or check permissions of your X-Server
3208 (See "man X" resp. "man xhost" for details)
3209 25759:
3210 25759:  runtime linker statistics:
3211 25759:             final number of relocations: 24
3212 25759:  final number of relocations from cache: 2142
3213 $ ldd /usr/lib/openoffice/program/soffice2.bin | wc -l
3214      77
3215 $ # Unprelinked system
3216 $ LD_DEBUG=statistics /usr/lib/openoffice/program/soffice2.bin 2>&1 | sed "$S"
3217 19115:
3218 19115:  runtime linker statistics:
3219 19115:    total startup time in dynamic loader: 947793670 clock cycles
3220 19115:              time needed for relocation: 936895741 clock cycles (98.8%)
3221 19115:                   number of relocations: 69164
3222 19115:        number of relocations from cache: 94502
3223 19115:          number of relative relocations: 59374
3224 19115:             time needed to load objects: 10046486 clock cycles (1.0%)
3225 /usr/lib/openoffice/program/soffice2.bin X11 error: Can't open display:
3226 Set DISPLAY environment variable, use -display option
3227 or check permissions of your X-Server
3228 (See "man X" resp. "man xhost" for details)
3229 19115:
3230 19115:  runtime linker statistics:
3231 19115:             final number of relocations: 69966
3232 19115:  final number of relocations from cache: 94502
3233 $ # Prelinked system
3234 $ LD_DEBUG=statistics /usr/lib/openoffice/program/soffice2.bin 2>&1 | sed "$S"
3235 25777:
3236 25777:  runtime linker statistics:
3237 25777:    total startup time in dynamic loader: 10952099 clock cycles
3238 25777:              time needed for relocation: 3254518 clock cycles (29.7%)
3239 25777:                   number of relocations: 0
3240 25777:        number of relocations from cache: 5309
3241 25777:          number of relative relocations: 0
3242 25777:             time needed to load objects: 6805013 clock cycles (62.1%)
3243 /usr/lib/openoffice/program/soffice2.bin X11 error: Can't open display:
3244 Set DISPLAY environment variable, use -display option
3245 or check permissions of your X-Server
3246 (See "man X" resp. "man xhost" for details)
3247 25777:
3248 25777:  runtime linker statistics:
3249 25777:             final number of relocations: 24
3250 25777:  final number of relocations from cache: 5309
3251 $ ldd /usr/lib/openoffice/program/soffice3.bin | wc -l
3252      76
3253 $ # Unprelinked system
3254 $ LD_DEBUG=statistics /usr/lib/openoffice/program/soffice3.bin 2>&1 | sed "$S"
3255 19131:
3256 19131:  runtime linker statistics:
3257 19131:    total startup time in dynamic loader: 852275754 clock cycles
3258 19131:              time needed for relocation: 840996859 clock cycles (98.6%)
3259 19131:                   number of relocations: 68362
3260 19131:        number of relocations from cache: 89213
3261 19131:          number of relative relocations: 55831
3262 19131:             time needed to load objects: 10170207 clock cycles (1.1%)
3263 /usr/lib/openoffice/program/soffice3.bin X11 error: Can't open display:
3264 Set DISPLAY environment variable, use -display option
3265 or check permissions of your X-Server
3266 (See "man X" resp. "man xhost" for details)
3267 19131:
3268 19131:  runtime linker statistics:
3269 19131:             final number of relocations: 69177
3270 19131:  final number of relocations from cache: 89213
3271 $ # Prelinked system
3272 $ LD_DEBUG=statistics /usr/lib/openoffice/program/soffice3.bin 2>&1 | sed "$S"
3273 25847:
3274 25847:  runtime linker statistics:
3275 25847:    total startup time in dynamic loader: 12277407 clock cycles
3276 25847:              time needed for relocation: 4232915 clock cycles (34.4%)
3277 25847:                   number of relocations: 0
3278 25847:        number of relocations from cache: 8961
3279 25847:          number of relative relocations: 0
3280 25847:             time needed to load objects: 6925023 clock cycles (56.4%)
3281 /usr/lib/openoffice/program/soffice3.bin X11 error: Can't open display:
3282 Set DISPLAY environment variable, use -display option
3283 or check permissions of your X-Server
3284 (See "man X" resp. "man xhost" for details)
3285 25847:
3286 25847:  runtime linker statistics:
3287 25847:             final number of relocations: 24
3288 25847:  final number of relocations from cache: 8961
3289 \end{verbatim}}
3290 \prelinklistingcaption{Dynamic linker statistics for unprelinked and prelinked OpenOffice.org}}
3291
3292 Below are measurement using \tts{time(1)} for each of the \tts{soffice.bin}
3293 variants, prelinked and unprelinked.  \tts{OpenOffice.org} was killed
3294 immediately after painting \tts{Writer}'s window using \tts{Ctrl+Q}.
3295
3296 \noindent{\small\begin{center}
3297 \begin{longtable}{l|llllllllll|ll}
3298 {\bf Type} & \multicolumn{10}{l|}{\bf Values (in seconds)} & {\bf Average} & {\bf Std.Dev.} \\
3299 \hline
3300 \endhead
3301 & \multicolumn{10}{l|}{unprelinked soffice1.bin private:factory/swriter} && \\
3302 \hline
3303 {real} & {5.569} & {5.149} & {5.547} & {5.559} & {5.549} & {5.139} & {5.55} & {5.559} & {5.598} & {5.559} & {5.478} & {0.1765} \\
3304 {user} & {4.65} & {4.57} & {4.62} & {4.64} & {4.57} & {4.55} & {4.65} & {4.49} & {4.52} & {4.46} & {4.572} & {0.0680} \\
3305 {sys} & {0.29} & {0.24} & {0.19} & {0.21} & {0.21} & {0.21} & {0.25} & {0.25} & {0.27} & {0.26} & {0.238} & {0.0319} \\
3306 \hline
3307 & \multicolumn{10}{l|}{prelinked soffice1.bin private:factory/swriter} && \\
3308 \hline
3309 {real} & {4.946} & {4.899} & {5.291} & {4.879} & {4.879} & {4.898} & {5.299} & {4.901} & {4.887} & {4.901} & {4.978} & {0.1681} \\
3310 {user} & {4.23} & {4.27} & {4.18} & {4.24} & {4.17} & {4.22} & {4.15} & {4.25} & {4.26} & {4.31} & {4.228} & {0.0494} \\
3311 {sys} & {0.22} & {0.22} & {0.24} & {0.26} & {0.3} & {0.26} & {0.29} & {0.17} & {0.21} & {0.23} & {0.24} & {0.0389} \\
3312 \hline
3313 & \multicolumn{10}{l|}{unprelinked soffice2.bin private:factory/swriter} && \\
3314 \hline
3315 {real} & {5.575} & {5.166} & {5.592} & {5.149} & {5.571} & {5.559} & {5.159} & {5.157} & {5.569} & {5.149} & {5.365} & {0.2201} \\
3316 {user} & {4.59} & {4.5} & {4.57} & {4.37} & {4.47} & {4.57} & {4.56} & {4.41} & {4.63} & {4.5} & {4.517} & {0.0826} \\
3317 {sys} & {0.24} & {0.24} & {0.21} & {0.34} & {0.27} & {0.19} & {0.19} & {0.27} & {0.19} & {0.29} & {0.243} & {0.0501} \\
3318 \hline
3319 & \multicolumn{10}{l|}{prelinked soffice2.bin private:factory/swriter} && \\
3320 \hline
3321 {real} & {3.69} & {3.66} & {3.658} & {3.661} & {3.639} & {3.638} & {3.649} & {3.659} & {3.65} & {3.659} & {3.656} & {0.0146} \\
3322 {user} & {2.93} & {2.88} & {2.88} & {2.9} & {2.84} & {2.63} & {2.89} & {2.85} & {2.77} & {2.83} & {2.84} & {0.0860} \\
3323 {sys} & {0.22} & {0.18} & {0.23} & {0.2} & {0.18} & {0.29} & {0.22} & {0.23} & {0.24} & {0.22} & {0.221} & {0.0318} \\
3324 \hline
3325 & \multicolumn{10}{l|}{unprelinked soffice3.bin private:factory/swriter} && \\
3326 \hline
3327 {real} & {5.031} & {5.02} & {5.009} & {5.028} & {5.019} & {5.019} & {5.019} & {5.052} & {5.426} & {5.029} & {5.065} & {0.1273} \\
3328 {user} & {4.31} & {4.35} & {4.34} & {4.3} & {4.38} & {4.29} & {4.45} & {4.37} & {4.38} & {4.44} & {4.361} & {0.0547} \\
3329 {sys} & {0.27} & {0.25} & {0.26} & {0.27} & {0.27} & {0.31} & {0.18} & {0.17} & {0.16} & {0.15} & {0.229} & {0.0576} \\
3330 \hline
3331 & \multicolumn{10}{l|}{prelinked soffice3.bin private:factory/swriter} && \\
3332 \hline
3333 {real} & {3.705} & {3.669} & {3.659} & {3.669} & {3.66} & {3.659} & {3.659} & {3.661} & {3.668} & {3.649} & {3.666} & {0.0151} \\
3334 {user} & {2.86} & {2.88} & {2.85} & {2.84} & {2.83} & {2.86} & {2.84} & {2.91} & {2.86} & {2.8} & {2.853} & {0.0295} \\
3335 {sys} & {0.26} & {0.19} & {0.27} & {0.25} & {0.24} & {0.23} & {0.28} & {0.21} & {0.21} & {0.27} & {0.241} & {0.0303} \\
3336 \hline
3337 \multicolumn{13}{l}{} \\
3338 \caption{OpenOffice.org start up times without and with prelinking} \\
3339 \end{longtable}
3340 \end{center}}
3341
3342 \section{Similar tools on other ELF using Operating Systems}
3343
3344 Something similar to \tts{prelink} is available on other \tts{ELF}
3345 platforms.  On Irix there is \tts{QUICKSTART} and on Solaris \tts{crle}.
3346
3347 SGI \tts{QUICKSTART} is much closer to \tts{prelink} from these two.
3348 The \tts{rqs} program relocates libraries to (if possible) unique
3349 virtual address space slot.  The base address is either specified
3350 on the command line with the \tts{-l} option, or \tts{rqs} uses
3351 a \tts{so\_locations} registry with \tts{-c} or \tts{-u} options
3352 and finds a not yet occupied slot.  This is similar to how \tts{prelink}
3353 lays out libraries without the \tts{-m} option.
3354
3355 \tts{QUICKSTART} uses the same data structure for library lists
3356 (\tts{ElfNN\_Lib}) as \tts{prelink}, but uses more fields in it
3357 (\tts{prelink} doesn't use \tts{l\_version} and \tts{l\_flags} fields at
3358 the moment) and uses different dynamic tags and section type for
3359 it.  Another difference is that \tts{QUICKSTART} makes all liblist
3360 section \tts{SHF\_ALLOC}, whether in shared libraries or executables.
3361 \tts{prelink} only needs liblist section in the executable be allocated,
3362 liblist sections in shared libraries are not allocated and used
3363 at \tts{prelink} time only.
3364
3365 The biggest difference between \tts{QUICKSTART} and \tts{prelink}
3366 is in how conflicts are encoded.  SGI stores them in a very compact
3367 format, as array of \tts{.dynsym} section indexes for symbols which
3368 are conflicting.  There is no information publicly available
3369 what exactly SGI dynamic linker does when it is resolving the conflicts,
3370 so this is just a guess.  Given that the conflicts can be stored
3371 in a shared library or executable different to the shared library with the
3372 relocations against the conflicting symbol and different to the shared
3373 library which the symbol was originally resolved to, there doesn't seem
3374 to be an obvious way how to handle the conflicts very cheaply.
3375 The dynamic linker probably collects list of all conflicting symbol
3376 names, for each such symbol computes \tts{ELF} hash and walks hash buckets
3377 for this hash of all shared libraries, looking for the symbol.
3378 Every time it finds the symbol, all relocations against it need to be
3379 redone.  Unlike this, \tts{prelink} stores conflicts as an array of
3380 \tts{ElfNN\_Rela} structures, with one entry for each shared relocation
3381 against conflicting symbol in some shared library.  This guarantees
3382 that there are no symbol lookups during program startup (provided
3383 that shared libraries have not been changed after prelinking), while
3384 with \tts{QUICKSTART} will do some symbol lookups if there are any
3385 conflicts.  \tts{QUICKSTART} puts conflict sections into the executable
3386 and every shared library where \tts{rqs} determines conflicts while
3387 \tts{prelink} stores them in the executable only (but the array is typically
3388 much bigger).  Disk space requirements for prelinked executables are certainly
3389 bigger than for requickstarted executables, but which one has bigger runtime
3390 memory requirements is unclear.  If prelinking can be used, all \tts{.rela*}
3391 and \tts{.rel*} sections in the executable and all shared libraries are skipped,
3392 so they will not need to be paged in during whole program's life (with the
3393 exception of first and last pages in the relocation sections which can be
3394 paged in because of other sections on the same page), but whole
3395 \tts{.gnu.conflict} section needs to be paged in (read-only) and processed.
3396 With \tts{QUICKSTART}, probably all (much smaller) conflict sections need
3397 to be paged in and also likely for each conflict whole relocation sections
3398 of each library which needs the conflict to be applied against.
3399
3400 In \tts{QUICKSTART} documentation, SGI says that conflicts are very costly
3401 and that developers should avoid them.  Unfortunately, this is sometimes quite
3402 hard, especially with C++ shared libraries.  It is unclear whether \tts{rqs}
3403 does any optimizations to trim down the number of conflicts.
3404
3405 Sun took completely different approach.  The dynamic linker provides a
3406 \tts{dldump (const char *ipath, const char *opath, int flags);} function.
3407 {\sl ipath} is supposed to be a path to an \tts{ELF} object loaded already in
3408 the current process.  This function creates a new \tts{ELF} object at
3409 {\sl opath}, which is like the {\sl ipath} object, but relocated to the
3410 base address which it has actually been mapped at in the current process
3411 and with some relocations (specified in {\sl flags} bitmask) applied as
3412 they have been resolved in the current process.  Relocations, which have
3413 been applied, are overwritten in the relocation sections with
3414 \tts{R\_*\_NONE} relocations.  The \tts{crle} executable, in addition to other
3415 functions not related to startup times, with some specific options uses the
3416 \tts{dldump} function to dump all shared libraries a particular executable
3417 uses (and the executable itself) into a new directory, with selected
3418 relocation classes being already applied.  The main disadvantage of this
3419 approach is that such alternate shared libraries are at least for
3420 most relocation classes not shareable across different programs at all
3421 (and for those where they could be shareable a little bit there will
3422 be many relocations left for the dynamic linker, so the speed gains will
3423 be small).  Another disadvantage is that all relocation sections need to
3424 be paged into the memory, just to find out that most of the relocations
3425 are \tts{R\_*\_NONE}.
3426
3427 \section{ELF extensions for prelink}
3428
3429 \tts{Prelink} needs a few \tts{ELF} extensions for its data structures
3430 in \tts{ELF} objects.  For list of dependencies at the time of prelinking,
3431 a new section type \tts{SHT\_GNU\_LIBLIST} is defined:
3432
3433 \noindent{{\small\begin{verbatim}
3434 #define SHT_GNU_LIBLIST   0x6ffffff7  /* Prelink library list */
3435
3436 typedef struct
3437 {
3438   Elf32_Word l_name;            /* Name (string table index) */
3439   Elf32_Word l_time_stamp;      /* Timestamp */
3440   Elf32_Word l_checksum;        /* Checksum */
3441   Elf32_Word l_version;         /* Unused, should be zero */
3442   Elf32_Word l_flags;           /* Unused, should be zero */
3443 } Elf32_Lib;
3444
3445 typedef struct
3446 {
3447   Elf64_Word l_name;            /* Name (string table index) */
3448   Elf64_Word l_time_stamp;      /* Timestamp */
3449   Elf64_Word l_checksum;        /* Checksum */
3450   Elf64_Word l_version;         /* Unused, should be zero */
3451   Elf64_Word l_flags;           /* Unused, should be zero */
3452 } Elf64_Lib;
3453 \end{verbatim}}
3454 \prelinklistingcaption{New structures and section type constants used by \tts{prelink}}}
3455
3456 Introduces a few new special sections:
3457
3458 \noindent{\begin{center}
3459 \begin{longtable}{l|lc}
3460 {\bf Name} & {\bf Type} & {\bf Attributes} \\
3461 \hline
3462 & {\sl In shared libraries} & \\
3463 {.gnu.liblist} & {SHT\_GNU\_LIBLIST} & {0} \\
3464 {.gnu.libstr} & {SHT\_STRTAB} & {0} \\
3465 {.gnu.prelink\_undo} & {SHT\_PROGBITS} & {0} \\
3466 \hline
3467 & {\sl In executables} & \\
3468 {.gnu.liblist} & {SHT\_GNU\_LIBLIST} & {SHF\_ALLOC} \\
3469 {.gnu.conflict} & {SHT\_RELA} & {SHF\_ALLOC} \\
3470 {.gnu.prelink\_undo} & {SHT\_PROGBITS} & {0} \\
3471 \multicolumn{3}{l}{} \\
3472 \caption{Special sections introduced by \tts{prelink}} \\
3473 \end{longtable}
3474 \end{center}}
3475
3476 \begin{description}
3477 \item[\tts{.gnu.liblist}] This section contains one \tts{ElfNN\_Lib} structure
3478 for each shared library which the object has been prelinked against,
3479 in the order in which they appear in symbol search scope.
3480 Section's \tts{sh\_link} value should contain section index of \tts{.gnu.libstr}
3481 for shared libraries and section index of \tts{.dynsym} for executables.
3482 \tts{l\_name} field contains the dependent library's name as index
3483 into the section pointed by\tts{sh\_link} field.  \tts{l\_time\_stamp}
3484 resp. \tts{l\_checksum} should contain copies of \tts{DT\_GNU\_PRELINKED}
3485 resp. \tts{DT\_CHECKSUM} values of the dependent library.
3486
3487 \item[\tts{.gnu.conflict}] This section contains one \tts{ElfNN\_Rela}
3488 structure for each needed \tts{prelink} conflict fixup.  \tts{r\_offset}
3489 field contains the absolute address at which the fixup needs to be applied,
3490 \tts{r\_addend} the value that needs to be stored at that location.
3491 \tts{ELFNN\_R\_SYM} of \tts{r\_info} field should be zero,
3492 \tts{ELFNN\_R\_TYPE} of \tts{r\_info} field should be architecture
3493 specific relocation type which should be handled the same as
3494 for \tts{.rela.*} sections on the architecture.  For \tts{EM\_ALPHA} machine,
3495 all types with \tts{R\_ALPHA\_JMP\_SLOT} in lowest 8 bits of \tts{ELF64\_R\_TYPE}
3496 should be handled as \tts{R\_ALPHA\_JMP\_SLOT} relocation, the upper
3497 24 bits contains index in original \tts{.rela.plt} section of the
3498 \tts{R\_ALPHA\_JMP\_SLOT} relocation the fixup was created for.
3499
3500 \item[\tts{.gnu.libstr}] This section contains strings for \tts{.gnu.liblist}
3501 section in shared libraries where \tts{.gnu.liblist} section is not
3502 allocated.
3503
3504 \item[\tts{.gnu.prelink\_undo}] This section contains \tts{prelink} private
3505 data used for \tts{prelink --undo} operation.  This data includes the
3506 original \tts{ElfNN\_Ehdr} of the object before prelinking and all its
3507 original \tts{ElfNN\_Phdr} and \tts{ElfNN\_Shdr} headers.
3508 \end{description}
3509
3510 \tts{Prelink} also defines 6 new dynamic tags:
3511
3512 \noindent{{\small\begin{verbatim}
3513 #define DT_GNU_PRELINKED  0x6ffffdf5  /* Prelinking timestamp */
3514 #define DT_GNU_CONFLICTSZ 0x6ffffdf6  /* Size of conflict section */
3515 #define DT_GNU_LIBLISTSZ  0x6ffffdf7  /* Size of library list */
3516 #define DT_CHECKSUM       0x6ffffdf8  /* Library checksum */
3517
3518 #define DT_GNU_CONFLICT   0x6ffffef8  /* Start of conflict section */
3519 #define DT_GNU_LIBLIST    0x6ffffef9  /* Library list */
3520 \end{verbatim}}
3521 \prelinklistingcaption{\tts{Prelink} dynamic tags}}
3522
3523 \tts{DT\_GNU\_PRELINKED} and \tts{DT\_CHECKSUM} dynamic tags must
3524 be present in prelinked shared libraries.  The corresponding
3525 \tts{d\_un.d\_val} fields should contain time when the library
3526 has been prelinked (in seconds since January, 1st, 1970, 00:00 UTC)
3527 resp. \tts{CRC32} checksum of all sections with one of
3528 \tts{SHF\_ALLOC}, \tts{SHF\_WRITE} or \tts{SHF\_EXECINSTR} bit set
3529 whose type is not \tts{SHT\_NOBITS}, in the order they appear in the
3530 shared library's section header table, with \tts{DT\_GNU\_PRELINKED}
3531 and \tts{DT\_CHECKSUM} \tts{d\_un.v\_val} values set to 0 for
3532 the time of checksum computation.
3533
3534 The \tts{DT\_GNU\_LIBLIST} and \tts{DT\_GNU\_LIBLISTSZ} dynamic tags
3535 must be present in all prelinked executables.  The \tts{d\_un.d\_ptr} value of
3536 the \tts{DT\_GNU\_LIBLIST} dynamic tag contains the virtual address
3537 of the \tts{.gnu.liblist} section in the executable and \tts{d\_un.d\_val}
3538 of \tts{DT\_GNU\_LIBLISTSZ} tag contains its size in bytes.
3539
3540 \tts{DT\_GNU\_CONFLICT} and \tts{DT\_GNU\_CONFLICTSZ} dynamic tags
3541 may be present in prelinked executables.  \tts{d\_un.d\_ptr} of
3542 \tts{DT\_GNU\_CONFLICT} dynamic tag contains the virtual address
3543 of \tts{.gnu.conflict} section in the executable (if present)
3544 and \tts{d\_un.d\_val} of \tts{DT\_GNU\_CONFLICTSZ} tag contains
3545 its size in bytes.
3546
3547 \begin{appendix}
3548
3549 \section{Glossary}
3550 \printglossary
3551
3552 \section{References}
3553
3554 \begin{description}
3555 \item[\textrm{[1]}]
3556 \href{http://www.caldera.com/developers/devspecs/gabi41.pdf}%
3557 {\sl System V Application Binary Interface, Edition 4.1}.
3558
3559 \item[\textrm{[2]}]
3560 \href{http://www.caldera.com/developers/devspecs/abi386-4.pdf}%
3561 {\sl System V Application Binary Interface, Intel 386 Architecture Processor
3562 Supplement}.
3563
3564 \item[\textrm{[3]}]
3565 \href{http://www.x86-64.org/cgi-bin/cvsweb.cgi/x86-64-ABI/}%
3566 {\sl System V Application Binary Interface, AMD64 Architecture Processor
3567 Supplement}.
3568
3569 \item[\textrm{[4]}]
3570 \href{http://refspecs.freestandards.org/elf/IA64-SysV-psABI.pdf}%
3571 {{\sl System V Application Binary Interface, Intel Itanium Architecture Processor
3572 Supplement}, Intel Corporation, 2001}.
3573
3574 \item[\textrm{[5]}]
3575 \href{http://refspecs.freestandards.org/elf/elfspec_ppc.pdf}%
3576 {Steve Zucker, Kari Karhi, {\sl System V Application Binary Interface,
3577 PowerPC Architecture Processor Supplement}, SunSoft, IBM, 1995}.
3578
3579 \item[\textrm{[6]}]
3580 \href{ftp://ftp.linuxppc64.org/pub/people/amodra/PPC-elf64abi.txt.gz}%
3581 {\sl System V Application Binary Interface, PowerPC64 Architecture Processor
3582 Supplement}.
3583
3584 \item[\textrm{[7]}]
3585 \href{http://www.arm.com/support/566FHT/$File/ARMELF.pdf}%
3586 {\sl System V Application Binary Interface, ARM Architecture Processor
3587 Supplement}.
3588
3589 \item[\textrm{[8]}]
3590 \href{http://www.sparc.com/standards/SCD.2.4.1.ps.Z}%
3591 {{\sl SPARC Compliance Definition, Version 2.4.1},
3592 SPARC International, Inc., 1999}.
3593
3594 \item[\textrm{[9]}]
3595 \href{http://people.redhat.com/drepper/dsohowto.pdf}%
3596 {Ulrich Drepper, {\sl How To Write Shared Libraries}, Red Hat, Inc., 2003}.
3597
3598 \item[\textrm{[10]}]
3599 \href{http://docs.sun.com/db/doc/816-1386}%
3600 {{\sl Linker And Library Guide}, Sun Microsystems, 2002}.
3601
3602 \item[\textrm{[11]}]
3603 \href{http://www.gzlinux.org/docs/category/dev/c/linkerandloader.pdf}%
3604 {John R. Levine, {\sl Linkers and Loaders}, 1999}.
3605
3606 \item[\textrm{[12]}]
3607 \href{http://people.redhat.com/drepper/tls.pdf}%
3608 {Ulrich Drepper, {\sl ELF Handling For Thread-Local Storage}, Red Hat, Inc.,
3609 2003}.
3610
3611 \item[\textrm{[13]}]
3612 \href{ftp://ftp.linuxppc64.org/pub/people/amodra/ppc32tls.txt.gz}%
3613 {Alan Modra, {\sl PowerPC Specific Thread Local Storage ABI}, 2003}.
3614
3615 \item[\textrm{[14]}]
3616 \href{ftp://ftp.linuxppc64.org/pub/people/amodra/ppc64tls.txt.gz}%
3617 {Alan Modra, {\sl PowerPC64 Specific Thread Local Storage ABI}, 2003}.
3618
3619 \item[\textrm{[15]}]
3620 \href{http://www.eagercon.com/dwarf/dwarf-2.0.0.pdf}%
3621 {\sl DWARF Debugging Information Format Version 2}.
3622
3623 \item[\textrm{[16]}]
3624 \href{http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf}%
3625 {{\sl DWARF Debugging Information Format Version 3}, Draft, 2001}.
3626
3627 \item[\textrm{[17]}]
3628 \href{http://sources.redhat.com/cgi-bin/cvsweb.cgi/src/gdb/doc/stabs.texinfo?cvsroot=src}%
3629 {\sl The "stabs" debugging information format}.
3630 \end{description}
3631
3632
3633 \section{Revision History}
3634
3635 \begin{description}
3636 \item[2003-11-03] First draft.
3637
3638
3639 \end{description}
3640
3641 \end{appendix}
3642
3643 \end{document}