[erlang-questions] enif_send rules questions
Thu Jan 12 20:21:57 CET 2017
The documentation for enif_send says this:
The environment of the calling process. Must be NULL only if
calling from a created thread.
I have a few questions about this.
1. What is "the environment of the calling process"? Does that mean the
environment that was passed to the NIF?
2. What is a "created thread"?
3. Is it really invalid to do this from a NIF call -- unless I spawn a
separate thread to do it, and then it's OK?
NIF_ENV msg_env = enif_alloc_env();
NIF_TERM msg = enif_make_int(env, 1);
enif_send(NULL, &pid, msg_env, msg);
4. We suspect it's actually totally safe to pass a process-independent
environment as the first parameter, regardless of whether there's a
"calling process" or we're "calling from a created thread". Is it?
If so, would you accept a patch to document that that's OK?
Background: I'm working on Rustler, a library for writing Erlang NIFs in
the Rust programming language. Rustler aims to be safe: Rustler NIFs
can't trigger undefined behavior or crash the VM, as long as you avoid
Rust's `unsafe` keyword. If you manage to crash, it's not your bug. It's
This means Rustler must enforce all "erl_nif.h" API usage rules.
We can enforce most rules with zero overhead. \o/ In a few cases, we add
a runtime check. But `enif_send` is different. We have to know whether
or not we're in a "created thread". If not, we have to know "the
environment of the calling process", because passing any other
environment would be illegal. That imposes a bit of overhead on every
NIF call -- on entry, we have to stash the env in thread-local storage.
I measured, and on Linux, it costs about 133ns per NIF call. Not awful,
but we'd have to impose that on everyone, whether they use `enif_send`
or not. So I thought I'd ask. The changes proposed in question #4 would
eliminate the need for this overhead, because all environments would
always be OK for sending.
Thanks for reading!
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the erlang-questions