Debian Codegraph @

debian/rust-vendor/link-section/src/platform/wasm.rs

raw
1 //! WASM-specific implementation of the link section.
2 //!
3 //! WASM has no linker-gathered sections whose bounds are available at runtime.
4 //! Each submission emits a single intrusive [`LinkCell`] static: the value `T`
5 //! at offset 0 with list metadata trailing it, plus an `.init_array.0`
6 //! constructor that threads the cell onto a singly-linked list. The cells are
7 //! interior-mutable and address-significant, so LLVM cannot merge them even
8 //! under fat LTO with identical values.
9 //!
10 //! Sections that hand out `Ref`/`MovableRef` handles carry a fix-up slot after
11 //! the list pointer ([`LinkMetaSlot`]). Plain `typed`/`mutable` sections do not
12 //! ([`LinkMeta`]).
13 //!
14 //! The list is flattened into contiguous storage either by the "backstop" ctor
15 //! that runs in `.init_array.1`, or lazily on the first bounds/ref access.
16
17 use core::alloc::Layout;
18 use core::cell::UnsafeCell;
19 use core::ptr::{self, NonNull};
20 use core::sync::atomic::{AtomicU8, Ordering};
21
22 use super::{SectionRange, SyncUnsafeCell};
23
24 #[doc(hidden)]
25 #[macro_export]
26 #[allow(unknown_lints, edition_2024_expr_fragment_specifier)]
27 macro_rules! __get_section_wasm {
28 (movable, name=$name:tt, type=$generic_ty:ty) => {
29 $crate::__get_section_wasm!(@emit
30 ($name),
31 ($crate::__support::wasm::LinkSectionMovableInfo),
32 ($crate::__support::wasm::LinkSectionMovableInfo::new::<$generic_ty>(__LINK_SECTION_NAME)),
33 ($crate::__support::MovableBounds)
34 )
35 };
36 ($section_type:ident, name=$name:tt, type=$generic_ty:ty) => {
37 $crate::__get_section_wasm!(@emit
38 ($name),
39 ($crate::__support::wasm::LinkSectionInfo),
40 // Only `reference` sections need per-item fix-up slots.
41 ($crate::__support::wasm::LinkSectionInfo::new::<$generic_ty>(
42 __LINK_SECTION_NAME,
43 $crate::__support::wasm::section_has_slot!($section_type),
44 )),
45 ($crate::__support::Bounds)
46 )
47 };
48 (@emit
49 ($name:tt),
50 ($info_ty:ty),
51 ($info_init:expr),
52 ($bounds_ty:path)
53 ) => {
54 {
55 static __LINK_SECTION_NAME: &'static str = $crate::__support::section_name!(
56 string item data bare $name
57 );
58 $crate::__support::add_section_link_attribute!(
59 item data bounds $name
60 #[export_name = __]
61 #[used]
62 static __LINK_SECTION_INFO: $crate::__support::wasm::LinkSectionInfoLock<$info_ty> =
63 $crate::__support::wasm::LinkSectionInfoLock::new($info_init);
64 );
65
66 // Eager finalization at `.init_array.1` (submissions are `.init_array.0`).
67 #[link_section = ".init_array.1"]
68 #[used]
69 #[allow(non_snake_case)]
70 static __LINK_SECTION_FLATTEN_FN_REF: extern "C" fn() = {
71 extern "C" fn __LINK_SECTION_FLATTEN_FN() {
72 unsafe {
73 $crate::__support::wasm::flatten(
74 &raw const __LINK_SECTION_INFO,
75 );
76 }
77 }
78 __LINK_SECTION_FLATTEN_FN
79 };
80
81 unsafe { <$bounds_ty>::new(&raw const __LINK_SECTION_INFO) }
82 }
83 };
84 }
85
86 pub use crate::__get_section_wasm as get_section;
87
88 /// Import a section's `LinkSectionInfoLock` static under a local name.
89 ///
90 /// The definition lives in [`__get_section_wasm!`]; every site that needs to
91 /// reference it (item registration, `Ref`/`MovableRef` storage) imports it via
92 /// this helper so the `extern "C"` block, link-name mangling, and type are
93 /// spelled once. A mismatched `$info_ty` would be a silent definition/import
94 /// clash (UB).
95 #[doc(hidden)]
96 #[macro_export]
97 macro_rules! __import_section_info {
98 ($info_ty:ty, $local_name:ident, $section:tt) => {
99 $crate::__add_section_link_attribute!(
100 item data bounds $section
101 #[link_name = __]
102 extern "C" {
103 static $local_name: $crate::__support::wasm::LinkSectionInfoLock<$info_ty>;
104 }
105 );
106 };
107 }
108 pub use crate::__import_section_info as import_section_info;
109
110 /// Whether a section kind hands out reference handles and so needs a per-item
111 /// fix-up slot. Only `reference` sections do. Expands to a `const bool`.
112 #[doc(hidden)]
113 #[macro_export]
114 macro_rules! __section_has_slot {
115 (reference) => {
116 true
117 };
118 ($other:ident) => {
119 false
120 };
121 }
122 pub use crate::__section_has_slot as section_has_slot;
123
124 crate::__def_section_name! {
125 __section_name_wasm,
126 {
127 data bare => (".data" ".link_section.") __ ();
128 data section => (".data" ".link_section.") __ ();
129 code bare => (".text" ".link_section.") __ ();
130 code section => (".text" ".link_section.") __ ();
131 data bounds => (".data" ".link_section.") __ (".bounds");
132 }
133 AUXILIARY = ".";
134 REFS = ".r.";
135 MAX_LENGTH = 16;
136 HASH_LENGTH = 6;
137 VALID_SECTION_CHARS = "_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
138 }
139
140 #[cfg(not(target_family = "wasm"))]
141 #[doc(hidden)]
142 #[macro_export]
143 #[allow(unknown_lints, edition_2024_expr_fragment_specifier)]
144 macro_rules! __register_wasm_item {
145 ($($args:tt)*) => {};
146 }
147
148 #[cfg(target_family = "wasm")]
149 #[doc(hidden)]
150 #[macro_export]
151 #[allow(unknown_lints, edition_2024_expr_fragment_specifier)]
152 macro_rules! __register_wasm_item {
153 // Movable section: carry the `MovableRef` slot for flatten to fix up.
154 (movable, type=$ty:ty, value=$value:expr, slot=$slot:expr, section=$section:tt) => {
155 $crate::__register_wasm_item!(@emit
156 info_ty = ($crate::__support::wasm::LinkSectionMovableInfo),
157 ty = ($ty),
158 meta = ($crate::__support::wasm::LinkMetaSlot),
159 new = ($value, $slot as *const ()),
160 section = $section
161 );
162 };
163 // Reference section: carry the `Ref` slot for flatten to fix up.
164 ($section_type:ident, type=$ty:ty, value=$value:expr, ref=$ident:ident, section=$section:tt) => {
165 $crate::__register_wasm_item!(@emit
166 info_ty = ($crate::__support::wasm::LinkSectionInfo),
167 ty = ($ty),
168 meta = ($crate::__support::wasm::LinkMetaSlot),
169 new = ($value, &$ident as *const _ as *const ()),
170 section = $section
171 );
172 };
173 // Reference-section const items do not expose a `Ref`, but their cells must
174 // match the layout for static items.
175 (reference, type=$ty:ty, value=$value:expr, section=$section:tt) => {
176 $crate::__register_wasm_item!(@emit
177 info_ty = ($crate::__support::wasm::LinkSectionInfo),
178 ty = ($ty),
179 meta = ($crate::__support::wasm::LinkMetaSlot),
180 new = ($value, ::core::ptr::null()),
181 section = $section
182 );
183 };
184 // Typed / mutable const items: value is copied into the section, no slot.
185 ($section_type:ident, type=$ty:ty, value=$value:expr, section=$section:tt) => {
186 $crate::__register_wasm_item!(@emit
187 info_ty = ($crate::__support::wasm::LinkSectionInfo),
188 ty = ($ty),
189 meta = ($crate::__support::wasm::LinkMeta),
190 new = ($value),
191 section = $section
192 );
193 };
194 (@emit
195 info_ty = ($info_ty:ty),
196 ty = ($ty:ty),
197 meta = ($meta:ty),
198 new = ($($new_args:expr),*),
199 section = $section:tt
200 ) => {
201 #[used]
202 static __LINK_SECTION_CELL: $crate::__support::wasm::LinkCell<$ty, $meta> =
203 <$crate::__support::wasm::LinkCell<$ty, $meta>>::new($($new_args),*);
204
205 $crate::__import_section_info!(
206 $info_ty, __LINK_SECTION_INFO, $section
207 );
208
209 #[link_section = ".init_array.0"]
210 #[used] // TODO: used(linker) with linktime_used_linker feature
211 #[allow(non_snake_case)]
212 static __LINK_SECTION_ITEM_FN_REF: extern "C" fn() = {
213 extern "C" fn __LINK_SECTION_ITEM_FN() {
214 // Double-registration (e.g. `__wasm_call_ctors` running twice)
215 // is skipped inside `push` via the cell's `UNREGISTERED`
216 // sentinel, so there's no per-item disarm flag here.
217 unsafe {
218 $crate::__support::wasm::register(
219 &raw const __LINK_SECTION_INFO,
220 __LINK_SECTION_CELL.as_cell_ptr(),
221 );
222 }
223 }
224 __LINK_SECTION_ITEM_FN
225 };
226 };
227 }
228
229 /// The lifecycle state of a section's storage, stored as a `u8`.
230 #[repr(u8)]
231 enum LinkSectionState {
232 /// Items are still being submitted. No contiguous storage exists yet.
233 Gathering = 0,
234 /// The list has been materialised into contiguous storage.
235 Flattened = 1,
236 }
237
238 /// The lock state of a section's info record, stored as a `u8`.
239 #[repr(u8)]
240 enum LockState {
241 /// The info record is unlocked.
242 Unlocked = 0,
243 /// The info record is locked.
244 Locked = 1,
245 }
246
247 /// Intrusive list link for a plain (`typed`/`mutable`) cell: just the pointer to
248 /// the next cell in the list. Trails the value in a [`LinkCell`].
249 #[repr(C)]
250 pub struct LinkMeta {
251 /// Start of the next cell in the list (written at registration). Null for
252 /// the tail. Holds [`UNREGISTERED`] until the cell is pushed.
253 next: UnsafeCell<*mut u8>,
254 }
255
256 /// Intrusive list link for a reference (`reference`/`movable`) cell: the next
257 /// pointer, plus a type-erased `*const UnsafeCell<*const T>` fix-up slot that
258 /// flatten points at the item's final location. `next` stays first so it lives
259 /// at the same offset as [`LinkMeta`]'s `next`.
260 #[repr(C)]
261 pub struct LinkMetaSlot {
262 next: UnsafeCell<*mut u8>,
263 slot: *const (),
264 }
265
266 /// Sentinel stored in a cell's `next` field until [`LinkSectionInfo::push`]
267 /// threads it onto the list. Lets `push` detect and skip a double-registration
268 /// (e.g. if `__wasm_call_ctors` runs twice) without a per-item disarm flag.
269 /// `ptr::dangling_mut::<u8>()` (pointer value 1): non-null so it stays distinct
270 /// from the list-tail `null`, and a well-formed aligned dangling pointer.
271 const UNREGISTERED: *mut u8 = ::core::ptr::dangling_mut::<u8>();
272
273 /// Byte offset of the fix-up slot within [`LinkMetaSlot`] (it trails `next`).
274 const SLOT_OFFSET: usize = core::mem::size_of::<*mut u8>();
275
276 /// Offset of the trailing link metadata within a cell, given the value size.
277 ///
278 /// The value is the leading field and the link is pointer-aligned, so this is
279 /// `size_of::<T>()` rounded up to the pointer alignment. It depends only on the
280 /// value size — not on `T`'s alignment or on the link type (`LinkMeta` vs
281 /// `LinkMetaSlot`) — so flatten recovers it at runtime from the stored `size_of`.
282 const fn meta_offset(size_of: usize) -> usize {
283 let align = core::mem::align_of::<*mut u8>();
284 (size_of + align - 1) & !(align - 1)
285 }
286
287 /// Intrusive list node emitted once per submitted item. The value `T` is the
288 /// leading field (offset 0) so flatten copies `size_of::<T>()` bytes straight
289 /// from the cell's address, and the link metadata `M` trails it. The cell is
290 /// interior-mutable and address-significant, so LLVM can't fold identical cells
291 /// even under fat LTO. That is what keeps the item count LTO-safe.
292 #[repr(C)]
293 pub struct LinkCell<T: 'static, M> {
294 value: UnsafeCell<T>,
295 meta: M,
296 }
297
298 // SAFETY: `value` is set at construction and read only under the section lock
299 // at flatten, where it is copied out as bytes and (for reference sections) handed
300 // back out as `&T`. The trailing link is written only under that lock. Requiring
301 // `T: Sync` matches what every non-WASM target already enforces for typed items
302 // (`static IDENT: T` requires `T: Sync`), so a `!Sync` `T` no longer compiles on
303 // wasm only to surface later as a bogus `&T` from `as_slice`.
304 unsafe impl<T: 'static + Sync, M> Sync for LinkCell<T, M> {}
305
306 impl<T: 'static> LinkCell<T, LinkMeta> {
307 /// Create a plain cell embedding `value` (no fix-up slot).
308 pub const fn new(value: T) -> Self {
309 Self {
310 value: UnsafeCell::new(value),
311 meta: LinkMeta {
312 next: UnsafeCell::new(UNREGISTERED),
313 },
314 }
315 }
316 }
317
318 impl<T: 'static> LinkCell<T, LinkMetaSlot> {
319 /// Create a cell embedding `value` and a stable `slot` for flatten to fix up
320 /// (`Ref`/`MovableRef` sections).
321 pub const fn new(value: T, slot: *const ()) -> Self {
322 Self {
323 value: UnsafeCell::new(value),
324 meta: LinkMetaSlot {
325 next: UnsafeCell::new(UNREGISTERED),
326 slot,
327 },
328 }
329 }
330 }
331
332 impl<T: 'static, M> LinkCell<T, M> {
333 /// Pointer to the start of this cell (the value). Stored in the section's
334 /// list and in each cell's `meta.next`.
335 pub const fn as_cell_ptr(&self) -> *mut u8 {
336 self as *const LinkCell<T, M> as *mut u8
337 }
338 }
339
340 /// The link section handle. Registration and the first (flattening) read are
341 /// single-threaded. An atomic lock makes concurrent misuse panic instead of UB.
342 #[derive(Clone, Copy)]
343 pub struct LinkSection<I>(NonNull<LinkSectionInfoLock<I>>);
344
345 impl<I> LinkSection<I> {
346 /// Get a handle to the section info.
347 ///
348 /// # Safety
349 ///
350 /// `info_ptr` must point to the macro-generated `LinkSectionInfoLock<I>`
351 /// static for the section's entire lifetime. Registration and first access
352 /// must be single-threaded, pre-`main`.
353 pub const unsafe fn new(info_ptr: *const LinkSectionInfoLock<I>) -> Self {
354 Self(unsafe { NonNull::new_unchecked(info_ptr as *mut _) })
355 }
356
357 /// Lock the section info and return a guard.
358 #[inline]
359 pub fn lock(&self) -> LinkSectionLockGuard<'_, I> {
360 let lock_state = unsafe { self.lock_ref() };
361 if lock_state
362 .compare_exchange(
363 LockState::Unlocked as _,
364 LockState::Locked as _,
365 Ordering::Acquire,
366 Ordering::Acquire,
367 )
368 .is_err()
369 {
370 panic!("Link section already locked: concurrent access is not supported");
371 }
372 LinkSectionLockGuard(lock_state, unsafe { self.as_mut() })
373 }
374
375 #[inline(always)]
376 unsafe fn lock_ref(&self) -> &AtomicU8 {
377 // as_ref_unchecked when we bump MSRV
378 unsafe {
379 ptr::addr_of!((*self.0.as_ptr()).lock)
380 .as_ref()
381 .unwrap_unchecked()
382 }
383 }
384
385 #[inline(always)]
386 #[allow(clippy::mut_from_ref)]
387 unsafe fn as_mut(&self) -> &mut I {
388 unsafe {
389 let unsafe_cell = ptr::addr_of!((*self.0.as_ptr()).info);
390 // as_mut_unchecked when we bump MSRV
391 UnsafeCell::raw_get(unsafe_cell).as_mut().unwrap_unchecked()
392 }
393 }
394 }
395
396 /// Lightweight lock guard for the link section.
397 pub struct LinkSectionLockGuard<'a, I>(&'a AtomicU8, &'a mut I);
398 impl<'a, I> core::ops::Deref for LinkSectionLockGuard<'a, I> {
399 type Target = I;
400 fn deref(&self) -> &Self::Target {
401 self.1
402 }
403 }
404 impl<'a, I> core::ops::DerefMut for LinkSectionLockGuard<'a, I> {
405 fn deref_mut(&mut self) -> &mut Self::Target {
406 self.1
407 }
408 }
409 impl<'a, I> Drop for LinkSectionLockGuard<'a, I> {
410 fn drop(&mut self) {
411 self.0.store(LockState::Unlocked as _, Ordering::Release);
412 }
413 }
414
415 /// Lock + info record for a section.
416 #[repr(C)]
417 pub struct LinkSectionInfoLock<I> {
418 lock: AtomicU8,
419 info: UnsafeCell<I>,
420 }
421
422 // SAFETY: info mutation is guarded by `LinkSection::lock` (via `AtomicU8`).
423 unsafe impl<I> Sync for LinkSectionInfoLock<I> {}
424
425 impl<I> LinkSectionInfoLock<I> {
426 /// Create a new link section lock + info.
427 pub const fn new(info: I) -> Self {
428 Self {
429 lock: AtomicU8::new(LockState::Unlocked as _),
430 info: UnsafeCell::new(info),
431 }
432 }
433 }
434
435 /// A WASM link section: the intrusive submission list and, once flattened, the
436 /// contiguous storage bounds.
437 #[repr(C)]
438 pub struct LinkSectionInfo {
439 state: u8,
440 /// Whether cells carry a [`LinkMetaSlot`] fix-up slot (`reference`/`movable`
441 /// sections) rather than a bare [`LinkMeta`] (`typed`/`mutable` sections).
442 has_slot: bool,
443 head: *mut u8,
444 count: usize,
445 start: *const (),
446 end: *const (),
447 size_of: usize,
448 align_of: usize,
449 name: &'static str,
450 }
451
452 impl LinkSectionInfo {
453 /// Create metadata for a WASM link section storing `T`. `has_slot` selects
454 /// [`LinkMetaSlot`] cells (reference sections) over [`LinkMeta`] cells.
455 pub const fn new<T: 'static>(name: &'static str, has_slot: bool) -> Self {
456 Self {
457 state: LinkSectionState::Gathering as _,
458 has_slot,
459 head: ptr::null_mut(),
460 count: 0,
461 start: ptr::null(),
462 end: ptr::null(),
463 size_of: ::core::mem::size_of::<T>(),
464 align_of: ::core::mem::align_of::<T>(),
465 name,
466 }
467 }
468
469 /// Thread a cell onto the front of the list. Panics if already flattened
470 /// (a real misuse: reading section bounds from `#[ctor(priority = 0)]`
471 /// interleaves with registration). Idempotent per cell: a second push of the
472 /// same cell (e.g. if `__wasm_call_ctors` runs twice, which
473 /// `wasm32-unknown-unknown` allows when both `_initialize` and `_start`
474 /// invoke it) is a no-op, detected via the cell's `UNREGISTERED` sentinel
475 /// before the flatten-state check.
476 ///
477 /// # Safety
478 ///
479 /// `cell` must be the start of a `LinkCell` whose value type matches this
480 /// section's `size_of`, and whose trailing meta is [`LinkMetaSlot`] iff this
481 /// section was created with `has_slot`.
482 unsafe fn push(&mut self, cell: *mut u8) {
483 unsafe {
484 let next = cell.add(meta_offset(self.size_of)) as *mut *mut u8;
485 if *next != UNREGISTERED {
486 // Already on the list. A double run of `__wasm_call_ctors` would
487 // otherwise self-loop the cell and inflate `count`; skip it
488 // before the flatten-state check so a late second run (after the
489 // `.init_array.1` finalizer) doesn't trip the panic below.
490 return;
491 }
492 if self.state == LinkSectionState::Flattened as u8 {
493 panic!(
494 "link section '{}' flattened before all items were registered \
495 (reading section bounds from #[ctor(priority = 0)]? use >= 1)",
496 self.name
497 );
498 }
499 *next = self.head;
500 }
501 self.head = cell;
502 self.count += 1;
503 }
504
505 /// Allocate contiguous storage for `count` values and copy the list into it
506 /// back-to-front so contiguous order matches submission order. Sets
507 /// `state = Flattened` and fixes up empty sections. Idempotent: no-op if
508 /// already flattened.
509 ///
510 /// For each cell, if `has_slot`, points its fix-up slot at the item's final
511 /// location and invokes `on_slot(index, slot)` (used by movable sections to
512 /// record backrefs).
513 fn materialise_with(&mut self, mut on_slot: impl FnMut(usize, *const ())) {
514 if self.state == LinkSectionState::Flattened as u8 {
515 return;
516 }
517 let count = self.count;
518 if count == 0 {
519 let dangling = NonNull::<u8>::dangling().as_ptr() as *const ();
520 self.start = dangling;
521 self.end = dangling;
522 self.state = LinkSectionState::Flattened as u8;
523 return;
524 }
525
526 let size_of = self.size_of;
527 let bytes = count
528 .checked_mul(size_of)
529 .unwrap_or_else(|| panic!("link section '{}' size overflow", self.name));
530 let arr =
531 unsafe { allocate(Layout::from_size_align(bytes, self.align_of).unwrap()) as *mut u8 };
532 if arr.is_null() {
533 panic!("link section '{}' allocation failed", self.name);
534 }
535
536 let meta_offset = meta_offset(size_of);
537 let mut cell = self.head;
538 let mut i = count;
539 while !cell.is_null() {
540 i -= 1;
541 unsafe {
542 let dst = arr.add(i * size_of);
543 // Value is the leading field, at offset 0.
544 ptr::copy_nonoverlapping(cell, dst, size_of);
545
546 let meta = cell.add(meta_offset);
547 if self.has_slot {
548 let slot = *(meta.add(SLOT_OFFSET) as *const *const ());
549 if !slot.is_null() {
550 ptr::write(
551 UnsafeCell::raw_get(slot as *const UnsafeCell<*const ()>),
552 dst as *const (),
553 );
554 }
555 on_slot(i, slot);
556 }
557 // `next` is the leading field of the link metadata.
558 cell = *(meta as *const *mut u8);
559 }
560 }
561
562 self.start = arr as *const ();
563 self.end = unsafe { arr.add(bytes) } as *const ();
564 self.state = LinkSectionState::Flattened as u8;
565 }
566
567 /// The flattened item range. Only valid once [`materialise_with`](Self::materialise_with) has run.
568 fn range(&self) -> SectionRange {
569 SectionRange::new(self.start, self.end)
570 }
571 }
572
573 /// A movable WASM link section and its backref storage.
574 #[repr(C)]
575 pub struct LinkSectionMovableInfo {
576 base: LinkSectionInfo,
577 backrefs_start: *const (),
578 backrefs_end: *const (),
579 }
580
581 const BACKREF_SIZE_OF: usize = ::core::mem::size_of::<crate::MovableBackref<()>>();
582 const BACKREF_ALIGN_OF: usize = ::core::mem::align_of::<crate::MovableBackref<()>>();
583
584 impl LinkSectionMovableInfo {
585 /// Create metadata for a movable WASM link section storing `T`.
586 pub const fn new<T: 'static>(name: &'static str) -> Self {
587 Self {
588 // Movable sections hand out `MovableRef`s, so cells carry a slot.
589 base: LinkSectionInfo::new::<T>(name, true),
590 backrefs_start: ptr::null(),
591 backrefs_end: ptr::null(),
592 }
593 }
594
595 /// The flattened backref range. Only valid once [`LinkSectionInfo::materialise_with`] has run.
596 fn backrefs_range(&self) -> SectionRange {
597 SectionRange::new(self.backrefs_start, self.backrefs_end)
598 }
599 }
600
601 /// What a WASM section exposes to the generic [`register`] / [`flatten`] shims.
602 ///
603 /// Implemented by [`LinkSectionInfo`] (plain) and [`LinkSectionMovableInfo`]
604 /// (which delegates to its `base`). The two implementations collapse the four
605 /// per-kind register/flatten entrypoints into two generic ones.
606 #[doc(hidden)]
607 pub trait WasmSection {
608 /// The intrusive-list head + value layout. [`register`] pushes onto it.
609 fn info_mut(&mut self) -> &mut LinkSectionInfo;
610
611 /// Materialise the section into contiguous storage. Idempotent.
612 fn materialise(&mut self);
613 }
614
615 impl WasmSection for LinkSectionInfo {
616 fn info_mut(&mut self) -> &mut LinkSectionInfo {
617 self
618 }
619 fn materialise(&mut self) {
620 LinkSectionInfo::materialise_with(self, |_, _| {});
621 }
622 }
623
624 impl WasmSection for LinkSectionMovableInfo {
625 fn info_mut(&mut self) -> &mut LinkSectionInfo {
626 &mut self.base
627 }
628 fn materialise(&mut self) {
629 if self.base.state == LinkSectionState::Flattened as u8 {
630 return;
631 }
632
633 let count = self.base.count;
634 let name = self.base.name;
635 let (backrefs, backref_bytes) = if count == 0 {
636 let dangling = NonNull::<u8>::dangling().as_ptr() as *const ();
637 (dangling as *mut u8, 0)
638 } else {
639 let backref_bytes = count
640 .checked_mul(BACKREF_SIZE_OF)
641 .unwrap_or_else(|| panic!("link section '{}' backref size overflow", name));
642 let backrefs = unsafe {
643 allocate(Layout::from_size_align(backref_bytes, BACKREF_ALIGN_OF).unwrap())
644 as *mut u8
645 };
646 if backrefs.is_null() {
647 panic!("link section '{}' backref allocation failed", name);
648 }
649 (backrefs, backref_bytes)
650 };
651
652 // Copy values and record a backref at each item's fixed-up slot. Writing
653 // a `MovableBackref` per item (rather than byte math into the array)
654 // states the `#[repr(C)]` layout invariant in code.
655 self.base.materialise_with(|i, slot| unsafe {
656 let br = (backrefs as *mut crate::MovableBackref<()>).add(i);
657 ptr::write(
658 br,
659 crate::MovableBackref::new(slot as *const UnsafeCell<*const ()>),
660 );
661 });
662
663 self.backrefs_start = backrefs as *const ();
664 self.backrefs_end = unsafe { backrefs.add(backref_bytes) } as *const ();
665 // `base.state = Flattened` is already set inside `materialise_with`.
666 }
667 }
668
669 /// Thread a cell onto the section's intrusive list.
670 ///
671 /// # Safety
672 ///
673 /// `info_ptr` must be the matching `LinkSectionInfoLock<S>` static (see
674 /// [`LinkSection::new`]) and `cell` the start of the item's `LinkCell` (see
675 /// [`LinkCell::as_cell_ptr`]). The cell's trailing meta must be [`LinkMetaSlot`]
676 /// iff the section was created with `has_slot`. Must run single-threaded,
677 /// pre-`main`, before the section is flattened.
678 pub unsafe fn register<S: WasmSection>(info_ptr: *const LinkSectionInfoLock<S>, cell: *mut u8) {
679 let link_section = unsafe { LinkSection::new(info_ptr) };
680 unsafe { link_section.lock().info_mut().push(cell) };
681 }
682
683 /// Flatten a section (called eagerly by the `.init_array.1` finalizer, and as
684 /// an idempotent backstop from `Ref`/`MovableRef` deref and section reads).
685 ///
686 /// # Safety
687 ///
688 /// `info_ptr` must be the section's `LinkSectionInfoLock<S>` static (see
689 /// [`LinkSection::new`]).
690 pub unsafe fn flatten<S: WasmSection>(info_ptr: *const LinkSectionInfoLock<S>) {
691 let link_section = unsafe { LinkSection::new(info_ptr) };
692 link_section.lock().materialise();
693 }
694
695 #[cfg(target_family = "wasm")]
696 unsafe fn allocate(layout: Layout) -> *mut () {
697 use alloc::alloc::alloc;
698
699 // SAFETY: `layout` has non-zero size (callers check `count > 0` before
700 // allocating).
701 unsafe { alloc(layout) as _ }
702 }
703
704 #[cfg(not(target_family = "wasm"))]
705 unsafe fn allocate(_layout: Layout) -> *mut () {
706 unreachable!("placeholder for non-WASM platforms")
707 }
708
709 /// Runtime bounds for a WASM link section, flattened lazily on first access.
710 pub struct Bounds(LinkSection<LinkSectionInfo>);
711
712 impl Bounds {
713 /// Create a new bounds struct.
714 ///
715 /// # Safety
716 ///
717 /// See [`LinkSection::new`]: `info_ptr` must be the section's
718 /// `LinkSectionInfoLock` static for the section's entire lifetime.
719 pub const unsafe fn new(info_ptr: *const LinkSectionInfoLock<LinkSectionInfo>) -> Self {
720 unsafe { Self(LinkSection::new(info_ptr)) }
721 }
722
723 /// Resolve the section into an immutable [`SectionRange`], materialising it
724 /// (idempotently) if some earlier access has not already done so.
725 ///
726 /// Takes the section lock; see [`MovableBounds::range`] for the contract.
727 pub fn range(&self) -> SectionRange {
728 let mut info = self.0.lock();
729 info.materialise();
730 info.range()
731 }
732 }
733
734 /// Runtime bounds for a WASM movable link section and its backref section.
735 pub struct MovableBounds(LinkSection<LinkSectionMovableInfo>);
736
737 impl MovableBounds {
738 /// Create a new movable bounds struct.
739 ///
740 /// # Safety
741 ///
742 /// See [`LinkSection::new`]: `info_ptr` must be the movable section's
743 /// `LinkSectionInfoLock` static for the section's entire lifetime.
744 pub const unsafe fn new(info_ptr: *const LinkSectionInfoLock<LinkSectionMovableInfo>) -> Self {
745 unsafe { Self(LinkSection::new(info_ptr)) }
746 }
747
748 /// Resolve the movable item section into an immutable [`SectionRange`],
749 /// materialising it (idempotently) if necessary.
750 ///
751 /// Each accessor takes the section lock once and flattens on first call;
752 /// later calls re-lock but skip the (idempotent) materialise work.
753 pub fn range(&self) -> SectionRange {
754 let mut info = self.0.lock();
755 info.materialise();
756 info.base.range()
757 }
758
759 /// Resolve the movable backref section into an immutable [`SectionRange`].
760 /// See [`Self::range`] for the lock/materialise contract.
761 pub fn backrefs_range(&self) -> SectionRange {
762 let mut info = self.0.lock();
763 info.materialise();
764 info.backrefs_range()
765 }
766 }
767
768 /// Platform storage backing a [`crate::Ref`] on WASM: a lazily-populated pointer
769 /// slot plus the owning section for the flatten backstop. `ptr` is the first
770 /// field, so the registration slot (`&Ref`) points straight at it.
771 ///
772 /// Synchronization: the slot is written once, pre-`main`, under the section
773 /// lock by `materialise`, and read post-`main` via [`Self::get`]. The pre-`main`
774 /// write happens-before any post-`main` read through whatever thread-spawn edge
775 /// a multi-threaded WASM target uses (e.g. `wasm32-wasip2`'s `thread.spawn`,
776 /// `wasm32-wasip1-threads`, or shared-memory workers), so the non-atomic
777 /// `UnsafeCell` access is sound under the documented single-threaded-pre-`main`
778 /// contract. [`MovableRefStorage`] has the same shape; its post-`main` writes
779 /// (via `sort_unstable`) are governed by the section's exclusive-access
780 /// contract.
781 #[repr(C)]
782 pub struct RefStorage<T: 'static> {
783 ptr: UnsafeCell<*const T>,
784 section: *const LinkSectionInfoLock<LinkSectionInfo>,
785 }
786
787 impl<T> RefStorage<T> {
788 /// Storage for a `Ref` into `section`, resolved lazily on first deref.
789 pub const fn new(section: *const LinkSectionInfoLock<LinkSectionInfo>) -> Self {
790 Self {
791 ptr: UnsafeCell::new(ptr::null()),
792 section,
793 }
794 }
795
796 /// The item pointer, read without flattening ([`Self::get`] flattens first).
797 pub fn as_ptr(&self) -> *const T {
798 unsafe { *self.ptr.get() }
799 }
800
801 /// Resolve to the item, flattening the section on first touch as an
802 /// idempotent backstop for a `#[ctor(priority = 1)]` that runs before the
803 /// `.init_array.1` finalizer.
804 pub fn get(&self) -> &T {
805 unsafe {
806 if (*self.ptr.get()).is_null() {
807 flatten(self.section);
808 }
809 self.as_ptr().as_ref().expect("Ref not initialized")
810 }
811 }
812 }
813
814 /// Platform storage backing a [`crate::MovableRef`] on WASM. See
815 /// [`RefStorage`] for the synchronization story; `slot` is the first field so
816 /// [`crate::MovableRef::slot_ptr`] is an offset-0 cast.
817 #[repr(C)]
818 pub struct MovableRefStorage<T: 'static> {
819 slot: SyncUnsafeCell<*const T>,
820 section: *const LinkSectionInfoLock<LinkSectionMovableInfo>,
821 }
822
823 impl<T> MovableRefStorage<T> {
824 /// Storage for a `MovableRef` into `section`, resolved lazily on first deref.
825 pub const fn new(
826 ptr: *const T,
827 section: *const LinkSectionInfoLock<LinkSectionMovableInfo>,
828 ) -> Self {
829 Self {
830 slot: SyncUnsafeCell::new(ptr),
831 section,
832 }
833 }
834
835 /// The current slot pointer, read without flattening ([`Self::get`] flattens first).
836 pub const fn as_ptr(&self) -> *const T {
837 unsafe { *self.slot.get() }
838 }
839
840 /// Resolve to the item, flattening the section on first touch as an
841 /// idempotent backstop. See [`RefStorage::get`].
842 pub fn get(&self) -> &T {
843 unsafe {
844 if (*self.slot.get()).is_null() {
845 flatten(self.section);
846 }
847 self.as_ptr().as_ref().expect("MovableRef not initialized")
848 }
849 }
850 }