[erlang-questions] Issue with using enif_binary_to_term
Sverker Eriksson
sverker.eriksson@REDACTED
Tue May 15 16:14:23 CEST 2018
This is a bug in enif_binary_to_term which causes heap corruption when the term
is an immediate (atom, small integer, pid, port, empty list).
This should fix it:
diff --git a/erts/emulator/beam/erl_nif.c b/erts/emulator/beam/erl_nif.c
index e208792..0fbf0eb 100644
--- a/erts/emulator/beam/erl_nif.c
+++ b/erts/emulator/beam/erl_nif.c
@@ -1255,8 +1255,10 @@ size_t enif_binary_to_term(ErlNifEnv *dst_env,
if (is_non_value(*term)) {
return 0;
}
- erts_factory_close(&factory);
- cache_env(dst_env);
+ if (size > 0) {
+ erts_factory_close(&factory);
+ cache_env(dst_env);
+ }
ASSERT(bp > data);
return bp - data;
Your usage looks correct. The only nitpick is to test the return value from
enif_binary_to_term, either to handle broken binary or assert it's correct.
/Sverker
On mån, 2018-05-14 at 22:57 +0200, Vincent Siliakus wrote:
> Hi all,
>
> I'm writing a NIF library and can't wrap my head around why the following code
> makes the erlang runtime hang when called from a shell:
>
> static ERL_NIF_TERM test(ErlNifEnv* env, int argc, const ERL_NIF_TERM
> argv[]) {
> ErlNifBinary bin;
>
> ERL_NIF_TERM list = enif_make_list(env, 0);
> ERL_NIF_TERM in_term = enif_make_uint(env, 42);
> ERL_NIF_TERM out_term1, out_term2, out_term3;
>
> enif_term_to_binary(env, in_term, &bin);
>
> enif_binary_to_term(env, bin.data, bin.size, &out_term1, 0);
> list = enif_make_list_cell(env, out_term1, list);
>
> enif_binary_to_term(env, bin.data, bin.size, &out_term2, 0);
> list = enif_make_list_cell(env, out_term2, list);
>
> enif_binary_to_term(env, bin.data, bin.size, &out_term3, 0);
> list = enif_make_list_cell(env, out_term3, list);
>
> return list;
> }
>
> The multiple calls to enif_binary_to_term somehow seem to corrupt memory in
> the calling environment, so I'm probably using it incorrectly. Could some kind
> soul point me to the error? I'm running this code on OTP20 / erts-9.2.
>
> Thanks in advance,
> Vincent
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
More information about the erlang-questions
mailing list