Debian Codegraph @

debian/rust-vendor/link-section/docs/PREAMBLE.md

raw
1 A crate for defining linker-backed sections in Rust.
2
3 `link-section` provides two attributes:
4
5 - `#[section(...)]` defines a section handle. The handle is a `static` item used
6 to inspect the section at runtime, usually as a slice. The handle's visibility
7 determines where items may be submitted: public handles can be submitted from
8 any module, while private handles can only be submitted from the module that
9 defines them.
10 - `#[in_section(path::to::SECTION)]` submits an item to that section. A
11 submitted item is an item annotated with `#[in_section(...)]`; depending on
12 the section kind, it may also remain usable directly at the submission site.
13 The `path::to::SECTION` must be visible to the submission site.
14
15 Together, these attributes let separately-declared items be collected into one
16 linker section and accessed through a single section handle.
17
18 ## Visibility
19
20 Importantly, even though the linker is used to collect items, the visibility of
21 the section handle determines where items may be submitted: public handles can
22 be submitted from any crate (assuming the submitting crate references the one
23 with the collection handle), while private handles can only be submitted from
24 the crate that defines them.
25
26 The section name is generated from the name of the item and a location of the
27 item within the source tree. This means that you may have more than one
28 independent section with the item name in a project, and they will not conflict.
29
30 Note that if you are generating sections from a macro, you _must_ include at
31 least one token from the top-level macro call in the section definition to avoid
32 conflicts with tokens that are provided purely from the macro itself.
33
34 To allow for submission of items without visibility constraints, the crate
35 provides an `unsafe` option for the submission macro where the section's
36 name and attributes may be specified manually:
37
38 ```rust
39 # mod root {
40 pub struct MyType(u8);
41
42 mod my_private_section {
43 # use link_section::section;
44 # use super::MyType;
45 // Specify a section name so it can be used without a direct reference.
46 #[section(typed, unsafe, name = my_crate::SECTION_NAME)]
47 static MY_SECTION: link_section::TypedSection<MyType>;
48 }
49
50 mod elsewhere {
51 # use link_section::in_section;
52 # use super::MyType;
53 // This must match the definition site!
54 #[in_section(unsafe, name = my_crate::SECTION_NAME, type = typed)] // optionally: aux(main = MAIN_SECTION)
55 static ITEM: MyType = MyType(42);
56 }
57 # }
58 ```
59
60 ### Syntax
61
62 Section definition:
63
64 - `#[section(<kind>)]`
65 - `#[section(<kind>, aux(main = <path::to::MAIN_SECTION>))]`
66 - `#[section(unsafe, type = <kind>)]`
67 - `#[section(unsafe, type = <kind>, name = <name>)]`
68
69 Section submission:
70
71 - `#[in_section(path::to::SECTION)]`
72 - `#[in_section(unsafe, type = <kind>, name = <name>)]`
73
74 ## Section Kinds
75
76 There are five section kinds:
77
78 - `untyped`: Collects related code or data in one linker section without
79 exposing a typed slice. This is useful for co-location, phase-specific code,
80 or platform-specific section placement.
81 - `typed`: Stores values of one type and exposes them as an immutable slice.
82 - `mutable`: Stores values of one type and exposes them as a mutable slice.
83 - `reference`: Stores values of one type, exposes them as an immutable slice,
84 and also lets each submitted item be used as a reference at its submission
85 site.
86 - `movable`: Stores values of one type and exposes them as a mutable slice, and
87 also lets each submitted item be used as a reference at its submission site.
88 The entire section is available as a mutable slice, and items may be reordered
89 during startup initialization (see [`TypedMovableSection`] for more details).
90
91 | Section Kind | Immutable Slice | Mutable Slice | `const` Items | `static` / Reference Items |
92 | ------------ | --------------- | ------------- | ------------- | -------------------------- |
93 | `untyped` | ❌ | ❌ | ✅ | ✅ |
94 | `typed` | ✅ | ❌ | ✅ | ⚠️ |
95 | `mutable` | ✅ | ✅ | ✅ | ❌ |
96 | `reference` | ✅ | ❌ | ✅ | ✅ |
97 | `movable` | ✅ | ✅ | ❌ | ✅ |
98
99 ⚠️ Native targets support `static` submissions for `typed` sections; WASM uses
100 `const` submissions only.
101
102 ## Submitting Items
103
104 Items are submitted with `#[in_section(SECTION)]`.
105
106 A `const` submission copies the value into the section. The original constant
107 remains usable as a normal Rust constant, and the section receives its own
108 stored copy.
109
110 ```rust
111 # pub struct MyType(u8); impl MyType { const fn new() -> Self { Self(0) } }
112 # use link_section::{in_section, section};
113 # #[section(typed)] pub static MY_SECTION: link_section::TypedSection<MyType>;
114 #[in_section(MY_SECTION)]
115 pub const ITEM: MyType = MyType::new();
116 ```
117
118 A `static` submission stores the `static` directly in the section. References to
119 the `static` and references obtained from the section slice point at the same
120 underlying object. `static` submissions are supported for typed sections on
121 native targets and for reference sections.
122
123 ```rust
124 # pub struct MyType(u8); impl MyType { const fn new() -> Self { Self(0) } }
125 # use link_section::{in_section, section};
126 # #[section(typed)] pub static MY_SECTION: link_section::TypedSection<MyType>;
127 #[in_section(MY_SECTION)]
128 pub static ITEM: MyType = MyType::new();
129 ```
130
131 A `fn` submitted to a typed section is stored as a function pointer. The
132 function body itself is not placed into the typed data section.
133
134 ```rust
135 # use link_section::{in_section, section};
136 #[section(typed)]
137 pub static FUNCTIONS: link_section::TypedSection<fn()>;
138
139 #[in_section(FUNCTIONS)]
140 pub fn callback() {
141 // ...
142 }
143 ```
144
145 ## Platform Support
146
147 | Platform | Support |
148 | ------------------------ | ----------------------------------------------- |
149 | Linux | ✅ Supported, uses orphan section handling (§1) |
150 | \*BSD | ✅ Supported, uses orphan section handling (§1) |
151 | macOS | ✅ Fully supported |
152 | Windows | ✅ Fully supported |
153 | WASM | ✅ Fully supported, via emulation (§2) |
154 | AIX | ✅ Supported (§3) (§4) |
155 | Other LLVM/GCC platforms | ✅ Supported, uses orphan section handling (§1) |
156
157 (§1) Orphan section handling is a feature of the linker that allows sections to
158 be defined without a pre-defined name.
159
160 (§2) WASM requires `const` items, and uses `ctor`-like initialization to copy
161 data to a contiguous section. To access link-section slices in WASM in `#[ctor]`
162 functions, make sure to use at least `#[ctor(priority = 1)]`.
163
164 (§3) AIX requires `-C link-arg=-bdbg:namedsects:ss` which enables functionality
165 similar to LLVM/GCC's orphan section handling.
166
167 (§4) Empty sections are not currently supported: ensure every section has at least
168 one item, or pass the `-C link-arg=-berok` linker flag to ignore errors.
169
170 ## Platform Details
171
172 Each platform has a slightly different implementation of section control.
173
174 ### Linux and other LLVM/GCC platforms
175
176 - Has start/end symbols: ✅ (C-compatible names only)
177 - Supports linker sorting: ❌
178
179 On Linux and other LLVM/GCC platforms, the linker supports orphan sections,
180 which allow sections to be defined without a pre-defined name. These sections
181 are emitted as if they were r/w `.data`. For sections with C-compatible names,
182 the linker will emit start/end symbols for the section.
183
184 Orphan sections are not sorted via numeric suffix (e.g.: `SECTION.1`,
185 `SECTION.2`, etc.) with the default linker script.
186
187 ### macOS
188
189 - Has start/end symbols: ✅
190 - Supports linker sorting: ❌
191
192 On macOS, sections are configured via `__DATA` or `__TEXT` prefix and option
193 suffixes (`regular`, `no_dead_strip`, etc.). The linker emits start and stop
194 symbols, but Rust requires a (somewhat-stable) `\x01` prefix to avoid mangling
195 the section name. macOS does not support ordering in the linker.
196
197 ### Windows
198
199 - Has start/end symbols: ❌
200 - Supports linker sorting: ✅
201
202 On Windows, the linker does not emit start/end symbols, but all sections with a
203 common prefix are automatically sorted by suffix, allowing us to use suffixes to
204 control placement of start/stop symbols that we emit.
205
206 See
207 [this blog post](https://devblogs.microsoft.com/oldnewthing/20181107-00/?p=100155)
208 and
209 [this blog post](https://devblogs.microsoft.com/oldnewthing/20181108-00/?p=100165)
210 for more details about the alphabetical sorting rule.
211
212 ### WASM
213
214 - Has start/end symbols: ❌
215 - Supports linker sorting: ❌
216
217 On WASM platforms there are no linker-provided start/end symbols and no linker
218 ordering. Normally, WASM does not support placing arbitrary data in link
219 sections - only non-pointer data is supported. To work around this, the WASM
220 support uses `const` items and pre-`main` construction functions to gather each
221 entry into a contiguous section allocated at startup.
222
223 Each submitted item emits a plain (linear-memory) static "list node" plus an
224 `.init_array.0` constructor that threads the node onto an intrusive linked list
225 rooted in the section. Because these nodes are interior-mutable and have their
226 address taken, LLVM cannot merge them even under fat LTO, so the item
227 count is always exact.
228
229 The list is materialised into one contiguous allocation by an eager,
230 ordered constructor. Item submissions run at `.init_array.0` (priority 0), and
231 each section emits a finalization constructor at `.init_array.1` (priority 1).
232 Because wasm-ld orders `.init_array.*` by the integer value of the suffix, the
233 finalizer is guaranteed to run after every submission and before any
234 `#[ctor(priority >= 2)]` and before `main` — a well-defined pre-`main` time
235 rather than "whenever the section is first read".
236
237 [`Ref`] / [`MovableRef`] handles carry a pointer to their owning section and also
238 flatten it on first dereference. That lazy path is an idempotent backstop for the
239 one remaining tie: an explicit `#[ctor(priority = 1)]` that runs before the
240 finalizer. As a result the `#[ctor]` priority requirement is the same as
241 elsewhere: to read a link section or dereference a [`Ref`] / [`MovableRef`]
242 handle from a `#[ctor]`, use at least `#[ctor(priority = 1)]`. Reads from `main`
243 (or any later constructor) are always safe.
244
245 A `#[ctor(priority = 0)]` that reads section *bounds* (not a [`Ref`]) is the one
246 corner that breaks: it interleaves with `.init_array.0` submissions, triggers an
247 early lazy flatten, and then any later submission panics (the section is already
248 materialised). The contract — use at least priority 1 — is unchanged, but the
249 panic now names the section and the likely cause.
250
251 ### AIX
252
253 - Has start/end symbols: ✅
254 - Supports linker sorting: ❌
255
256 AIX maps Rust's `#[link_section]` to `csect`s (Control Sections), which act like
257 subsections of the larger `.text` and `.data` sections
258 <sup>[↳](https://www.ibm.com/docs/kk/aix/7.2.0?topic=program-understanding-programming-toc)</sup>.
259 A `csect` is the smallest, indivisible unit of code or data.
260
261 By default, AIX does not have section start/stop symbols, but the most recent
262 versions of the linker added a new `-bdbg:namedsects:ss` flag which enables
263 section start/stop symbols
264 <sup>[↳](https://reviews.llvm.org/D124857?id=427067)</sup>.
265
266 This flag can be set with `-C link-arg=-bdbg:namedsects:ss` (or by upgrading to
267 a recent Rust version that sets this automatically
268 <sup>[↳](https://rust.googlesource.com/rust/+/ad582a586550bf2c72e963939f61a71df1af7c0c%5E%21/#F0)</sup>
269 to support link sections.
270
271 The linker will report an error like this if the start/stop symbols are not
272 found:
273
274 ```text
275 = note: ld: 0711-317 ERROR: Undefined symbol: __start__data_link_section_DATABASES
276 ld: 0711-317 ERROR: Undefined symbol: __stop__data_link_section_DATABASES
277 ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information.
278 ```
279
280 In addition, the linker may report the same errors if a section is empty. It is
281 recommended that you either (1) provide a sentinel item for AIX that can be skipped
282 in the slice, or (2) pass the `-C link-arg=-berok` linker flag to ignore the error.
283
284 For debugging AIX link-section issues, `-C link-arg=-bmap:[path]/linker.out` and
285 `-C link-arg=-bnoquiet` may also be useful.
286
287 AIX supports a special mode to strip (`strip -r`) that preserves structural
288 symbols like `csect`s and exports. A future version of `link-section` may add
289 support for loading `csect` bounds from the binary's symbol table.
290
291 ```toml
292 [target.powerpc64-ibm-aix]
293 rustflags = [
294 "-C", "link-arg=-bdbg:namedsects:ss", # required
295 "-C", "link-arg=-bmap:linker.out", # for debugging
296 "-C", "link-arg=-bnoquiet", # for debugging
297 ]
298 ```
299
300 ## Typed Sections
301
302 Typed sections provide a section where all items are of a specific, sized type.
303 The typed section may be accessed as a slice of the type at zero cost if
304 desired.
305
306 A typed section can be created from either `static` or `const` items.
307
308 For `const` items: a copy of the `const` is materialised at link time, while the
309 constant itself remains available for use as a constant in `const` contexts.
310
311 For `static` items: the static is stored directly in the link section.
312
313 `fn` items are special-cased and stored as function pointers in the typed
314 section.
315
316 ## Exclusive Access
317
318 Mutable sections (ie: [`TypedMutableSection`] and [`TypedMovableSection`])
319 require exclusive access to the section's memory while calling
320 [`TypedMutableSection::as_mut_slice`] or [`TypedMovableSection::as_mut_slice`].
321
322 This is normally satisfied only during pre-`main` initialization (for example
323 inside a `#[ctor]`). After `main`, the caller must guarantee no concurrent reads
324 or writes from other threads and no active Rust references into the section.
325
326 It is highly recommended not to access the mutable references after `main` has
327 started.
328
329 ## Usage
330
331 Create an untyped section using the `#[section]` macro that keeps related items
332 in close proximity:
333
334 ```rust
335 use link_section::{in_section, section};
336
337 #[section(untyped)]
338 pub static CODE_SECTION: link_section::Section;
339
340 #[in_section(CODE_SECTION)]
341 pub fn link_section_function() {
342 println!("link_section_function");
343 }
344 ```
345
346 Create a typed section using the `#[section]` macro that stores items of a
347 specific, sized type from `static` or `const` items:
348
349 ```rust
350 mod my_registry {
351 use link_section::{in_section, section};
352
353 pub struct MyStruct {
354 name: &'static str,
355 }
356
357 #[section(typed)]
358 pub static MY_REGISTRY: link_section::TypedSection<MyStruct>;
359
360 // Registers a `const` item.
361 mod register_a_constant {
362 use super::*;
363
364 // A copy of this constant is registered in the link section.
365 #[in_section(MY_REGISTRY)]
366 pub const LINKED_MY_STRUCT: MyStruct = MyStruct { name: "my_struct" };
367 }
368
369 // Registers a `static` item.
370 mod register_a_static {
371 use super::*;
372
373 // This static lives directly in the link section.
374 #[in_section(MY_REGISTRY)]
375 pub static LINKED_MY_STRUCT: MyStruct = MyStruct { name: "my_struct_2" };
376 }
377 }
378 ```
379
380 ## Inspiration
381
382 `link-section` would have been far more challenging to implement without dtolnay's great `linkme` project paving the way.