Is it possible to dynamically load a @safe function from a shared library ?

H. S. Teoh hsteoh at
Fri Mar 13 21:04:59 UTC 2020

On Fri, Mar 13, 2020 at 08:22:53PM +0000, wjoe via Digitalmars-d-learn wrote:
> So from what I understand, because, at least on Posix, since there's
> only a symbol name there's nothing I can do in my loader to verify
> that a function is or does what it claim to be/do.

As far as I know, it's the same thing on Windows PE format.

Basically, once your code is compiled down to the object file level,
there really isn't anything at the level of higher programming language
concepts anymore, like type signatures and stuff.  As far as object
files are concerned, it's just a bunch of opaque binary data with string
labels tacked on them, plus some extra information like relocation data
and other such OS-level concepts.  What's in that opaque binary data
isn't really the purview of the object file format; things like types
and function signatures are an interpretation laid upon the data by
higher-level application code. The OS doesn't know what it is, and
doesn't care (nor should it, that's not its job).

So given some arbitrary object file, there's really no real guarantee as
to what the contents are inside.  Anybody can craft an object file that
exports symbol names that look like the symbols generated by some
higher-level programming language, but the actual binary data the names
point to may do something completely different.  In fact, this is
exactly why pragma(mangle) is so useful: Adam Ruppe's jni.d, for
example, makes extensive use of this in order to make the D code inside
the object file appear like Java JNI symbols to the JVM.  D's C++
interop is also based on the same concept: export symbols that look like
C++ mangled symbols, but inside is actually D code, not C++ code.

Far from being "disappointing", I think this stuff is very powerful, and
lots of fun if you do it right.  But it does come with the caveat that
you're essentially meddling around under the hood, so it's your
responsibility not to do something that will cause the engine to blow
up.  Hence the @trusted tag.


Never step over a puddle, always step around it. Chances are that whatever made it is still dripping.

More information about the Digitalmars-d-learn mailing list