NIF calls to enif_fprintf causing segfaults on Windows

7 views
Skip to first unread message

Brett Hemes

unread,
Jul 26, 2021, 5:27:31 PMJul 26
to erlang-q...@erlang.org

I have recently moved from a Linux environment to Windows and my NIFs that call `enif_fprintf` are causing segfaults.

 

A simple call such as `enif_fprintf(stdout, “Hello, world!\n”);` will cause issue.

 

My build setup is:

* Windows 10

* rebar3

* MSYS2 + MinGW 64-bit + gcc

 

I have tried in both `erl` and `werl` to the same effect as well as `stdout` and `stderr`...

 

Does anyone have any insight into what might be the issue?

 

Thanks,

Brett

Jaka Bac

unread,
Jul 27, 2021, 7:32:03 AMJul 27
to Brett Hemes, erlang-q...@erlang.org
Just thinking out loud...

Is the segfault a null pointer dereference?
It is possible that stdout is not what MinGW runtime expects it to be and is possibly null.
Windows Erlang is built by MSVC and it will run the MSVC CRT initialization code (which will set up stdout). Your NIF DLL is built by MinGW. And its CRT initialization possibly did not run or did not run correctly which in turn leaves the MinGW stdout undefined.

Jaka

Brett Hemes

unread,
Jul 27, 2021, 9:26:09 AMJul 27
to Jaka Bac, erlang-q...@erlang.org

Interesting...  so I put together a Windows native make file to use cl.exe (vs gcc) from within a Visual Studio developer prompt and in this scenario the segfaults are gone but I don’t get any output to the terminal at all.

 

Brett

Jaka Bac

unread,
Jul 27, 2021, 9:45:49 AMJul 27
to Brett Hemes, erlang-q...@erlang.org
Are you running erlang with werl.exe? 
In this case Erlang is started as a Windows application (not a console one) and writing to stdout will not have any effect. If this is the case, try to run your app with erl.exe

What version of MSVC did you use to build your NIF? Keep in mind that MSVC 2015-2019 have a common CRT, anything older has its own separate incompatible CRT. So you may run into a similar problem where you have 2 MSVC CRTs loaded in your app, which don't play nice together. Sharing non-trivial data between MSVC CRT implementations is considered undefined.

Erlang 24.x is built with MSVC 2019, so it is using the common 2015-2019 CRT

Jaka

Brett Hemes

unread,
Jul 29, 2021, 1:57:56 PMJul 29
to Jaka Bac, erlang-q...@erlang.org

I made sure to try in just erl.exe.  I am using MSVC 2017 so that should be OK too...  At this point I am just rolling with all the stdout/stderr fprintf’s commented out.  On this note, does anyone have any good tip for debugging NIFs in general?  It is not immediately clear to me how one would get a debugging session going with something like GDB while using Erlang/rebar3.

 

Thanks,

Reply all
Reply to author
Forward
0 new messages