I'm trying to use jnim to compile a shared library which can be used from Java 
via JNI. I have a minimal example in this [debug 
branch](https://github.com/bluenote10/JniScalaNimExample/tree/debug).

On the Java side the code is:
    
    
    public class NativeTest {
        
        public native static void run();
        
        public static void main(String[] args) {
            System.loadLibrary("nativetest");
            NativeTest.run();
        }
    
    }
    

On the Nim side it is just:
    
    
    import jnim
    
    proc Java_NativeTest_run*(env: JNIEnvPtr, obj: jobject) {. cdecl, exportc, 
dynlib .} =
      system.setupForeignThreadGc()
      echo "Printing from JNI..."
    

In general this works nicely, but unfortunately I'm getting random segfaults, 
with a <5% probability in this example.

I'm compiling it using `nim --app:lib -o:libnativetest.so --threads:on c 
native.nim`. In the first attempt I was omitting the 
`system.setupForeignThreadGc()` (and not enabling threads). @yglukhov suggested 
that there might be something wrong related to initializing TLS, so this was 
the first thing that came to my mind.

To rule out that it is a general JVM bug, I was doing the same using a C 
implementation. This does not seem to cause segfaults, so I think I might be 
doing something wrong here. Any ideas how to fix this?

The gdb stacktrace isn't particularly helpful to me either: 
    
    
    Program received signal SIGSEGV, Segmentation fault.
    [Switching to Thread 0x7ffff7fc2700 (LWP 14740)]
    0x00007fffe10002b4 in ?? ()
    (gdb) where
    #0  0x00007fffe10002b4 in ?? ()
    #1  0x0000000000000246 in ?? ()
    #2  0x00007fffe1000160 in ?? ()
    #3  0x00007ffff7392bf0 in VM_Operation::_names () from 
/home/fabian/bin/jdk1.8.0_74/jre/lib/amd64/server/libjvm.so
    #4  0x00007ffff7fc1980 in ?? ()
    #5  0x00007ffff6ec5d2d in VM_Version::get_processor_features() () from 
/home/fabian/bin/jdk1.8.0_74/jre/lib/amd64/server/libjvm.so
    Backtrace stopped: previous frame inner to this frame (corrupt stack?)
    (gdb) list
    1   events.c: No such file or directory.
    

Reply via email to