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