xref: /freebsd/contrib/llvm-project/lld/docs/ELF/start-stop-gc.rst (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1-z start-stop-gc
2================
3
4If your ``-Wl,--gc-sections`` build fail with a linker error like this:
5
6    error: undefined symbol: __start_meta
7    >>> referenced by {{.*}}
8    >>> the encapsulation symbol needs to be retained under --gc-sections properly; consider -z nostart-stop-gc (see https://lld.llvm.org/start-stop-gc)
9
10it is likely your C identifier name sections are not properly annotated to
11suffice under ``--gc-sections``.
12
13``__start_meta`` and ``__stop_meta`` are sometimes called encapsulation
14symbols. In October 2015, GNU ld switched behavior and made a ``__start_meta``
15reference from a live section retain all ``meta`` input sections. This
16conservative behavior works for existing code which does not take GC into fair
17consideration, but unnecessarily increases sizes for modern metadata section
18usage which desires precise GC.
19
20GNU ld 2.37 added ``-z start-stop-gc`` to restore the traditional behavior
21ld.lld 13.0.0 defaults to ``-z start-stop-gc`` and supports ``-z nostart-stop-gc``
22to switch to the conservative behavior.
23
24The Apple ld64 linker has a similar ``section$start`` feature and always
25allowed GC (like ``-z start-stop-gc``).
26
27Annotate C identifier name sections
28-----------------------------------
29
30A C identifier name section (``meta``) sometimes depends on another section.
31Let that section reference ``meta`` via a relocation.
32
33.. code-block:: c
34
35  asm(".pushsection .init_array,\"aw\",@init_array\n" \
36      ".reloc ., R_AARCH64_NONE, meta\n"              \
37      ".popsection\n")
38
39If a relocation is inconvenient, consider using ``__attribute__((retain))``
40(GCC 11 with modern binutils, Clang 13).
41
42.. code-block:: c
43
44  #pragma GCC diagnostic push
45  #pragma GCC diagnostic ignored "-Wattributes"
46  __attribute__((retain,used,section("meta")))
47  static const char dummy[0];
48  #pragma GCC diagnostic pop
49
50GCC before 11 and Clang before 13 do not recognize ``__attribute__((retain))``,
51so ``-Wattributes`` may need to be ignored. On ELF targets,
52``__attribute__((used))`` prevents compiler discarding, but does not affect
53linker ``--gc-sections``.
54
55In a macro, you may use:
56
57.. code-block:: c
58
59  _Pragma("GCC diagnostic push")
60  _Pragma("GCC diagnostic ignored \"-Wattributes\"")
61  ...
62  _Pragma("GCC diagnostic pop")
63
64If you use the ``SECTIONS`` command in a linker script, use
65`the ``KEEP`` keyword <https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html>`_, e.g.
66``meta : { KEEP(*(meta)) }``
67