Static ctors in wasm

kinke noone at nowhere.com
Fri Feb 9 00:48:47 UTC 2024


On Friday, 9 February 2024 at 00:02:12 UTC, H. S. Teoh wrote:
> How are static ctors actually implemented in D?  I was under 
> the impression that there's some kind of table stored in the 
> executable that the druntime startup code traverses. But 
> apparently this is OS-dependent??  I'm trying to get static 
> ctors to work in wasm, but can't find any way of making it 
> work. The druntime code that I looked into all hook into stuff 
> dependent on the executable format, and obviously there isn't 
> anything for wasm (yet).

It primarily depends on the binary format, and is a cooperation 
between compiler and druntime. Usually, the compiler emits 
non-linker-strippable pointers to compiler-generated `ModuleInfo` 
structs into a special section (`__minfo`, `.minfo` or so), one 
for each .d module getting compiled into a specific object file. 
After linking to an executable/shared library, the ModuleInfo 
pointers of *all* .d modules of *each linked* object file are 
then stored consecutively in that named section of the data 
segment. This way, druntime can then reflect on all D 
modules/ModuleInfos linked into a binary, by getting that data 
range of ModuleInfo pointers (e.g., via linker-generated 
`__{start,stop}___minfo` bracketing symbols for ELF). And from 
there, module ctors, unittests etc. can be inferred.

> Is this even possible in wasm?  Or am I missing something 
> obvious?

LDC has a fallback for exotic platforms, where it uses a linked 
list, and compiler-generated CRT-constructor functions which 
insert the ModuleInfo pointers at program initialization (in 
undefined order), invoked by the C runtime before C main(). So if 
wasm doesn't support named sections/data ranges, but would 
'implicitly' support initializer functions (CRT constructors), 
that could be a potential route to take.


More information about the Digitalmars-d mailing list