Debian Codegraph @

debian/rust-vendor/link-section/README.md

raw
1 The crate is part of the [`linktime`](https://crates.io/crates/linktime) project.
2
3 [![GitHub](https://img.shields.io/badge/repo-github-blue)](https://github.com/mmastrac/linktime) [![Crates.io License](https://img.shields.io/crates/l/link-section)](https://crates.io/crates/link-section) [![Build Status](https://github.com/mmastrac/linktime/actions/workflows/rust.yml/badge.svg)](https://github.com/mmastrac/linktime/actions/workflows/rust.yml)
4
5
6 | crate | |
7 | --- | --- |
8 | `linktime`<br>[![docs.rs](https://docs.rs/linktime/badge.svg)](https://docs.rs/linktime) [![crates.io](https://img.shields.io/crates/v/linktime.svg)](https://crates.io/crates/linktime) | Convenience crate for `ctor`, `dtor` and `link-section` |
9 | `ctor`<br>[![docs.rs](https://docs.rs/ctor/badge.svg)](https://docs.rs/ctor) [![crates.io](https://img.shields.io/crates/v/ctor.svg)](https://crates.io/crates/ctor) | Module initialization functions before main |
10 | `dtor`<br>[![docs.rs](https://docs.rs/dtor/badge.svg)](https://docs.rs/dtor) [![crates.io](https://img.shields.io/crates/v/dtor.svg)](https://crates.io/crates/dtor) | Module shutdown functions before main |
11 | `link-section`<br>[![docs.rs](https://docs.rs/link-section/badge.svg)](https://docs.rs/link-section) [![crates.io](https://img.shields.io/crates/v/link-section.svg)](https://crates.io/crates/link-section) | Linker-managed typed (slices) and untyped sections |
12 | `scattered-collect`<br>[![docs.rs](https://docs.rs/scattered-collect/badge.svg)](https://docs.rs/scattered-collect) [![crates.io](https://img.shields.io/crates/v/scattered-collect.svg)](https://crates.io/crates/scattered-collect) | Linker-managed collections: slices, sorted slices, maps |
13 # link-section
14 A crate for defining linker-backed sections in Rust.
15
16 `link-section` provides two attributes:
17
18 - `#[section(...)]` defines a section handle. The handle is a `static` item used
19 to inspect the section at runtime, usually as a slice. The handle's visibility
20 determines where items may be submitted: public handles can be submitted from
21 any module, while private handles can only be submitted from the module that
22 defines them.
23 - `#[in_section(path::to::SECTION)]` submits an item to that section. A
24 submitted item is an item annotated with `#[in_section(...)]`; depending on
25 the section kind, it may also remain usable directly at the submission site.
26 The `path::to::SECTION` must be visible to the submission site.
27
28 Together, these attributes let separately-declared items be collected into one
29 linker section and accessed through a single section handle.
30
31 ## Visibility
32
33 Importantly, even though the linker is used to collect items, the visibility of
34 the section handle determines where items may be submitted: public handles can
35 be submitted from any crate (assuming the submitting crate references the one
36 with the collection handle), while private handles can only be submitted from
37 the crate that defines them.
38
39 The section name is generated from the name of the item and a location of the
40 item within the source tree. This means that you may have more than one
41 independent section with the item name in a project, and they will not conflict.
42
43 Note that if you are generating sections from a macro, you _must_ include at
44 least one token from the top-level macro call in the section definition to avoid
45 conflicts with tokens that are provided purely from the macro itself.
46
47 To allow for submission of items without visibility constraints, the crate
48 provides an `unsafe` option for the submission macro where the section's
49 name and attributes may be specified manually:
50
51 ```rust
52 pub struct MyType(u8);
53
54 mod my_private_section {
55 // Specify a section name so it can be used without a direct reference.
56 #[section(typed, unsafe, name = my_crate::SECTION_NAME)]
57 static MY_SECTION: link_section::TypedSection<MyType>;
58 }
59
60 mod elsewhere {
61 // This must match the definition site!
62 #[in_section(unsafe, name = my_crate::SECTION_NAME, type = typed)] // optionally: aux(main = MAIN_SECTION)
63 static ITEM: MyType = MyType(42);
64 }
65 ```
66
67 ### Syntax
68
69 Section definition:
70
71 - `#[section(<kind>)]`
72 - `#[section(<kind>, aux(main = <path::to::MAIN_SECTION>))]`
73 - `#[section(unsafe, type = <kind>)]`
74 - `#[section(unsafe, type = <kind>, name = <name>)]`
75
76 Section submission:
77
78 - `#[in_section(path::to::SECTION)]`
79 - `#[in_section(unsafe, type = <kind>, name = <name>)]`
80
81 ## Section Kinds
82
83 There are five section kinds:
84
85 - `untyped`: Collects related code or data in one linker section without
86 exposing a typed slice. This is useful for co-location, phase-specific code,
87 or platform-specific section placement.
88 - `typed`: Stores values of one type and exposes them as an immutable slice.
89 - `mutable`: Stores values of one type and exposes them as a mutable slice.
90 - `reference`: Stores values of one type, exposes them as an immutable slice,
91 and also lets each submitted item be used as a reference at its submission
92 site.
93 - `movable`: Stores values of one type and exposes them as a mutable slice, and
94 also lets each submitted item be used as a reference at its submission site.
95 The entire section is available as a mutable slice, and items may be reordered
96 during startup initialization (see [`TypedMovableSection`] for more details).
97
98 | Section Kind | Immutable Slice | Mutable Slice | `const` Items | `static` / Reference Items |
99 | ------------ | --------------- | ------------- | ------------- | -------------------------- |
100 | `untyped` | ❌ | ❌ | ✅ | ✅ |
101 | `typed` | ✅ | ❌ | ✅ | ⚠️ |
102 | `mutable` | ✅ | ✅ | ✅ | ❌ |
103 | `reference` | ✅ | ❌ | ✅ | ✅ |
104 | `movable` | ✅ | ✅ | ❌ | ✅ |
105
106 ⚠️ Native targets support `static` submissions for `typed` sections; WASM uses
107 `const` submissions only.
108
109 ## Submitting Items
110
111 Items are submitted with `#[in_section(SECTION)]`.
112
113 A `const` submission copies the value into the section. The original constant
114 remains usable as a normal Rust constant, and the section receives its own
115 stored copy.
116
117 ```rust
118 #[in_section(MY_SECTION)]
119 pub const ITEM: MyType = MyType::new();
120 ```
121
122 A `static` submission stores the `static` directly in the section. References to
123 the `static` and references obtained from the section slice point at the same
124 underlying object. `static` submissions are supported for typed sections on
125 native targets and for reference sections.
126
127 ```rust
128 #[in_section(MY_SECTION)]
129 pub static ITEM: MyType = MyType::new();
130 ```
131
132 A `fn` submitted to a typed section is stored as a function pointer. The
133 function body itself is not placed into the typed data section.
134
135 ```rust
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.
383 # Re-exporting from another crate
384
385 The macros assume this crate is available as a direct dependency, resolving their
386 support paths through the crate's own name. If you re-export this crate's items as
387 part of your own crate (so that downstream users don't need to depend on it
388 directly), you have two options:
389
390 - (preferred) use the declarative macro form. It resolves its support paths
391 relative to your re-export, so no extra configuration is required.
392 - Alternatively, pass the `crate_path` attribute to redirect the macro's
393 generated output to the path where this crate has been re-exported.
394
395 See the `crate_path` entry in the *Macro Attributes* section below for the exact
396 syntax for this crate.
397 # Crate Features
398
399 | Cargo feature | Description |
400 | --- | --- |
401 | `proc_macro` | Crate feature `proc_macro` (enables the `#[section]` attribute shim). |
402
403 # Macro Attributes
404
405 <table><tr><th>Attribute</th><th>Description</th></tr>
406 <tr><td><code>aux(main = path::to::MAIN_SECTION)</code></td><td>
407
408 Auxiliary sections are stored in a section near the main section. The
409 aux path must be a valid reference to the main section.
410
411
412 </td></tr>
413 <tr><td><code>crate_path = ::path::to::link_section</code></td><td>
414
415 The path to the `link-section` crate containing the support macros. If
416 you re-export `link-section` items as part of your crate, you can use
417 this to redirect the macro's output to the correct crate.
418
419 Using the declarative [`section!`][s] form is
420 preferred over this parameter.
421
422 [s]: crate::declarative::section!
423
424
425 </td></tr>
426 <tr><td><code>name = my_crate::SECTION_NAME</code></td><td>
427
428 Specify a custom section name to allow the section to be used without a
429 direct reference. If not specified, the section name will be generated
430 using the item name and a path to the section.
431
432 It is valid to specify multiple sections with the same name, and the linker
433 will ensure that both sections contain the same items. The multiple sections
434 must contain the same type, otherwise the section will `panic!` at runtime.
435
436 While `name` accepts a path, this path does not refer to a specific Rust
437 item path.
438
439
440 </td></tr>
441 <tr><td><code>untyped | typed | mutable | movable | reference</code></td><td>
442
443 The type of the section.
444
445
446 </td></tr>
447 <tr><td><code>unsafe</code></td><td>
448
449 Allow the section to be used without a direct reference.
450
451
452 </td></tr>
453 </table>
454
455 # Defaults