shared libraries in D

Iain Buclaw ibuclaw at ubuntu.com
Mon Feb 14 04:45:18 PST 2011


So I've been prototyping, and have built a fully working shared D2
druntime/phobos library on Linux (will come to caveats in a moment). Just for
sake of visual proof.

[iain at natty gdc]$ cat hello.d
import std.stdio;
void main()
{
    writeln("Hello World");
}
[iain at natty gdc]$ gdc hello.d -lrt -ldl # Never needed these before...
[iain at natty gdc]$ du -hs a.out
8.0K	a.out
[iain at natty gdc]$ ldd a.out
	linux-gate.so.1 =>  (0x00a32000)
	librt.so.1 => /lib/librt.so.1 (0x00c32000)
	libdl.so.2 => /lib/libdl.so.2 (0x00914000)
	libgphobos2 => /usr/local/lib/libgphobos2 (0x0050d000)
	libgdruntime => /usr/local/lib/libgdruntime (0x00a90000)
	libm.so.6 => /lib/libm.so.6 (0x00921000)
	libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00e8f000)
	libpthread.so.0 => /lib/libpthread.so.0 (0x007b9000)
	libc.so.6 => /lib/libc.so.6 (0x00110000)
	/lib/ld-linux.so.2 (0x00f07000)



Now, what's the catch?

The curent catch is that *none* of the external static ctors/dtors are called,
because the linked module list (_Dmodule_ref) is generated before the program
enters C main, thus before the shared druntime and phobos libraries have been
loaded into memory (don't know if this is the same for DMD, but I'll assume
that will likely be the case too).

Breakpoint 1, hello.__modinit() () at hello.d:1
(gdb) bt
#0  hello.__modinit() () at hello.d:1
#1  0x0804889d in __do_global_ctors_aux ()
#2  0x080485d0 in _init ()
#3  0x08048829 in __libc_csu_init ()
#4  0x003a8c84 in __libc_start_main () from /lib/libc.so.6
#5  0x08048661 in _start ()


Each modules own __modinit() is written out as such:

  struct _modref_t {
      _modref_t  * next;
      ModuleInfo m;
  }
  extern (C) _modref_t * _Dmodule_ref;
  private _modref_t our_mod_ref =
    { next: null, m: _ModuleInfo_xxx };
  void ___modinit() { // a static constructor
     our_mod_ref.next = _Dmodule_ref;
     _Dmodule_ref = & our_mod_ref;
  }

These functions are created by the compiler, and inserted into the .ctor list.

Before I progress, posting to ask if anyone has any good implementation ideas
to get this fully functional?

Regards
Iain


More information about the Digitalmars-d mailing list