2 @c @node Dynamic Linker, Internal Probes, Threads, Top
3 @c %MENU% Loading programs and shared objects.
4 @chapter Dynamic Linker
8 The @dfn{dynamic linker} is responsible for loading dynamically linked
9 programs and their dependencies (in the form of shared objects). The
10 dynamic linker in @theglibc{} also supports loading shared objects (such
11 as plugins) later at run time.
13 Dynamic linkers are sometimes called @dfn{dynamic loaders}.
16 * Dynamic Linker Invocation:: Explicit invocation of the dynamic linker.
17 * Dynamic Linker Introspection:: Interfaces for querying mapping information.
18 * Dynamic Linker Hardening:: Avoiding unexpected issues with dynamic linking.
21 @node Dynamic Linker Invocation
22 @section Dynamic Linker Invocation
24 @cindex program interpreter
25 When a dynamically linked program starts, the operating system
26 automatically loads the dynamic linker along with the program.
27 @Theglibc{} also supports invoking the dynamic linker explicitly to
28 launch a program. This command uses the implied dynamic linker
29 (also sometimes called the @dfn{program interpreter}):
32 sh -c 'echo "Hello, world!"'
35 This command specifies the dynamic linker explicitly:
38 ld.so /bin/sh -c 'echo "Hello, world!"'
41 Note that @command{ld.so} does not search the @env{PATH} environment
42 variable, so the full file name of the executable needs to be specified.
44 The @command{ld.so} program supports various options. Options start
45 @samp{--} and need to come before the program that is being launched.
46 Some of the supported options are listed below.
49 @item --list-diagnostics
50 Print system diagnostic information in a machine-readable format.
51 @xref{Dynamic Linker Diagnostics}.
55 * Dynamic Linker Diagnostics:: Obtaining system diagnostic information.
58 @node Dynamic Linker Diagnostics
59 @subsection Dynamic Linker Diagnostics
60 @cindex diagnostics (dynamic linker)
62 The @samp{ld.so --list-diagnostics} produces machine-readable
63 diagnostics output. This output contains system data that affects the
64 behavior of @theglibc{}, and potentially application behavior as well.
66 The exact set of diagnostic items can change between releases of
67 @theglibc{}. The output format itself is not expected to change
70 The following table shows some example lines that can be written by the
74 @item dl_pagesize=0x1000
75 The system page size is 4096 bytes.
77 @item env[0x14]="LANG=en_US.UTF-8"
78 This item indicates that the 21st environment variable at process
79 startup contains a setting for @code{LANG}.
81 @item env_filtered[0x22]="DISPLAY"
82 The 35th environment variable is @code{DISPLAY}. Its value is not
83 included in the output for privacy reasons because it is not recognized
84 as harmless by the diagnostics code.
86 @item path.prefix="/usr"
87 This means that @theglibc{} was configured with @code{--prefix=/usr}.
89 @item path.system_dirs[0x0]="/lib64/"
90 @itemx path.system_dirs[0x1]="/usr/lib64/"
91 The built-in dynamic linker search path contains two directories,
92 @code{/lib64} and @code{/usr/lib64}.
96 * Dynamic Linker Diagnostics Format:: Format of ld.so output.
97 * Dynamic Linker Diagnostics Values:: Data contain in ld.so output.
100 @node Dynamic Linker Diagnostics Format
101 @subsubsection Dynamic Linker Diagnostics Format
103 As seen above, diagnostic lines assign values (integers or strings) to a
104 sequence of labeled subscripts, separated by @samp{.}. Some subscripts
105 have integer indices associated with them. The subscript indices are
106 not necessarily contiguous or small, so an associative array should be
107 used to store them. Currently, all integers fit into the 64-bit
108 unsigned integer range. Every access path to a value has a fixed type
109 (string or integer) independent of subscript index values. Likewise,
110 whether a subscript is indexed does not depend on previous indices (but
111 may depend on previous subscript labels).
113 A syntax description in ABNF (RFC 5234) follows. Note that
114 @code{%x30-39} denotes the range of decimal digits. Diagnostic output
115 lines are expected to match the @code{line} production.
119 HEXDIG = %x30-39 / %x61-6f ; lowercase a-f only
120 ALPHA = %x41-5a / %x61-7a / %x7f ; letters and underscore
121 ALPHA-NUMERIC = ALPHA / %x30-39 / "_"
124 ; Numbers are always hexadecimal and use a 0x prefix.
125 hex-value-prefix = %x30 %x78
126 hex-value = hex-value-prefix 1*HEXDIG
128 ; Strings use octal escape sequences and \\, \".
129 string-char = %x20-21 / %x23-5c / %x5d-7e ; printable but not "\
130 string-quoted-octal = %x30-33 2*2%x30-37
131 string-quoted = "\" ("\" / DQUOTE / string-quoted-octal)
132 string-value = DQUOTE *(string-char / string-quoted) DQUOTE
134 value = hex-value / string-value
136 label = ALPHA *ALPHA-NUMERIC
137 index = "[" hex-value "]"
138 subscript = label [index]
140 line = subscript *("." subscript) "=" value
143 @node Dynamic Linker Diagnostics Values
144 @subsubsection Dynamic Linker Diagnostics Values
146 As mentioned above, the set of diagnostics may change between
147 @theglibc{} releases. Nevertheless, the following table documents a few
148 common diagnostic items. All numbers are in hexadecimal, with a
152 @item dl_dst_lib=@var{string}
153 The @code{$LIB} dynamic string token expands to @var{string}.
155 @cindex HWCAP (diagnostics)
156 @item dl_hwcap=@var{integer}
157 @itemx dl_hwcap2=@var{integer}
158 The HWCAP and HWCAP2 values, as returned for @code{getauxval}, and as
159 used in other places depending on the architecture.
161 @cindex page size (diagnostics)
162 @item dl_pagesize=@var{integer}
163 The system page size is @var{integer} bytes.
165 @item dl_platform=@var{string}
166 The @code{$PLATFORM} dynamic string token expands to @var{string}.
168 @item dso.libc=@var{string}
169 This is the soname of the shared @code{libc} object that is part of
170 @theglibc{}. On most architectures, this is @code{libc.so.6}.
172 @item env[@var{index}]=@var{string}
173 @itemx env_filtered[@var{index}]=@var{string}
174 An environment variable from the process environment. The integer
175 @var{index} is the array index in the environment array. Variables
176 under @code{env} include the variable value after the @samp{=} (assuming
177 that it was present), variables under @code{env_filtered} do not.
179 @item path.prefix=@var{string}
180 This indicates that @theglibc{} was configured using
181 @samp{--prefix=@var{string}}.
183 @item path.sysconfdir=@var{string}
184 @Theglibc{} was configured (perhaps implicitly) with
185 @samp{--sysconfdir=@var{string}} (typically @code{/etc}).
187 @item path.system_dirs[@var{index}]=@var{string}
188 These items list the elements of the built-in array that describes the
189 default library search path. The value @var{string} is a directory file
190 name with a trailing @samp{/}.
192 @item path.rtld=@var{string}
193 This string indicates the application binary interface (ABI) file name
194 of the run-time dynamic linker.
196 @item version.release="stable"
197 @itemx version.release="development"
198 The value @code{"stable"} indicates that this build of @theglibc{} is
199 from a release branch. Releases labeled as @code{"development"} are
200 unreleased development versions.
202 @cindex version (diagnostics)
203 @item version.version="@var{major}.@var{minor}"
204 @itemx version.version="@var{major}.@var{minor}.9000"
205 @Theglibc{} version. Development releases end in @samp{.9000}.
207 @cindex auxiliary vector (diagnostics)
208 @item auxv[@var{index}].a_type=@var{type}
209 @itemx auxv[@var{index}].a_val=@var{integer}
210 @itemx auxv[@var{index}].a_val_string=@var{string}
211 An entry in the auxiliary vector (specific to Linux). The values
212 @var{type} (an integer) and @var{integer} correspond to the members of
213 @code{struct auxv}. If the value is a string, @code{a_val_string} is
214 used instead of @code{a_val}, so that values have consistent types.
216 The @code{AT_HWCAP} and @code{AT_HWCAP2} values in this output do not
217 reflect adjustment by @theglibc{}.
219 @item uname.sysname=@var{string}
220 @itemx uname.nodename=@var{string}
221 @itemx uname.release=@var{string}
222 @itemx uname.version=@var{string}
223 @itemx uname.machine=@var{string}
224 @itemx uname.domain=@var{string}
225 These Linux-specific items show the values of @code{struct utsname}, as
226 reported by the @code{uname} function. @xref{Platform Type}.
228 @item aarch64.cpu_features.@dots{}
229 These items are specific to the AArch64 architectures. They report data
230 @theglibc{} uses to activate conditionally supported features such as
231 BTI and MTE, and to select alternative function implementations.
233 @item aarch64.processor[@var{index}].@dots{}
234 These are additional items for the AArch64 architecture and are
237 @item aarch64.processor[@var{index}].requested=@var{kernel-cpu}
238 The kernel is told to run the subsequent probing on the CPU numbered
239 @var{kernel-cpu}. The values @var{kernel-cpu} and @var{index} can be
240 distinct if there are gaps in the process CPU affinity mask. This line
241 is not included if CPU affinity mask information is not available.
243 @item aarch64.processor[@var{index}].observed=@var{kernel-cpu}
244 This line reports the kernel CPU number @var{kernel-cpu} on which the
245 probing code initially ran. If the CPU number cannot be obtained,
246 this line is not printed.
248 @item aarch64.processor[@var{index}].observed_node=@var{node}
249 This reports the observed NUMA node number, as reported by the
250 @code{getcpu} system call. If this information cannot be obtained, this
253 @item aarch64.processor[@var{index}].midr_el1=@var{value}
254 The value of the @code{midr_el1} system register on the processor
255 @var{index}. This line is only printed if the kernel indicates that
256 this system register is supported.
258 @item aarch64.processor[@var{index}].dczid_el0=@var{value}
259 The value of the @code{dczid_el0} system register on the processor
262 @cindex CPUID (diagnostics)
263 @item x86.cpu_features.@dots{}
264 These items are specific to the i386 and x86-64 architectures. They
265 reflect supported CPU features and information on cache geometry, mostly
266 collected using the CPUID instruction.
268 @item x86.processor[@var{index}].@dots{}
269 These are additional items for the i386 and x86-64 architectures, as
270 described below. They mostly contain raw data from the CPUID
271 instruction. The probes are performed for each active CPU for the
272 @code{ld.so} process, and data for different probed CPUs receives a
273 uniqe @var{index} value. Some CPUID data is expected to differ from CPU
274 core to CPU core. In some cases, CPUs are not correctly initialized and
275 indicate the presence of different feature sets.
277 @item x86.processor[@var{index}].requested=@var{kernel-cpu}
278 The kernel is told to run the subsequent probing on the CPU numbered
279 @var{kernel-cpu}. The values @var{kernel-cpu} and @var{index} can be
280 distinct if there are gaps in the process CPU affinity mask. This line
281 is not included if CPU affinity mask information is not available.
283 @item x86.processor[@var{index}].observed=@var{kernel-cpu}
284 This line reports the kernel CPU number @var{kernel-cpu} on which the
285 probing code initially ran. If the CPU number cannot be obtained,
286 this line is not printed.
288 @item x86.processor[@var{index}].observed_node=@var{node}
289 This reports the observed NUMA node number, as reported by the
290 @code{getcpu} system call. If this information cannot be obtained, this
293 @item x86.processor[@var{index}].cpuid_leaves=@var{count}
294 This line indicates that @var{count} distinct CPUID leaves were
295 encountered. (This reflects internal @code{ld.so} storage space, it
296 does not directly correspond to @code{CPUID} enumeration ranges.)
298 @item x86.processor[@var{index}].ecx_limit=@var{value}
299 The CPUID data extraction code uses a brute-force approach to enumerate
300 subleaves (see the @samp{.subleaf_eax} lines below). The last
301 @code{%rcx} value used in a CPUID query on this probed CPU was
304 @item x86.processor[@var{index}].cpuid.eax[@var{query_eax}].eax=@var{eax}
305 @itemx x86.processor[@var{index}].cpuid.eax[@var{query_eax}].ebx=@var{ebx}
306 @itemx x86.processor[@var{index}].cpuid.eax[@var{query_eax}].ecx=@var{ecx}
307 @itemx x86.processor[@var{index}].cpuid.eax[@var{query_eax}].edx=@var{edx}
308 These lines report the register contents after executing the CPUID
309 instruction with @samp{%rax == @var{query_eax}} and @samp{%rcx == 0} (a
310 @dfn{leaf}). For the first probed CPU (with a zero @var{index}), only
311 leaves with non-zero register contents are reported. For subsequent
312 CPUs, only leaves whose register contents differs from the previously
313 probed CPUs (with @var{index} one less) are reported.
315 Basic and extended leaves are reported using the same syntax. This
316 means there is a large jump in @var{query_eax} for the first reported
319 @item x86.processor[@var{index}].cpuid.subleaf_eax[@var{query_eax}].ecx[@var{query_ecx}].eax=@var{eax}
320 @itemx x86.processor[@var{index}].cpuid.subleaf_eax[@var{query_eax}].ecx[@var{query_ecx}].ebx=@var{ebx}
321 @itemx x86.processor[@var{index}].cpuid.subleaf_eax[@var{query_eax}].ecx[@var{query_ecx}].ecx=@var{ecx}
322 @itemx x86.processor[@var{index}].cpuid.subleaf_eax[@var{query_eax}].ecx[@var{query_ecx}].edx=@var{edx}
323 This is similar to the leaves above, but for a @dfn{subleaf}. For
324 subleaves, the CPUID instruction is executed with @samp{%rax ==
325 @var{query_eax}} and @samp{%rcx == @var{query_ecx}}, so the result
326 depends on both register values. The same rules about filtering zero
327 and identical results apply.
329 @item x86.processor[@var{index}].cpuid.subleaf_eax[@var{query_eax}].ecx[@var{query_ecx}].until_ecx=@var{ecx_limit}
330 Some CPUID results are the same regardless the @var{query_ecx} value.
331 If this situation is detected, a line with the @samp{.until_ecx}
332 selector ins included, and this indicates that the CPUID register
333 contents is the same for @code{%rcx} values between @var{query_ecx}
334 and @var{ecx_limit} (inclusive).
336 @item x86.processor[@var{index}].cpuid.subleaf_eax[@var{query_eax}].ecx[@var{query_ecx}].ecx_query_mask=0xff
337 This line indicates that in an @samp{.until_ecx} range, the CPUID
338 instruction preserved the lowested 8 bits of the input @code{%rcx} in
339 the output @code{%rcx} registers. Otherwise, the subleaves in the range
340 have identical values. This special treatment is necessary to report
341 compact range information in case such copying occurs (because the
342 subleaves would otherwise be all different).
344 @item x86.processor[@var{index}].xgetbv.ecx[@var{query_ecx}]=@var{result}
345 This line shows the 64-bit @var{result} value in the @code{%rdx:%rax}
346 register pair after executing the XGETBV instruction with @code{%rcx}
347 set to @var{query_ecx}. Zero values and values matching the previously
348 probed CPU are omitted. Nothing is printed if the system does not
349 support the XGETBV instruction.
352 @node Dynamic Linker Introspection
353 @section Dynamic Linker Introspection
355 @Theglibc{} provides various functions for querying information from the
358 @deftypefun {int} dlinfo (void *@var{handle}, int @var{request}, void *@var{arg})
359 @safety{@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
360 @standards{GNU, dlfcn.h}
361 This function returns information about @var{handle} in the memory
362 location @var{arg}, based on @var{request}. The @var{handle} argument
363 must be a pointer returned by @code{dlopen} or @code{dlmopen}; it must
364 not have been closed by @code{dlclose}.
366 On success, @code{dlinfo} returns 0 for most request types; exceptions
367 are noted below. If there is an error, the function returns @math{-1},
368 and @code{dlerror} can be used to obtain a corresponding error message.
370 The following operations are defined for use with @var{request}:
373 @item RTLD_DI_LINKMAP
374 The corresponding @code{struct link_map} pointer for @var{handle} is
375 written to @code{*@var{arg}}. The @var{arg} argument must be the
376 address of an object of type @code{struct link_map *}.
379 The namespace identifier of @var{handle} is written to
380 @code{*@var{arg}}. The @var{arg} argument must be the address of an
381 object of type @code{Lmid_t}.
384 The value of the @code{$ORIGIN} dynamic string token for @var{handle} is
385 written to the character array starting at @var{arg} as a
386 null-terminated string.
388 This request type should not be used because it is prone to buffer
391 @item RTLD_DI_SERINFO
392 @itemx RTLD_DI_SERINFOSIZE
393 These requests can be used to obtain search path information for
394 @var{handle}. For both requests, @var{arg} must point to a
395 @code{Dl_serinfo} object. The @code{RTLD_DI_SERINFOSIZE} request must
396 be made first; it updates the @code{dls_size} and @code{dls_cnt} members
397 of the @code{Dl_serinfo} object. The caller should then allocate memory
398 to store at least @code{dls_size} bytes and pass that buffer to a
399 @code{RTLD_DI_SERINFO} request. This second request fills the
400 @code{dls_serpath} array. The number of array elements was returned in
401 the @code{dls_cnt} member in the initial @code{RTLD_DI_SERINFOSIZE}
402 request. The caller is responsible for freeing the allocated buffer.
404 This interface is prone to buffer overflows in multi-threaded processes
405 because the required size can change between the
406 @code{RTLD_DI_SERINFOSIZE} and @code{RTLD_DI_SERINFO} requests.
408 @item RTLD_DI_TLS_DATA
409 This request writes the address of the TLS block (in the current thread)
410 for the shared object identified by @var{handle} to @code{*@var{arg}}.
411 The argument @var{arg} must be the address of an object of type
412 @code{void *}. A null pointer is written if the object does not have
413 any associated TLS block.
415 @item RTLD_DI_TLS_MODID
416 This request writes the TLS module ID for the shared object @var{handle}
417 to @code{*@var{arg}}. The argument @var{arg} must be the address of an
418 object of type @code{size_t}. The module ID is zero if the object
419 does not have an associated TLS block.
422 This request writes the address of the program header array to
423 @code{*@var{arg}}. The argument @var{arg} must be the address of an
424 object of type @code{const ElfW(Phdr) *} (that is,
425 @code{const Elf32_Phdr *} or @code{const Elf64_Phdr *}, as appropriate
426 for the current architecture). For this request, the value returned by
427 @code{dlinfo} is the number of program headers in the program header
431 The @code{dlinfo} function is a GNU extension.
434 The remainder of this section documents the @code{_dl_find_object}
435 function and supporting types and constants.
437 @deftp {Data Type} {struct dl_find_object}
438 @standards{GNU, dlfcn.h}
439 This structure contains information about a main program or loaded
440 object. The @code{_dl_find_object} function uses it to return
441 result data to the caller.
444 @item unsigned long long int dlfo_flags
445 Currently unused and always 0.
447 @item void *dlfo_map_start
448 The start address of the inspected mapping. This information comes from
449 the program header, so it follows its convention, and the address is not
450 necessarily page-aligned.
452 @item void *dlfo_map_end
453 The end address of the mapping.
455 @item struct link_map *dlfo_link_map
456 This member contains a pointer to the link map of the object.
458 @item void *dlfo_eh_frame
459 This member contains a pointer to the exception handling data of the
460 object. See @code{DLFO_EH_SEGMENT_TYPE} below.
464 This structure is a GNU extension.
467 @deftypevr Macro int DLFO_STRUCT_HAS_EH_DBASE
468 @standards{GNU, dlfcn.h}
469 On most targets, this macro is defined as @code{0}. If it is defined to
470 @code{1}, @code{struct dl_find_object} contains an additional member
471 @code{dlfo_eh_dbase} of type @code{void *}. It is the base address for
472 @code{DW_EH_PE_datarel} DWARF encodings to this location.
474 This macro is a GNU extension.
477 @deftypevr Macro int DLFO_STRUCT_HAS_EH_COUNT
478 @standards{GNU, dlfcn.h}
479 On most targets, this macro is defined as @code{0}. If it is defined to
480 @code{1}, @code{struct dl_find_object} contains an additional member
481 @code{dlfo_eh_count} of type @code{int}. It is the number of exception
482 handling entries in the EH frame segment identified by the
483 @code{dlfo_eh_frame} member.
485 This macro is a GNU extension.
488 @deftypevr Macro int DLFO_EH_SEGMENT_TYPE
489 @standards{GNU, dlfcn.h}
490 On targets using DWARF-based exception unwinding, this macro expands to
491 @code{PT_GNU_EH_FRAME}. This indicates that @code{dlfo_eh_frame} in
492 @code{struct dl_find_object} points to the @code{PT_GNU_EH_FRAME}
493 segment of the object. On targets that use other unwinding formats, the
494 macro expands to the program header type for the unwinding data.
496 This macro is a GNU extension.
499 @deftypefun {int} _dl_find_object (void *@var{address}, struct dl_find_object *@var{result})
500 @standards{GNU, dlfcn.h}
501 @safety{@mtsafe{}@assafe{}@acsafe{}}
502 On success, this function returns 0 and writes about the object
503 surrounding the address to @code{*@var{result}}. On failure, -1 is
506 The @var{address} can be a code address or data address. On
507 architectures using function descriptors, no attempt is made to decode
508 the function descriptor. Depending on how these descriptors are
509 implemented, @code{_dl_find_object} may return the object that defines
510 the function descriptor (and not the object that contains the code
511 implementing the function), or fail to find any object at all.
513 On success @var{address} is greater than or equal to
514 @code{@var{result}->dlfo_map_start} and less than
515 @code{@var{result}->dlfo_map_end}, that is, the supplied code address is
516 located within the reported mapping.
518 This function returns a pointer to the unwinding information for the
519 object that contains the program code @var{address} in
520 @code{@var{result}->dlfo_eh_frame}. If the platform uses DWARF
521 unwinding information, this is the in-memory address of the
522 @code{PT_GNU_EH_FRAME} segment. See @code{DLFO_EH_SEGMENT_TYPE} above.
523 In case @var{address} resides in an object that lacks unwinding information,
524 the function still returns 0, but sets @code{@var{result}->dlfo_eh_frame}
527 @code{_dl_find_object} itself is thread-safe. However, if the
528 application invokes @code{dlclose} for the object that contains
529 @var{address} concurrently with @code{_dl_find_object} or after the call
530 returns, accessing the unwinding data for that object or the link map
531 (through @code{@var{result}->dlfo_link_map}) is not safe. Therefore, the
532 application needs to ensure by other means (e.g., by convention) that
533 @var{address} remains a valid code address while the unwinding
534 information is processed.
536 This function is a GNU extension.
539 @node Dynamic Linker Hardening
540 @section Avoiding Unexpected Issues With Dynamic Linking
542 This section details recommendations for increasing application
543 robustness, by avoiding potential issues related to dynamic linking.
544 The recommendations have two main aims: reduce the involvement of the
545 dynamic linker in application execution after process startup, and
546 restrict the application to a dynamic linker feature set whose behavior
547 is more easily understood.
549 Key aspects of limiting dynamic linker usage after startup are: no use
550 of the @code{dlopen} function, disabling lazy binding, and using the
551 static TLS model. More easily understood dynamic linker behavior
552 requires avoiding name conflicts (symbols and sonames) and highly
553 customizable features like the audit subsystem.
555 Note that while these steps can be considered a form of application
556 hardening, they do not guard against potential harm from accidental or
557 deliberate loading of untrusted or malicious code. There is only
558 limited overlap with traditional security hardening for applications
559 running on GNU systems.
561 @subsection Restricted Dynamic Linker Features
563 Avoiding certain dynamic linker features can increase predictability of
564 applications and reduce the risk of running into dynamic linker defects.
568 Do not use the functions @code{dlopen}, @code{dlmopen}, or
569 @code{dlclose}. Dynamic loading and unloading of shared objects
570 introduces substantial complications related to symbol and thread-local
571 storage (TLS) management.
574 Without the @code{dlopen} function, @code{dlsym} and @code{dlvsym}
575 cannot be used with shared object handles. Minimizing the use of both
576 functions is recommended. If they have to be used, only the
577 @code{RTLD_DEFAULT} pseudo-handle should be used.
580 Use the local-exec or initial-exec TLS models. If @code{dlopen} is not
581 used, there are no compatibility concerns for initial-exec TLS. This
582 TLS model avoids most of the complexity around TLS access. In
583 particular, there are no TLS-related run-time memory allocations after
584 process or thread start.
586 If shared objects are expected to be used more generally, outside the
587 hardened, feature-restricted context, lack of compatibility between
588 @code{dlopen} and initial-exec TLS could be a concern. In that case,
589 the second-best alternative is to use global-dynamic TLS with GNU2 TLS
590 descriptors, for targets that fully implement them, including the fast
591 path for access to TLS variables defined in the initially loaded set of
592 objects. Like initial-exec TLS, this avoids memory allocations after
593 thread creation, but only if the @code{dlopen} function is not used.
596 Do not use lazy binding. Lazy binding may require run-time memory
597 allocation, is not async-signal-safe, and introduces considerable
601 Make dependencies on shared objects explicit. Do not assume that
602 certain libraries (such as @code{libc.so.6}) are always loaded.
603 Specifically, if a main program or shared object references a symbol,
604 create an ELF @code{DT_NEEDED} dependency on that shared object, or on
605 another shared object that is documented (or otherwise guaranteed) to
606 have the required explicit dependency. Referencing a symbol without a
607 matching link dependency results in underlinking, and underlinked
608 objects cannot always be loaded correctly: Initialization of objects may
609 not happen in the required order.
612 Do not create dependency loops between shared objects (@code{libA.so.1}
613 depending on @code{libB.so.1} depending on @code{libC.so.1} depending on
614 @code{libA.so.1}). @Theglibc{} has to initialize one of the objects in
615 the cycle first, and the choice of that object is arbitrary and can
616 change over time. The object which is initialized first (and other
617 objects involved in the cycle) may not run correctly because not all of
618 its dependencies have been initialized.
620 Underlinking (see above) can hide the presence of cycles.
623 Limit the creation of indirect function (IFUNC) resolvers. These
624 resolvers run during relocation processing, when @theglibc{} is not in
625 a fully consistent state. If you write your own IFUNC resolvers, do
626 not depend on external data or function references in those resolvers.
629 Do not use the audit functionality (@code{LD_AUDIT}, @code{DT_AUDIT},
630 @code{DT_DEPAUDIT}). Its callback and hooking capabilities introduce a
631 lot of complexity and subtly alter dynamic linker behavior in corner
632 cases even if the audit module is inactive.
635 Do not use symbol interposition. Without symbol interposition, the
636 exact order in which shared objects are searched are less relevant.
638 Exceptions to this rule are copy relocations (see the next item), and
639 vague linkage, as used by the C++ implementation (see below).
642 One potential source of symbol interposition is a combination of static
643 and dynamic linking, namely linking a static archive into multiple
644 dynamic shared objects. For such scenarios, the static library should
645 be converted into its own dynamic shared object.
647 A different approach to this situation uses hidden visibility for
648 symbols in the static library, but this can cause problems if the
649 library does not expect that multiple copies of its code coexist within
650 the same process, with no or partial sharing of state.
653 If you use shared objects that are linked with @option{-Wl,-Bsymbolic}
654 (or equivalent) or use protected visibility, the code for the main
655 program must be built as @option{-fpic} or @option{-fPIC} to avoid
656 creating copy relocations (and the main program must not use copy
657 relocations for other reasons). Using @option{-fpie} or @option{-fPIE}
658 is not an alternative to PIC code in this context.
661 Be careful about explicit section annotations. Make sure that the
662 target section matches the properties of the declared entity (e.g., no
663 writable objects in @code{.text}).
666 Ensure that all assembler or object input files have the recommended
667 security markup, particularly for non-executable stack.
670 Avoid using non-default linker flags and features. In particular, do
671 not use the @code{DT_PREINIT_ARRAY} dynamic tag, and do not flag
672 objects as @code{DF_1_INITFIRST}. Do not change the default linker
673 script of BFD ld. Do not override ABI defaults, such as the dynamic
674 linker path (with @option{--dynamic-linker}).
677 Some features of @theglibc{} indirectly depend on run-time code loading
678 and @code{dlopen}. Use @code{iconv_open} with built-in converters only
679 (such as @code{UTF-8}). Do not use NSS functionality such as
680 @code{getaddrinfo} or @code{getpwuid_r} unless the system is configured
681 for built-in NSS service modules only (see below).
684 Several considerations apply to ELF constructors and destructors.
688 The dynamic linker does not take constructor and destructor priorities
689 into account when determining their execution order. Priorities are
690 only used by the link editor for ordering execution within a
691 completely linked object. If a dynamic shared object needs to be
692 initialized before another object, this can be expressed with a
693 @code{DT_NEEDED} dependency on the object that needs to be initialized
697 The recommendations to avoid cyclic dependencies and symbol
698 interposition make it less likely that ELF objects are accessed before
699 their ELF constructors have run. However, using @code{dlsym} and
700 @code{dlvsym}, it is still possible to access uninitialized facilities
701 even with these restrictions in place. (Of course, access to
702 uninitialized functionality is also possible within a single shared
703 object or the main executable, without resorting to explicit symbol
704 lookup.) Consider using dynamic, on-demand initialization instead. To
705 deal with access after de-initialization, it may be necessary to
706 implement special cases for that scenario, potentially with degraded
710 Be aware that when ELF destructors are executed, it is possible to
711 reference already-deconstructed shared objects. This can happen even in
712 the absence of @code{dlsym} and @code{dlvsym} function calls, for
713 example if client code using a shared object has registered callbacks or
714 objects with another shared object. The ELF destructor for the client
715 code is executed before the ELF destructor for the shared objects that
716 it uses, based on the expected dependency order.
719 If @code{dlopen} and @code{dlmopen} are not used, @code{DT_NEEDED}
720 dependency information is complete, and lazy binding is disabled, the
721 execution order of ELF destructors is expected to be the reverse of the
722 ELF constructor order. However, two separate dependency sort operations
723 still occur. Even though the listed preconditions should ensure that
724 both sorts produce the same ordering, it is recommended not to depend on
725 the destructor order being the reverse of the constructor order.
728 The following items provide C++-specific guidance for preparing
729 applications. If another programming language is used and it uses these
730 toolchain features targeted at C++ to implement some language
731 constructs, these restrictions and recommendations still apply in
736 C++ inline functions, templates, and other constructs may need to be
737 duplicated into multiple shared objects using vague linkage, resulting
738 in symbol interposition. This type of symbol interposition is
739 unproblematic, as long as the C++ one definition rule (ODR) is followed,
740 and all definitions in different translation units are equivalent
741 according to the language C++ rules.
744 Be aware that under C++ language rules, it is unspecified whether
745 evaluating a string literal results in the same address for each
746 evaluation. This also applies to anonymous objects of static storage
747 duration that GCC creates, for example to implement the compound
748 literals C++ extension. As a result, comparing pointers to such
749 objects, or using them directly as hash table keys, may give unexpected
752 By default, variables of block scope of static storage have consistent
753 addresses across different translation units, even if defined in
754 functions that use vague linkage.
757 Special care is needed if a C++ project uses symbol visibility or
758 symbol version management (for example, the GCC @samp{visibility}
759 attribute, the GCC @option{-fvisibility} option, or a linker version
760 script with the linker option @option{--version-script}). It is
761 necessary to ensure that the symbol management remains consistent with
762 how the symbols are used. Some C++ constructs are implemented with
763 the help of ancillary symbols, which can make complicated to achieve
764 consistency. For example, an inline function that is always inlined
765 into its callers has no symbol footprint for the function itself, but
766 if the function contains a variable of static storage duration, this
767 variable may result in the creation of one or more global symbols.
768 For correctness, such symbols must be visible and bound to the same
769 object in all other places where the inline function may be called.
770 This requirement is not met if the symbol visibility is set to hidden,
771 or if symbols are assigned a textually different symbol version
772 (effectively creating two distinct symbols).
774 Due to the complex interaction between ELF symbol management and C++
775 symbol generation, it is recommended to use C++ language features for
776 symbol management, in particular inline namespaces.
779 The toolchain and dynamic linker have multiple mechanisms that bypass
780 the usual symbol binding procedures. This means that the C++ one
781 definition rule (ODR) still holds even if certain symbol-based isolation
782 mechanisms are used, and object addresses are not shared across
783 translation units with incompatible type definitions.
785 This does not matter if the original (language-independent) advice
786 regarding symbol interposition is followed. However, as the advice may
787 be difficult to implement for C++ applications, it is recommended to
788 avoid ODR violations across the entire process image. Inline namespaces
789 can be helpful in this context because they can be used to create
790 distinct ELF symbols while maintaining source code compatibility at the
794 Be aware that as a special case of interposed symbols, symbols with the
795 @code{STB_GNU_UNIQUE} binding type do not follow the usual ELF symbol
796 namespace isolation rules: such symbols bind across @code{RTLD_LOCAL}
797 boundaries. Furthermore, symbol versioning is ignored for such symbols;
798 they are bound by symbol name only. All their definitions and uses must
799 therefore be compatible. Hidden visibility still prevents the creation
800 of @code{STB_GNU_UNIQUE} symbols and can achieve isolation of
801 incompatible definitions.
804 C++ constructor priorities only affect constructor ordering within one
805 shared object. Global constructor order across shared objects is
806 consistent with ELF dependency ordering if there are no ELF dependency
810 C++ exception handling and run-time type information (RTTI), as
811 implemented in the GNU toolchain, is not address-significant, and
812 therefore is not affected by the symbol binding behaviour of the dynamic
813 linker. This means that types of the same fully-qualified name (in
814 non-anonymous namespaces) are always considered the same from an
815 exception-handling or RTTI perspective. This is true even if the type
816 information object or vtable has hidden symbol visibility, or the
817 corresponding symbols are versioned under different symbol versions, or
818 the symbols are not bound to the same objects due to the use of
819 @code{RTLD_LOCAL} or @code{dlmopen}.
821 This can cause issues in applications that contain multiple incompatible
822 definitions of the same type. Inline namespaces can be used to create
823 distinct symbols at the ELF layer, avoiding this type of issue.
826 C++ exception handling across multiple @code{dlmopen} namespaces may
827 not work, particular with the unwinder in GCC versions before 12.
828 Current toolchain versions are able to process unwinding tables across
829 @code{dlmopen} boundaries. However, note that type comparison is
830 name-based, not address-based (see the previous item), so exception
831 types may still be matched in unexpected ways. An important special
832 case of exception handling, invoking destructors for variables of block
833 scope, is not impacted by this RTTI type-sharing. Likewise, regular
834 virtual member function dispatch for objects is unaffected (but still
835 requires that the type definitions match in all directly involved
838 Once more, inline namespaces can be used to create distinct ELF symbols
842 Although the C++ standard requires that destructors for global objects
843 run in the opposite order of their constructors, the Itanium C++ ABI
844 requires a different destruction order in some cases. As a result, do
845 not depend on the precise destructor invocation order in applications
846 that use @code{dlclose}.
849 Registering destructors for later invocation allocates memory and may
850 silently fail if insufficient memory is available. As a result, the
851 destructor is never invoked. This applies to all forms of destructor
852 registration, with the exception of thread-local variables (see the next
853 item). To avoid this issue, ensure that such objects merely have
854 trivial destructors, avoiding the need for registration, and deallocate
855 resources using a different mechanism (for example, from an ELF
859 A similar issue exists for @code{thread_local} variables with thread
860 storage duration of types that have non-trivial destructors. However,
861 in this case, memory allocation failure during registration leads to
862 process termination. If process termination is not acceptable, use
863 @code{thread_local} variables with trivial destructors only.
864 Functions for per-thread cleanup can be registered using
865 @code{pthread_key_create} (globally for all threads) and activated
866 using @code{pthread_setspecific} (on each thread). Note that a
867 @code{pthread_key_create} call may still fail (and
868 @code{pthread_create} keys are a limited resource in @theglibc{}), but
869 this failure can be handled without terminating the process.
872 @subsection Producing Matching Binaries
874 This subsection recommends tools and build flags for producing
875 applications that meet the recommendations of the previous subsection.
879 Use BFD ld (@command{bfd.ld}) from GNU binutils to produce binaries,
880 invoked through a compiler driver such as @command{gcc}. The version
881 should be not too far ahead of what was current when the version of
882 @theglibc{} was first released.
885 Do not use a binutils release that is older than the one used to build
889 Compile with @option{-ftls-model=initial-exec} to force the initial-exec
893 Link with @option{-Wl,-z,now} to disable lazy binding.
896 Link with @option{-Wl,-z,relro} to enable RELRO (which is the default on
900 Specify all direct shared objects dependencies using @option{-l} options
901 to avoid underlinking. Rely on @code{.so} files (which can be linker
902 scripts) and searching with the @option{-l} option. Do not specify the
903 file names of shared objects on the linker command line.
906 Consider using @option{-Wl,-z,defs} to treat underlinking as an error
910 When creating a shared object (linked with @option{-shared}), use
911 @option{-Wl,-soname,lib@dots{}} to set a soname that matches the final
912 installed name of the file.
915 Do not use the @option{-rpath} linker option. (As explained below, all
916 required shared objects should be installed into the default search
920 Use @option{-Wl,--error-rwx-segments} and @option{-Wl,--error-execstack} to
921 instruct the link editor to fail the link if the resulting final object
922 would have read-write-execute segments or an executable stack. Such
923 issues usually indicate that the input files are not marked up
927 Ensure that for each @code{LOAD} segment in the ELF program header, file
928 offsets, memory sizes, and load addresses are multiples of the largest
929 page size supported at run time. Similarly, the start address and size
930 of the @code{GNU_RELRO} range should be multiples of the page size.
932 Avoid creating gaps between @code{LOAD} segments. The difference
933 between the load addresses of two subsequent @code{LOAD} segments should
934 be the size of the first @code{LOAD} segment. (This may require linking
935 with @option{-Wl,-z,noseparate-code}.)
937 This may not be possible to achieve with the currently available link
941 If the multiple-of-page-size criterion for the @code{GNU_RELRO} region
942 cannot be achieved, ensure that the process memory image right before
943 the start of the region does not contain executable or writable memory.
944 @c https://sourceware.org/pipermail/libc-alpha/2022-May/138638.html
947 @subsection Checking Binaries
949 In some cases, if the previous recommendations are not followed, this
950 can be determined from the produced binaries. This section contains
951 suggestions for verifying aspects of these binaries.
955 To detect underlinking, examine the dynamic symbol table, for example
956 using @samp{readelf -sDW}. If the symbol is defined in a shared object
957 that uses symbol versioning, it must carry a symbol version, as in
958 @samp{pthread_kill@@GLIBC_2.34}.
961 Examine the dynamic segment with @samp{readelf -dW} to check that all
962 the required @code{NEEDED} entries are present. (It is not necessary to
963 list indirect dependencies if these dependencies are guaranteed to
964 remain during the evolution of the explicitly listed direct
968 The @code{NEEDED} entries should not contain full path names including
969 slashes, only @code{sonames}.
972 For a further consistency check, collect all shared objects referenced
973 via @code{NEEDED} entries in dynamic segments, transitively, starting at
974 the main program. Then determine their dynamic symbol tables (using
975 @samp{readelf -sDW}, for example). Ideally, every symbol should be
976 defined at most once, so that symbol interposition does not happen.
978 If there are interposed data symbols, check if the single interposing
979 definition is in the main program. In this case, there must be a copy
980 relocation for it. (This only applies to targets with copy relocations.)
982 Function symbols should only be interposed in C++ applications, to
983 implement vague linkage. (See the discussion in the C++ recommendations
987 Using the previously collected @code{NEEDED} entries, check that the
988 dependency graph does not contain any cycles.
991 The dynamic segment should also mention @code{BIND_NOW} on the
992 @code{FLAGS} line or @code{NOW} on the @code{FLAGS_1} line (one is
996 Ensure that only static TLS relocations (thread-pointer relative offset
997 locations) are used, for example @code{R_AARCH64_TLS_TPREL} and
998 @code{X86_64_TPOFF64}. As the second-best option, and only if
999 compatibility with non-hardened applications using @code{dlopen} is
1000 needed, GNU2 TLS descriptor relocations can be used (for example,
1001 @code{R_AARCH64_TLSDESC} or @code{R_X86_64_TLSDESC}).
1004 There should not be references to the traditional TLS function symbols
1005 @code{__tls_get_addr}, @code{__tls_get_offset},
1006 @code{__tls_get_addr_opt} in the dynamic symbol table (in the
1007 @samp{readelf -sDW} output). Supporting global dynamic TLS relocations
1008 (such as @code{R_AARCH64_TLS_DTPMOD}, @code{R_AARCH64_TLS_DTPREL},
1009 @code{R_X86_64_DTPMOD64}, @code{R_X86_64_DTPOFF64}) should not be used,
1013 Likewise, the functions @code{dlopen}, @code{dlmopen}, @code{dlclose}
1014 should not be referenced from the dynamic symbol table.
1017 For shared objects, there should be a @code{SONAME} entry that matches
1018 the file name (the base name, i.e., the part after the slash). The
1019 @code{SONAME} string must not contain a slash @samp{/}.
1022 For all objects, the dynamic segment (as shown by @samp{readelf -dW})
1023 should not contain @code{RPATH} or @code{RUNPATH} entries.
1026 Likewise, the dynamic segment should not show any @code{AUDIT},
1027 @code{DEPAUDIT}, @code{AUXILIARY}, @code{FILTER}, or
1028 @code{PREINIT_ARRAY} tags.
1031 If the dynamic segment contains a (deprecated) @code{HASH} tag, it
1032 must also contain a @code{GNU_HASH} tag.
1035 The @code{INITFIRST} flag (undeer @code{FLAGS_1}) should not be used.
1038 The program header must not have @code{LOAD} segments that are writable
1039 and executable at the same time.
1042 All produced objects should have a @code{GNU_STACK} program header that
1043 is not marked as executable. (However, on some newer targets, a
1044 non-executable stack is the default, so the @code{GNU_STACK} program
1045 header is not required.)
1048 @subsection Run-time Considerations
1050 In addition to preparing program binaries in a recommended fashion, the
1051 run-time environment should be set up in such a way that problematic
1052 dynamic linker features are not used.
1056 Install shared objects using their sonames in a default search path
1057 directory (usually @file{/usr/lib64}). Do not use symbolic links.
1058 @c This is currently not standard practice.
1061 The default search path must not contain objects with duplicate file
1065 Do not use environment variables (@code{LD_@dots{}} variables such as
1066 @code{LD_PRELOAD} or @code{LD_LIBRARY_PATH}, or @code{GLIBC_TUNABLES})
1067 to change default dynamic linker behavior.
1070 Do not install shared objects in non-default locations. (Such locations
1071 are listed explicitly in the configuration file for @command{ldconfig},
1072 usually @file{/etc/ld.so.conf}, or in files included from there.)
1075 In relation to the previous item, do not install any objects it
1076 @code{glibc-hwcaps} subdirectories.
1079 Do not configure dynamically-loaded NSS service modules, to avoid
1080 accidental internal use of the @code{dlopen} facility. The @code{files}
1081 and @code{dns} modules are built in and do not rely on @code{dlopen}.
1084 Do not truncate and overwrite files containing programs and shared
1085 objects in place, while they are used. Instead, write the new version
1086 to a different path and use @code{rename} to replace the
1087 already-installed version.
1090 Be aware that during a component update procedure that involves multiple
1091 object files (shared objects and main programs), concurrently starting
1092 processes may observe an inconsistent combination of object files (some
1093 already updated, some still at the previous version). For example,
1094 this can happen during an update of @theglibc{} itself.
1097 @c FIXME these are undocumented: