Java call C library using native-image from GraalVM - java

I have a simple project: https://github.com/MarcoLunar/native-pid-test
All what it is doing is calling getpid from C library. Project is as simple as:
public static void main(String[] args) throws Exception {
System.out.println("start");
C_lib cLib = Native.loadLibrary("c", C_lib.class);
int getpid = cLib.getpid();
System.out.println("pid = " + getpid);
System.out.println("end");
}
When launching from IDE everything works fine:
start
pid = 155080
end
When trying to build using native-image from GraalVM I got this error:
[simpletest:155323] compile: 2,597.81 ms, 2.05 GB
Fatal error:org.graalvm.compiler.graph.GraalGraphError: java.lang.NullPointerException
at node: 43|&
at method: Object com.oracle.svm.reflect.JNIGeneratedMethodSupport_getFieldOffsetFromId_5041c78d77a7b3d62103393b72fc35d80d2cc709.invoke(Object, Object[])
at org.graalvm.compiler.phases.common.CanonicalizerPhase$Instance.tryCanonicalize(CanonicalizerPhase.java:397)
at org.graalvm.compiler.phases.common.CanonicalizerPhase$Instance.processNode(CanonicalizerPhase.java:325)
at org.graalvm.compiler.phases.common.CanonicalizerPhase$Instance.processWorkSet(CanonicalizerPhase.java:302)
at org.graalvm.compiler.phases.common.CanonicalizerPhase$Instance.run(CanonicalizerPhase.java:264)
at org.graalvm.compiler.phases.common.CanonicalizerPhase.run(CanonicalizerPhase.java:177)
at org.graalvm.compiler.phases.common.CanonicalizerPhase.run(CanonicalizerPhase.java:73)
at org.graalvm.compiler.phases.BasePhase.apply(BasePhase.java:214)
at org.graalvm.compiler.phases.BasePhase.apply(BasePhase.java:147)
at com.oracle.svm.hosted.code.CompileQueue.doInlineTrivial(CompileQueue.java:587)
at com.oracle.svm.hosted.code.CompileQueue.access$000(CompileQueue.java:156)
at com.oracle.svm.hosted.code.CompileQueue$TrivialInlineTask.run(CompileQueue.java:284)
at com.oracle.graal.pointsto.util.CompletionExecutor.lambda$execute$0(CompletionExecutor.java:173)
at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1402)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: java.lang.NullPointerException
at org.graalvm.compiler.nodes.calc.BinaryArithmeticNode.tryConstantFold(BinaryArithmeticNode.java:120)
I have tried many times, many different solutions ... but for now I have no more to check.
I am asking for help in repairing the project. I think this is possible, because with some configurations I have the same error as in https: //github.com/oracle/graal/issues/2261 ... where someone fixed it ... but didn't write the solution: (

I think currently JNA doesn't work in native image. You can use JNI if that's possible. Or you can use another interface to native code that will work specifically in the native images. Some info can be found in the javadoc of org.graalvm.nativeimage.c and its subpackages: https://www.graalvm.org/sdk/javadoc/index.html?org/graalvm/nativeimage/c/package-summary.html
Here's an example of using it: https://www.praj.in/posts/2020/opengl-demo-using-graalvm/

Related

ZetaSQL Sample Using Apache beam

I am Facing Issues while Using ZetaSQL in Apache beam Framework (2.17.0-SNAPSHOT). After Going through documentation of the apache beam I am not able to find any sample for ZetaSQL.
I tried to add the Planner:
options.setPlannerName("org.apache.beam.sdk.extensions.sql.zetasql.ZetaSQLQueryPlanner");
But Still Facing Issue, Snippet is added below for help.
```
String sql =
"SELECT CAST (1243 as INT64), "
+ "CAST ('2018-09-15 12:59:59.000000+00' as TIMESTAMP), "
+ "CAST ('string' as STRING);";
ZetaSQLQueryPlanner zetaSQLQueryPlanner = new ZetaSQLQueryPlanner();
BeamRelNode beamRelNode = zetaSQLQueryPlanner.convertToBeamRel(sql);
PCollection<Row> stream = BeamSqlRelUtils.toPCollection(p, beamRelNode);
p.run();
I Understand we need the below Snippet but failed to create the config
Frameworks.newConfigBuilder()
and while Running Code I found below Exceptions:
Exception in thread "main" java.util.ServiceConfigurationError: com.google.zetasql.ClientChannelProvider: Provider com.google.zetasql.JniChannelProvider could not be instantiated
at java.util.ServiceLoader.fail(Unknown Source)
at java.util.ServiceLoader.access$100(Unknown Source)
at java.util.ServiceLoader$LazyIterator.nextService(Unknown Source)
Update: as of 06/23/2020, Beam ZetaSQL is supported on Mac OS as well (not all versions but at least most recent ones)!
====
I think it is related to your OS. Beam is as unified framework but your exception looks from its dependency: ZetaSQL parser. If you change to a newer version of linux I think your code snippet should work.

Weka DiscriminantAnalysis NoClassDefFoundError

I'm trying to use MultiClassFLDA in discriminant analysis package but I always get an error on running the code and defining a new instance of the MultiClassFLDA class
Exception in thread "main" java.lang.NoClassDefFoundError: no/uib/cipr/matrix/Vector
at assignment2.face.tryLDA(face.java:141)
at assignment2.Assignment2.main(Assignment2.java:106)
Caused by: java.lang.ClassNotFoundException: no.uib.cipr.matrix.Vector
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
It seems to be linked to some dynamic class loading in newer versions of Weka, presumably within the Weka Package Manager: that class is defined in the mtj.jar, which is bundled inside weka.jar. In that other question, an answer suggested to extract the mtj.jar and add it to your classpath.
As I didn't have this problem with other Filters, my guess is that MultiClassFLDA is not implemented correctly: I found out is that if you use another Filter before, that specific class will get loaded:
// Run a dummy Filter for correct initialization
Filter f = new Standardize();
f.setInputFormat(data);
Filter.useFilter(new Instances("", params, 0), f); // Dummy run on empty dataset
// Now run the MultiClassFLDA
f = new MultiClassFLDA();
f.setInputFormat(data);
data = Filter.useFilter(data, f);
N.B. that is a really ugly hack! I used it to be able to work. I'll edit my answer when I find the appropriate way to do it (other than extracting the jar from Weka itslef).

JNA - Ubuntu - XGetInputFocus

OS: Ubuntu 16.04
JNA: 4.2.X
JDK: 1.8.0u111
I'm trying to get the currently focused window programmaticaly on a JavaFX application.
if (Platform.isLinux()) {
final X11 x11 = X11.INSTANCE;
final XLib xlib = XLib.INSTANCE;
X11.Display display = x11.XOpenDisplay(null);
X11.Window window = new X11.Window();
Pointer pointer = Pointer.NULL;
xlib.XGetInputFocus(display, window, pointer); // << ERROR
X11.XTextProperty name = new X11.XTextProperty();
x11.XGetWMName(display, window, name);
System.out.println(name.toString());
}
public interface XLib extends StdCallLibrary {
XLib INSTANCE = (XLib) Native.loadLibrary("/usr/lib/x86_64-linux-gnu/libX11.so", XLib.class);
int XGetInputFocus(X11.Display display, X11.Window focus_return, Pointer revert_to_return);
}
But it doesn't work and throws this exception :
java.lang.IllegalArgumentException: Unrecognized calling convention: 63
at com.sun.jna.Native.invokeInt(Native Method)
at com.sun.jna.Function.invoke(Function.java:390)
at com.sun.jna.Function.invoke(Function.java:323)
at com.sun.jna.Library$Handler.invoke(Library.java:236)
at com.sun.proxy.$Proxy1.XGetInputFocus(Unknown Source)
at application.Main.start(Main.java:33)
Is this line correct ?
XLib INSTANCE = (XLib) Native.loadLibrary("/usr/lib/x86_64-linux-gnu/libX11.so", XLib.class);
I tested with an older version of JNA (4.1.X) and the error changed for :
Unrecognized calling convention: 1
Debug log with -Djna.debug_load=true
Looking in classpath from sun.misc.Launcher$AppClassLoader#73d16e93 for /com/sun/jna/linux-x86-64/libjnidispatch.so
Found library resource at jar:file:/home/puglic/eclipse/jna-4.2.2.jar!/com/sun/jna/linux-x86-64/libjnidispatch.so
Looking for library 'X11'
Adding paths from jna.library.path: null
Trying libX11.so
Found library 'X11' at libX11.so
Looking for library 'X11'
Adding paths from jna.library.path: null
Trying libX11.so
Found library 'X11' at libX11.so
java.lang.IllegalArgumentException: Unrecognized calling convention: 63
Your XLib definition uses StdCallLibrary, which only makes sense on 32-bit windows systems. It should simply be Library, or derive from the JNA contrib-defined version.
You're basically asking for a calling convention that does not exist.

Why does java.lang.VerifyError mean?

While I've tried to use the following code snippet with the Groovy in-operator explanation the VerifyError has occured. Have you guys any idea about?
The code and console output is below.
class Hello extends ArrayList {
boolean isCase(Object val) {
return val == 66
}
static void main(args) {
def myList = new Hello()
myList << 55
assert 66 in myList
assert !myList.contains(66)
}
}
The error log:
Exception in thread "main" java.lang.VerifyError: (class: Hello, method: super$1$stream signature: ()Ljava/util/stream/Stream;) Illegal use of nonvirtual function call
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:259)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:116)
The code origin from the topic How does the Groovy in operator work?.
Update:
Groovy Version: 1.8.6 JVM: 1.6.0_45 Vendor: Sun Microsystems Inc. OS: Linux
Check this out.
It's for Java, but generally problem is, that you are using wrong library versions. The class is there, but different version than expected.
http://craftingjava.blogspot.co.uk/2012/08/3-reasons-for-javalangverfiyerror.html
Probably you have messed up Groovy or Java SDK installations.

IncompatibleClassChangeError in Java

After learning Lambda Expressions in Java, I tried to practice some simple examples. But in my first example only I am getting the following error.
Exception in thread "main" java.lang.IncompatibleClassChangeError
at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:384)
at com.example.lambda.HelloLambda.main(HelloLambda.java:15)
Caused by: java.lang.NoSuchMethodException: no such method: java.lang.invoke.LambdaMetafactory.metaFactory(Lookup,String,MethodType,MethodHandle,MethodHandle,MethodType)CallSite/invokeStatic
at java.lang.invoke.MemberName.makeAccessException(MemberName.java:763)
at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:880)
at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1019)
at java.lang.invoke.MethodHandles$Lookup.linkMethodHandleConstant(MethodHandles.java:1284)
at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:382)
... 1 more
Caused by: java.lang.NoSuchMethodError: java.lang.invoke.LambdaMetafactory.metaFactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;
at java.lang.invoke.MethodHandleNatives.resolve(Native Method)
at java.lang.invoke.MemberName$Factory.resolve(MemberName.java:852)
at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:877)
... 4 more
The error seems an error because of backward compatibility issue. But don't know how to fix this. Many answers in StackOverFlow suggested Recompilation could fix this issue. But still I am getting this error.
My code
package com.example.lambda;
public class HelloLambda {
static String firstname = "ChanSek";
static String lastname = "Nayak";
interface HelloService {
String hello();
}
public static void main(String[] args) {
HelloService helloService =
() -> {String hello="Hello " + firstname + " " + lastname;
return hello;};
System.out.println(helloService.hello());
}
}
The code compiles fine. But running gives the above mentioned error.
I am using JDK1.8.0 snapshot.
Is it possibly because of this?
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=8019635
The way lambdas have been done in Java 8 has changed, very recently (07/2013), in a not backwards compatible way.
If you've somehow managed to compile with a compiler which talks PRE beta 103 lambdas, but are running with a JRE of POST 103 lambdas, you'll have problems.
(The hint for me here is that the metafactory name used to be mixed case, but in java 1.8.0 beta 103 appears to be lower case - you're searching for mixed case, but not finding it.)

Categories

Resources