I have a C (navive) program and a jar file with the main() method. From my native program I am initializing the JVM, and calling the main() method. I have no problems with this, everything is completely fine. But then I wanted to call back a C function from my java code.
The C function is defined in the native code in the same module as the one, that have created the JVM. The header is auto-generated, and the body is as simple as this:
JNIEXPORT void JNICALL Java_eu_raman_chakhouski_NativeUpdaterBus_connect0(JNIEnv* env, jclass clazz)
{
return;
}
So, from the java code I'm calling NativeUpdaterBus.connect0(), continuosly getting an UnsatisfiedLinkError. I have no System.loadLibrary() calls in my java code, because I thought, that there will be no problems calling the native code back from the java code if the target module is (possibly?) already loaded.
Well, maybe my approach is completely incorrect, but I can't see any obvious defects, maybe you could help?
What possibly could help (but I didn't tried any of these approaches, because I'm still not quite sure)
Use a kind of a "trampoline" dynamic library with these JNI methods, load it from the java code, then marshal native calls through it.
Define a java.lang.Runnable's anonymous inheritor, created with jni_env->DefineClass() but this involves some bytecode trickery.
Use an another, less invasive approach, like sockets, named pipes, etc. But in my case I'm using only one native process, so this might be an overkill.
I'm using OpenJDK 11.0.3 and Windows 10. My C program is compiled with the Microsoft cl.exe 19.16.27031.1 for x64 (Visual Studio 2017).
One possibility, as others have already mentioned, is to create a shared library (.dll) and call it from the native code and from Java to exchange data.
However, if you want to callback to a C function defined in the native code in the same module as the one the JVM originally created, you can use RegisterNatives.
Simple Example
C program creates JVM
it calls a Main of a class
the Java Main calls back a C function named connect0 in the calling C code
to have a test case the native C function constructs a Java string and returns it
the Java side prints the result
Java
package com.software7.test;
public class Main {
private native String connect0() ;
public static void main(String[] args) {
Main m = new Main();
m.makeTest(args);
}
private void makeTest(String[] args) {
System.out.println("Java: main called");
for (String arg : args) {
System.out.println(" -> Java: argument: '" + arg + "'");
}
String res = connect0(); //callback into native code
System.out.println("Java: result of connect0() is '" + res + "'"); //process returned String
}
}
C Program
One can create the Java VM in C as shown here
(works not only with cygwin but still with VS 2019) and then register with RegisterNatives native C callbacks. So using the function invoke_class from the link above it could look like this:
#include <stdio.h>
#include <windows.h>
#include <jni.h>
#include <stdlib.h>
#include <stdbool.h>
...
void invoke_class(JNIEnv* env) {
jclass helloWorldClass;
jmethodID mainMethod;
jobjectArray applicationArgs;
jstring applicationArg0;
helloWorldClass = (*env)->FindClass(env, "com/software7/test/Main");
mainMethod = (*env)->GetStaticMethodID(env, helloWorldClass, "main", "([Ljava/lang/String;)V");
applicationArgs = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env, "java/lang/String"), NULL);
applicationArg0 = (*env)->NewStringUTF(env, "one argument");
(*env)->SetObjectArrayElement(env, applicationArgs, 0, applicationArg0);
(*env)->CallStaticVoidMethod(env, helloWorldClass, mainMethod, applicationArgs);
}
jstring connect0(JNIEnv* env, jobject thiz);
static JNINativeMethod native_methods[] = {
{ "connect0", "()Ljava/lang/String;", (void*)connect0 },
};
jstring connect0(JNIEnv* env, jobject thiz) {
printf("C: connect0 called\n");
return (*env)->NewStringUTF(env, "Some Result!!");
}
static bool register_native_methods(JNIEnv* env) {
jclass clazz = (*env)->FindClass(env, "com/software7/test/Main");
if (clazz == NULL) {
return false;
}
int num_methods = sizeof(native_methods) / sizeof(native_methods[0]);
if ((*env)->RegisterNatives(env, clazz, native_methods, num_methods) < 0) {
return false;
}
return true;
}
int main() {
printf("C: Program starts, creating VM...\n");
JNIEnv* env = create_vm();
if (env == NULL) {
printf("C: creating JVM failed\n");
return 1;
}
if (!register_native_methods(env)) {
printf("C: registering native methods failed\n");
return 1;
}
invoke_class(env);
destroy_vm();
getchar();
return 0;
}
Result
Links
Creating a JVM from a C Program: http://www.inonit.com/cygwin/jni/invocationApi/c.html
Registering Native Methods: https://docs.oracle.com/en/java/javase/11/docs/specs/jni/functions.html#registering-native-methods
System.loadLibrary() is essential for the jni lookup to work. You also have a more flexible System.load() alternative.
Make sure that the native method implementation is declared with extern "C" and is not hidden by linker.
Related
1. Summarize the problem:
I would like to invoke a C# method by invoking a Java method to check license file. This license check is performed by using a C# dll. I'm using JNI and a C++ wrapper. I will provide necessary source code below.
The C# dll has a method public static string GetLicenseStatus() implemented which I wrote a wrapper for and now I'm trying to invoke this method from Java application.
I'm using jdk-17.0.2.8-hotspot from Eclipse Adoptium (64-bit) and IntelliJ IDEA as Java IDE and Visual Studio 2022 for C# project.
After Java method invocation I expect that it returns a String (number from 0-4, not valid, valid, expired, ...) but it results in a StackOverflowException when C# code is being executed/accessed.
2. Describe what you've tried
I also tried to return just a value in the C++ method without calling any C# code; this worked fine. So JNI <--> C++ wrapper is working fine.
Also I tried to run C# source code within a C# main class, that was also working fine. So there's no faulty C# code.
Good to know is maybe also that I tried to create an own C# dll to confirm that the issue is not related to the license dll (that's why I writing before about a "C# project in Visual Studio"). This dll is very basic and is just checking for dummy username & password. Even When I tried to just return true in the function, when invoking it from Java it resulted again in a StackOverflowException in Java IDE. Its running into this error when attempting to instantiate an object with gcnew. My own created C# class and also the C# license dll were added as reference in the C++ project.
Maybe also worth to mention:
The C# dll is relying on another dll to process license checking I assume.
I observed that Visual Studio for some reason doesn't recognise imported header files. I have to add them manually in visual Studio and copy paste code into the manual created file.
3. Show some code
"Authenticator.java":
package org.example;
public class Authenticator {
static {
System.loadLibrary("CppAuthenticator");
}
public native boolean authenticate(String username, String password);
public native String getLicenseStatus();
public static void main(String[] args) {
System.out.println("Program start");
Authenticator authenticator = new Authenticator();
System.out.println("Authenticator created");
/**boolean valid = authenticator.authenticate(args[0], args[1]);
System.out.println("Is valid?: "+valid);
if(!valid) {
System.err.println("Not valid!");
System.exit(1);
}
else {
System.out.println("Valid");
}**/
System.out.println("License Check...");
System.out.println("Status: "+authenticator.getLicenseStatus());
}
}
"CppAuthenticator.cpp"
#include "pch.h"
#include <msclr\marshal.h>
#include "CppAuthenticator.h"
#include "org_example_Authenticator.h"
// this is the main DLL file.
#include <string>
using System::Text::Encoding;
String^ toString(const char* chars) {
int len = (int)strlen(chars);
array<unsigned char>^ a = gcnew array<unsigned char> (len);
int i = 0;
while (i < len) {
a[i] = chars[i];
}
return Encoding::UTF8->GetString(a);
}
bool authenticate(const char* username, const char* password) {
SharpAuthenticator::Authenticator^ a = gcnew SharpAuthenticator::Authenticator(); // Fails here
return a->Authenticate(toString(username), toString(password));
}
JNIEXPORT jboolean JNICALL Java_org_example_Authenticator_authenticate
(JNIEnv* env, jobject c, jstring username, jstring password) {
jboolean isCopyUsername;
const char *c_username = env->GetStringUTFChars(username, &isCopyUsername);
jboolean isCopyPassword;
const char* c_password = env->GetStringUTFChars(password, &isCopyPassword);
jboolean result = authenticate(c_username, c_password);
env->ReleaseStringUTFChars(username, c_username);
env->ReleaseStringUTFChars(password, c_password);
return result;
}
String^ getLicenseStatus() {
return LicenseCheck::ValidateLicense::GetLicenseStatus(); // Fails here
}
JNIEXPORT jstring JNICALL Java_org_example_Authenticator_getLicenseStatus
(JNIEnv* env, jobject c) {
String^ cliString = getLicenseStatus();
msclr::interop::marshal_context context;
const char* utf8String = context.marshal_as<const char*>(cliString);
jstring result = env->NewStringUTF(utf8String);
return result;
}
"SharpAuthenticator.cs":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharpAuthenticator
{
public class Authenticator
{
public bool Authenticate(String username, String password)
{
return username == "user" && password == "pass";
}
public bool Authenticate1()
{
return false;
}
}
}
Here is the project structure I have in Visual Studio ("org_example_Authenticator.h" code was created with "javac -h ..."-command located in bin folder of JDK mentioned above.)
Here are the C++ project properties in Visual Studio:
Here are C# project properties for my own created dummy dll mentioned above:
It was a stupid mistake... It just cost me 1.5 days figuring out that I forgot to increment i in the while loop in toString method of "CppAuthenticator.cpp". Why these things always happen to me...? :D
Here the correct working method:
String^ toString(const char* chars) {
int len = (int)strlen(chars);
array<unsigned char>^ a = gcnew array<unsigned char> (len);
int i = 0;
while (i < len) {
a[i] = chars[i];
i++;
}
return Encoding::UTF8->GetString(a);
}
I'm at a total loss here. I'm trying to get a JVMTI agent library running but it keeps crashing for some reason.
I've narrowed it down this line:
(*jvm)->GetEnv(jvm, (void**)jvmti, JVMTI_VERSION_1_0);
this is the full code of the agent lib (in C):
#include <jvmti.h>
#include <stdlib.h>
jvmtiEnv* jvmti = NULL;
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)
{
printf("Agent started.\n");
_flushall();
jint err = (*jvm)->GetEnv(jvm, (void**)jvmti, JVMTI_VERSION_1_0);
if (err != JNI_OK)
{
printf("Failed to get JVMTI env!\n");
_flushall();
return err;
}
return JNI_OK;
}
JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* reserved)
{
return JNI_OK;
}
JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm)
{
}
As I tried to isolate what the issue was I wrote a very simple java app to test
this with:
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello from java!");
}
}
If I run this from netbeans with the VM arg -agentpath set to my .dllcontaining the code above, the app seems to crash when it tries to call GetEnv().
I've made sure of the following things:
- The JVM and the dll are both 64bit.
- The library is most definitely being found and loaded (the printf output is visible before the crash.)
I don't know what else could probably be causing this, do I have to link against some JVMTI API lib that I don't know about?
Or could this be an issue with the java installation on my PC?
Thanks
You should be passing address of jvmti to GetEnv() as in:
jint err = (*jvm)->GetEnv(jvm, (void**) &jvmti, JVMTI_VERSION_1_0);
In an Android app I have some JNI code that calls a java static method.
jbyteArray response = (jbyteArray)pEnv->CallObjectMethod(handlerClass, mid, jstrServiceUrl, jstrRequest);
Executing it in Android 5 in an ART environment, I get a check jni error:
JNI DETECTED ERROR IN APPLICATION: calling static method byte[] x.y.z(java.lang.String, java.lang.String) with CallObjectMethodV in call to CallObjectMethodV...
I don't get this error in Android 4 with a Dalvik environment.
The java method is this one:
public static byte[] z(String serviceURL, String request)
and is previously binded like this:
jclass handlerClass = pEnv->FindClass("x/y/z");
if (handlerClass == NULL) {
return -1;
}
mid = pEnv->GetStaticMethodID(handlerClass, "z", "(Ljava/lang/String;Ljava/lang/String;)[B");
if (mid == NULL) {
return -2;
}
// Construct Strings
jstring jstrServiceUrl = pEnv->NewStringUTF(szServiceURL);
jstring jstrRequest = pEnv->NewStringUTF(szRequest);
I don't know why your code worked with Dalvik, but the method id given to Call<type>Method must be obtained with GetMethodID. If you have a method id obtained with GetStaticMethodID you should use CallStatic<type>Method.
See the descriptions of Call<type>Method and CallStatic<type>Method in the JNI functions documentation.
I am trying to call a Java method from the code. C code listens to either Escape, Shift, Ctrl key press, then it calls the Java method telling which key was pressed. Following are the snippets that play a role in this.
C Snippet:
mid = (*env)->GetMethodID(env,cls,"callBack","(Ljava/lang/String;)V");
Env = env;
if(called)
switch(param) {
case VK_CONTROL:
printf("Control pressed !\n");
(*Env)->CallVoidMethodA(Env,Obj,mid,"11"); // calling the java method
break;
case VK_SHIFT:
printf("Shift pressed !\n");
(*Env)->CallVoidMethodA(Env,Obj,mid,"10"); // calling the java method
break;
case VK_ESCAPE:
printf("Escape pressed !\n");
(*Env)->CallVoidMethodA(Env,Obj,mid,"1B"); // calling the java method
break;
default:
printf("The default case\n");
break;
}
Java Snippet:
public void callBack(String key) {
String x = KeyEvent.getKeyText(Integer.parseInt(key, 16));
System.out.println(x);
}
When I run the program and press the Escape key I get this on the console:
Escape pressed !
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x5c8b809a, pid=7588, tid=8088
#
# JRE version: 7.0
# Java VM: Java HotSpot(TM) Client VM (20.0-b01 mixed mode, sharing windows-x86 )
# Problematic frame:
# V [jvm.dll+0x19809a]
#
# An error report file with more information is saved as:
# W:\UnderTest\NetbeansCurrent\KeyLoggerTester\build\classes\hs_err_pid7588.log
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
#
I know I am calling the Java function the wrong way, but I don't know where I am wrong. As from the output, it satisfies the case when I press the Escape key and then an unexpected error occurs.
Link to the LOG FILE
EDIT:
After the answer by mavroprovato I still get the same errors.
I edited this way:
(*Env)->CallVoidMethodA(Env,Obj,mid,(*Env)->NewStringUTF(Env,"1B"));
EDIT:
COMPLETE CODE version 1
COMPLETE CODE version 2
The JVM is crashing because the JNIEnv that is used is not a valid one. There are other issues with the code as well.
The Sun JNI documentation is providing very good information regarding threads.
Here comes some parts that are obvious:
Create a JNI_OnLoad function in your code. It will be called when the library is loaded. Then cache the JavaVM pointer because that is valid across threads. An alternative is to call (*env)->GetJavaVM in the initializeJNIVars function but I prefer the first one.
In your initializeJNIVars you can save the obj reference by calling Obj = (*env)->NewGlobalRef(obj).
In the LowLevelKeyboardProc you will have to get the env pointer:
AttachCurrentThread(JavaVM *jvm, JNIEnv &env, NULL);
Edit
OK, here are the code that you should add to get it working, I have tried it myself and it works. NB: I have not analyzed what your code is actually doing so I just did some fixes to get it working.
Add these variables among your other global variables:
static JavaVM *javaVM = NULL;
static jmethodID callbackMethod = NULL;
static jobject callbackObject = NULL;
You can remove your cls, mid, Env and Obj variables and use mine instead.
Create the JNI_OnLoad method where you cache the JavaVM pointer:
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
JNIEnv *env = 0;
if ((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_4)) {
return JNI_ERR;
}
javaVM = jvm;
return JNI_VERSION_1_4;
}
Alter your initializeJNIVars to look like the following:
void Java_keylogger_TestKeys_initializeJNIVars(JNIEnv *env, jobject obj) {
jclass cls = (*env)->GetObjectClass(env,obj);
callbackMethod = (*env)->GetMethodID(env, cls, "callBack", "(Ljava/lang/String;)V");
callbackObject = (*env)->NewGlobalRef(env, obj);
if(cls == NULL || callbackMethod == NULL) {
printf("One of them is null \n");
}
called = TRUE;
}
And finally in your LowLoevelKeyboardProc code you will have to add the following:
...
WPARAM param = kbhook->vkCode;
JNIEnv *env;
jint rs = (*javaVM)->AttachCurrentThread(javaVM, (void**)&env, NULL);
if (rs != JNI_OK) {
return NULL; // Or something appropriate...
}
...
case VK_ESCAPE:
printf("Escape pressed !\n");
jstring message = (*env)->NewStringUTF(env, "1B");
(*env)->CallVoidMethod(env, callbackObject, callbackMethod, message);
break;
...
In your unregisterWinHook you should delete the global reference so that objects can be GC'd.
...
(*env)->DeleteGlobalRef(env, callbackObject);
And that's it.
I believe you cannot call a java method that takes a String parameter and pass it a char*. You should call NewStringUTF first.
I think it is due to the UAC feature enabled on your Operating System. This was a bug for Java 6. Read this for further reference.
The reason I say this is because the event to the escape key is fired correctly and the problem only begins as soon as the call to the java method is done.
To support a static-analysis tool I want to instrument or monitor a Java program in such a way that I can determine for every reflective call (like Method.invoke(..)):
1.) which class C this method is invoked on, and
2.) which classloader loaded this class C.
Ideally I am looking for a solution that does not require me to statically modify the Java Runtime Library, i.e. I am looking for a load-time solution. However, the solution should be able to capture all reflective calls, even such calls that occur within the Java Runtime Library itself. (I played around with ClassFileTransformer but this seems to be applied only to classes that ClassFileTransformer itself does not depend on. In particular, a ClassFileTransfomer is not applied to the class "Class".)
Thanks!
Are you looking for something that can run in production? Or is it sufficient to instrument the application running in a test environment? If it's the latter, might want to consider running the application under a profiling tool. I've personally used and would recommend JProfiler, which lets you do call tracing and set up triggers to perform actions like logging when specific methods are invoked. It does not require any modifications to the hosted program and works just fine on the Java runtime library. There are open source tools, too, but I have not had as much success getting those to work.
If you need something that will run in production, you might want to investigate implementing your own custom Classloader or byte code manipulation via Javassist or CGLib, perhaps using AspectJ (AOP). That's obviously a more complication solution and I'm not sure it'll work without compile-time support, so hopefully the profiling tool is feasible for your situation.
The API that you are probably after is JVMTI. JVMTI allows you to register callbacks for the majority of events that occur within the JVM, including MethodEntry, MethodExit. You listen for those events and pull out the Method.invoke events. There are API calls to get the classloader for a specific class. However you will have to write tool in C or C++.
Here is an example that will get the filter out the java.lang.reflect.Method.invoke call and print it out. To get details regarding the object that has been called you will probably need to look at the stack frame.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <jvmti.h>
static jvmtiEnv *jvmti = NULL;
static jvmtiCapabilities capa;
static jint check_jvmti_error(jvmtiEnv *jvmti,
jvmtiError errnum,
const char *str) {
if (errnum != JVMTI_ERROR_NONE) {
char *errnum_str;
errnum_str = NULL;
(void) (*jvmti)->GetErrorName(jvmti, errnum, &errnum_str);
printf("ERROR: JVMTI: %d(%s): %s\n",
errnum,
(errnum_str == NULL ? "Unknown" : errnum_str),
(str == NULL ? "" : str));
return JNI_ERR;
}
return JNI_OK;
}
void JNICALL callbackMethodEntry(jvmtiEnv *jvmti_env,
JNIEnv* jni_env,
jthread thread,
jmethodID method) {
char* method_name;
char* method_signature;
char* generic_ptr_method;
char* generic_ptr_class;
char* class_name;
jvmtiError error;
jclass clazz;
error = (*jvmti_env)->GetMethodName(jvmti_env,
method,
&method_name,
&method_signature,
&generic_ptr_method);
if (check_jvmti_error(jvmti_env, error, "Failed to get method name")) {
return;
}
if (strcmp("invoke", method_name) == 0) {
error
= (*jvmti_env)->GetMethodDeclaringClass(jvmti_env, method,
&clazz);
if (check_jvmti_error(jvmti_env, error,
"Failed to get class for method")) {
(*jvmti_env)->Deallocate(jvmti_env, method_name);
(*jvmti_env)->Deallocate(jvmti_env, method_signature);
(*jvmti_env)->Deallocate(jvmti_env, generic_ptr_method);
return;
}
error = (*jvmti_env)->GetClassSignature(jvmti_env, clazz, &class_name,
&generic_ptr_class);
if (check_jvmti_error(jvmti_env, error, "Failed to get class signature")) {
(*jvmti_env)->Deallocate(jvmti_env, method_name);
(*jvmti_env)->Deallocate(jvmti_env, method_signature);
(*jvmti_env)->Deallocate(jvmti_env, generic_ptr_method);
return;
}
if (strcmp("Ljava/lang/reflect/Method;", class_name) == 0) {
printf("Method entered: %s.%s.%s\n", class_name, method_name,
method_signature);
}
(*jvmti_env)->Deallocate(jvmti_env, class_name);
(*jvmti_env)->Deallocate(jvmti_env, generic_ptr_class);
}
(*jvmti_env)->Deallocate(jvmti_env, method_name);
(*jvmti_env)->Deallocate(jvmti_env, method_signature);
(*jvmti_env)->Deallocate(jvmti_env, generic_ptr_method);
}
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
jint result;
jvmtiError error;
jvmtiEventCallbacks callbacks;
result = (*jvm)->GetEnv(jvm, (void**) &jvmti, JVMTI_VERSION_1_0);
if (result != JNI_OK || jvmti == NULL) {
printf("error\n");
return JNI_ERR;
} else {
printf("loaded agent\n");
}
(void) memset(&capa, 0, sizeof(jvmtiCapabilities));
capa.can_generate_method_entry_events = 1;
error = (*jvmti)->AddCapabilities(jvmti, &capa);
if (check_jvmti_error(jvmti, error, "Unable to set capabilities") != JNI_OK) {
return JNI_ERR;
}
(void) memset(&callbacks, 0, sizeof(callbacks));
callbacks.MethodEntry = &callbackMethodEntry;
error = (*jvmti)->SetEventCallbacks(jvmti,
&callbacks,
(jint) sizeof(callbacks));
if (check_jvmti_error(jvmti, error, "Unable to set callbacks") != JNI_OK) {
return JNI_ERR;
}
error = (*jvmti)->SetEventNotificationMode(jvmti,
JVMTI_ENABLE,
JVMTI_EVENT_METHOD_ENTRY,
(jthread) NULL);
if (check_jvmti_error(jvmti, error,
"Unable to set method entry notifications") != JNI_OK) {
return JNI_ERR;
}
return JNI_OK;
}