1

Part of my tries to understand why my code is hanging when running in different OS, I had to debug different eclipse plugins. I saw the following code in some Java file:

Library.loadLibrary("swt")

Based on What are native methods in Java and where should they be used?, I understand that native methods are used to execute functions written in different programming languages. But I have two question regarding it:

  1. When loadLibrary is called with the input "swt", what actually happens? Where loadLibrary looks for SWT library and how can I change it? What is the equivalent command in Linux to get the library (I guess it's some shared library)?
  2. Consider the following code:
    public static final native void _gtk_widget_destroy(long /*int*/ widget);
    public static final void gtk_widget_destroy(long /*int*/ widget) {
        lock.lock();
        try {
            _gtk_widget_destroy(widget);
        } finally {
            lock.unlock();
        }
   }

The _gtk_widget_destroy method is native. Does it mean that there is a method in another language (probably C) that is called _gtk_widget_destroy? How do I know from which library this method is coming from (maybe SWT)?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • On java 15 and later, you can use the flag `-Xlog:library=info` to print info about library and native method loading. That will show you which library contains the implementation for the native method. – Jorn Vernee May 30 '22 at 21:35
  • @JornVernee Unfortunately we are using OpenJDK 8 – vesii May 31 '22 at 07:23

1 Answers1

1

System.loadLibrary("X") uses System#mapLibraryName to construct the actual library name. On Linux this is libX.so, on Mac it would be libX.dylib, and on Windows it is libX.dll.

It then searches for a library with that name in each entry of java.library.path (a VM property).

For your second question: you need the full namespace and class name of the surrounding class as well. A quick search tells me the full name of that method is org.eclipse.swt.internal.gtk.GTK#_gtk_widget_destroy. Now, there are two options:

  • Either libswt.so calls RegisterNatives to bind this method to a function pointer (typically in its JNI_OnLoad method.) This is not the case.
  • It uses the common name mangling scheme, which would result in a symbol with the name Java__org_eclipse_swt_internal_gtk_GTK_1gtk_1widget_1destroy. It seems the developers have abstracted that long name into a macro. You can use the standard nm tool to determine whether a given .so file contains that symbol.
user207421
  • 305,947
  • 44
  • 307
  • 483
Botje
  • 26,269
  • 3
  • 31
  • 41