I am using JNI and I need to pass DateTime as an argument to a method. What format should I use?
Here is an example of my code:
int number = 10;
initial = env->GetMethodID(Simulator,"initialize", "(Ljava/util/Date;Ljava/util/Date;I)V");
if (env->ExceptionCheck()){
cout << "Fail:";
}
env->CallVoidMethod(Simulation,initial,"2014/05/21T00:00:00","2014/05/21T23:59:59",number);
I need to pass these Dates as Ljava/util/Date arguments and not as strings because I can't change the java code that JNI calls.
You just have to create the two java.util.Date objects first. Like this:
int number = 10;
jmethodID initial = env->GetMethodID(Simulator,"initialize", "(Ljava/util/Date;Ljava/util/Date;I)V");
if (env->ExceptionCheck()){
cout << "Fail:";
}
jclass dateType = env->FindClass("Ljava/util/Date;");
if(dateType == nullptr){
cout << "Fail:";
}
jmethodID dateTypeConstructor= env->GetMethodID(dateType, "<init>", "(Ljava/lang/String;)V");
if(constructor == nullptr){
cout << "Fail:";
}
jstring constructorString1 = env->NewStringUTF("2014/05/21T00:00:00");
jobject dateObject1 = env->NewObject(dateType , dateTypeConstructor, constructorString1);
if(dateObject1 == nullptr)
cout << "Fail:";
}
jstring constructorString2 = env->NewStringUTF("2014/05/21T23:59:59");
jobject dateObject2 = env->NewObject(dateType , dateTypeConstructor, constructorString2);
if(dateObject2 == nullptr)
cout << "Fail:";
}
env->CallVoidMethod(Simulation, initial, dateObject1, dateObject2, number);
The constructor Date(String s) is deprecated since JDK 1.1, but the principle is the same if you have to use a SimpleDateFormat or you can just write a static method in Java which will return a java.util.Date Object for the String that you pass to it.
Related
I am working on an android project to process images using Opencv.
I wrote an android jni function that should return a vector but I can't figure out how to do that right.
I tried to convert the vector to jobjectArray but it's not working.
Here is the code I'm working on:
jobjectArray
Java_com_grimg_testtt_MainActivity_getQuadrilateral(
JNIEnv *env,
jobject /* this */,
cv::Mat & grayscale,
cv::Mat & output) {
std::vector<std::string> vec;
cv::Mat approxPoly_mask(grayscale.rows, grayscale.cols, CV_8UC1);
approxPoly_mask = cv::Scalar(0);
std::vector<std::vector<cv::Point>> contours;
std::vector<int> indices(contours.size());
std::iota(indices.begin(), indices.end(), 0);
sort(indices.begin(), indices.end(), [&contours](int lhs, int rhs) {
return contours[lhs].size() > contours[rhs].size();
});
/// Find the convex hull object for each contour
std::vector<std::vector<cv::Point>> hull(1);
cv::convexHull(cv::Mat(contours[indices[0]]), hull[0], false);
std::vector<std::vector<cv::Point>> polygon(1);
approxPolyDP(hull[0], polygon[0], 20, true);
drawContours(approxPoly_mask, polygon, 0, cv::Scalar(255));
//imshow("approxPoly_mask", approxPoly_mask);
if (polygon[0].size() >= 4) // we found the 4 corners
{
return(polygon[0]);
}
return(std::vector<cv::Point>());
}
In the last two lines I'm getting this error which is obvious:
Returning 'std::vector<cv::Point> &' from a function returning 'jobjectArray': Types 'jobjectArray' and 'std::vector<cv::Point>' are not compatible.
What can I do to get over this problem?
Edit :
jclass clazz = (*env).FindClass("java/util/ArrayList");
jobjectArray result = (*env).NewObjectArray(polygon[0].size(), clazz, 0);
if (polygon[0].size() >= 4) // we found the 4 corners
{
for (int n=0;n<polygon[0].size();n++)
{
cv::Point point = (cv::Point) static_cast<cv::Point>(polygon[0][n]);
(*env).CallVoidMethod(result, (*env).GetMethodID(clazz, "add", "(java/lang/Object)V"), point);
}
return result;
}
return result;
}
Edit 2 :
jclass ptCls = env->FindClass("java/awt/Point");
jobjectArray result = (*env).NewObjectArray(polygon[0].size(), ptCls, NULL);
if (result == NULL) return NULL;
if (polygon[0].size() >= 4) // we found the 4 corners
{
for (int n=0;n<polygon[0].size();n++)
{
jobject point = (jobject) static_cast<jobject>(polygon[0][n]);
//(*env).CallVoidMethod(result, (*env).GetMethodID(ptCls, "add", "(java/lang/Object)V"), polygon[0][n]);
(*env).SetObjectArrayElement(result, polygon[0].size(), point);
}
return result;
}
return result;
Error
error: cannot cast from type 'std::__ndk1::__vector_base<cv::Point_<int>, std::__ndk1::allocator<cv::Point_<int> > >::value_type' (aka 'cv::Point_<int>') to pointer type 'jobject' (aka '_jobject *')
jobject point = (jobject) static_cast<jobject>(polygon[0][n]);
In the JNI layer you should map native objects to Java objects (Java objects are allocated on the JVM heap).
cv::Point needs to be converted to a Java class and std::vector needs to be converted to jobjectArray.
Use (*env)->NewObjectArray to create jobjectArray like this:
jobjectArray result = (*env)->NewObjectArray(env, size, PointCls, NULL);
if (result == NULL) return NULL;
The PointCls should refer to the Java class that corresponds to your native Point class.
Then iterate over each native cv::Point object, create a Java Point from it, copy the fields, and put it into the array (using (*env)->SetObjectArrayElement).
Then you can return the result array.
For example like this:
std::vector<cv::Point> const& input = polygon[0];
jclass doubleArray = env->FindClass("[D");
if (doubleArray == NULL) return NULL;
jobjectArray result = env->NewObjectArray(input.size(), doubleArray, NULL);
if (result == NULL) return NULL;
for (int i = 0; i < input.size(); ++i) {
jdoubleArray element = env->NewDoubleArray(2);
if (element == NULL)
break;
jdouble buf[2] = { input[i].x, input[i].y };
env->SetDoubleArrayRegion(element, 0, 2, buf);
env->SetObjectArrayElement(result, i, element);
}
return result;
This will return a 2D array double[][], with x, y corresponding to 0, 1 in the second dimension.
The DLL I made throws this error every time I try and load it in JNI. I narrowed the problem down to the main file, something in there is causing this. I'm not sure if it's because the toast notifications, couldn't find anything about that.
#include "stdafx.h"
#include <iostream>
#include <string>
#include "wintoast\wintoastlib.h"
#include "jni\me_glorantq_aboe_chat_client_notification_WindowsToastNotifier.h"
#include "ToastHandler.h"
std::wstring toastLogoPath = nullptr;
std::wstring jniToWstring(JNIEnv* env, jstring& jString) {
jboolean isCopy = true;
const char* chars = env->GetStringUTFChars(jString, &isCopy);
std::string str = std::string(chars);
std::wstring wstr(str.length(), L' ');
std::copy(str.begin(), str.end(), wstr.begin());
return wstr;
}
JNIEXPORT jboolean JNICALL Java_me_glorantq_aboe_chat_client_notification_WindowsToastNotifier_initialise(JNIEnv* env, jobject object, jstring logoPath) {
if (!WinToastLib::WinToast::instance()->isCompatible()) {
std::cerr << "WinToast is not compatible with this system!" << std::endl;
return false;
}
WinToastLib::WinToast::instance()->setAppName(L"A Bit of Everything");
std::wstring aumi = WinToastLib::WinToast::instance()->configureAUMI(L"me.glorantq", L"aboe", L"chat", L"win10");
WinToastLib::WinToast::instance()->setAppUserModelId(aumi);
if (!WinToastLib::WinToast::instance()->initialize()) {
std::cerr << "Failed to initialise WinToast!" << std::endl;
return false;
}
else {
std::cout << "Initialised WinToast!" << std::endl;
}
toastLogoPath = jniToWstring(env, logoPath);
std::cout << "Set logo path to: " << toastLogoPath.c_str() << std::endl;
return true;
}
JNIEXPORT void JNICALL Java_me_glorantq_aboe_chat_client_notification_WindowsToastNotifier_showNotificationNative(JNIEnv* env, jobject object, jstring header, jstring message) {
ToastHandler* handler = new ToastHandler;
WinToastLib::WinToastTemplate toastTemplate = WinToastLib::WinToastTemplate(WinToastLib::WinToastTemplate::ImageAndText02);
toastTemplate.setImagePath(toastLogoPath);
toastTemplate.setTextField(jniToWstring(env, header), WinToastLib::WinToastTemplate::FirstLine);
toastTemplate.setTextField(jniToWstring(env, message), WinToastLib::WinToastTemplate::SecondLine);
if (!WinToastLib::WinToast::instance()->showToast(toastTemplate, handler)) {
std::cerr << "Failed to show toast!" << std::endl;
}
}
When I remove everything from this file, everything works just fine, apart from the missing implementations of course.
In my previous question i cached the JNIEnv* between JNI Calls. And from the comment i came to know its invalid and this result me to learn the JNI Local and Global references. I did some test program to understand it. From the test program i am not able to understand the use of the Global references. Because the Local references itself working fine between multiple JNI calls. I have 3 questions from the test program
Eager to know the reason, that how the local reference getting cached and working properly.
Change in the ArrayList size is working and not the String object
Reason to know how the cached JNIEnv in working ,although its invalid (in my previous question).
The test code given below.
jni code :
jclass cls1, cls2, cls3;
jmethodID mth1, mth2, mth3;
jstring str1, str2;
jobject obj1, obj2, obj3;
JNIEXPORT void JNICALL Java_c_wrapperforjavaclass_clsNative_fnFindClass
(JNIEnv *env, jobject obj) {
if (cls1 == NULL || str1 == NULL || obj1 == NULL) {
cout << "Initializing new string object" << endl;
cls1 = env->FindClass("java/lang/String");
mth1 = env->GetMethodID(cls1, "<init>", "(Ljava/lang/String;)V");
str1 = env->NewStringUTF("Apple");
obj1 = env->NewObject(cls1, mth1, str1);
mth1 = env->GetMethodID(cls1, "length", "()I");
long i = (long) env->CallIntMethod(obj1, mth1);
cout << "Length = " << i << endl;
//env->DeleteLocalRef(cls1);
//env->DeleteLocalRef(str1);
//env->DeleteLocalRef(obj1);
} else {
cout << "String Object already initialized" << endl;
mth1 = env->GetMethodID(cls1, "length", "()I");
long i = (long) env->CallIntMethod(obj1, mth1);
cout << "Length = " << i << endl;
}
}
JNIEXPORT void JNICALL Java_c_wrapperforjavaclass_clsNative_fnGetExistingObject__Ljava_lang_String_2
(JNIEnv *env, jobject obj, jstring str) {
if (cls2 == NULL || obj2 == NULL) {
cout << "Initializing from existing string object" << endl;
cls2 = env->GetObjectClass(str);
obj2 = (jobject) env->NewLocalRef(str);
mth2 = env->GetMethodID(cls2, "length", "()I");
long i = (long) env->CallIntMethod(obj2, mth2);
cout << "Length = " << i << endl;
//env->DeleteLocalRef(cls2);
//env->DeleteLocalRef(obj3);
} else {
cout << "Object already initialized" << endl;
mth2 = env->GetMethodID(cls2, "length", "()I");
long i = (long) env->CallIntMethod(obj2, mth2);
cout << "Length = " << i << endl;
}
}
JNIEXPORT void JNICALL Java_c_wrapperforjavaclass_clsNative_fnGetExistingObject__Ljava_util_ArrayList_2
(JNIEnv *env, jobject obj, jobject lst) {
if (cls3 == NULL || obj3 == NULL) {
cout << "Initializing from existing ArrayList object" << endl;
cls3 = env->GetObjectClass(lst);
obj3 = (jobject) env->NewLocalRef(lst);
mth3 = env->GetMethodID(cls3, "size", "()I");
long i = (long) env->CallIntMethod(obj3, mth3);
cout << "Size = " << i << endl;
//env->DeleteLocalRef(cls3);
//env->DeleteLocalRef(obj3);
} else {
cout << "Object already initialized" << endl;
mth3 = env->GetMethodID(cls3, "size", "()I");
long i = (long) env->CallIntMethod(obj3, mth3);
cout << "Length = " << i << endl;
}
}
Calling Java code (Test Code) :
a.fnFindClass();
a.fnFindClass();
String str = new String("Android OS");
a.fnGetExistingObject(str);
//Increasing the size
str = new String("Will modified string length get effect");
a.fnGetExistingObject(str);
ArrayList<Integer> al = new ArrayList<>();
al.add(1);al.add(2);al.add(3);
a.fnGetExistingObject(al);
al.add(4);al.add(5); //Increasing the size
a.fnGetExistingObject(al);
Test Result :
Initializing new string object
Length = 5
String Object already initialized
Length = 5
Initializing from existing string object
Length = 10
Object already initialized
Length = 10
Initializing from existing ArrayList object
Size = 3
Object already initialized
Length = 5
Thanks In Advance.
Global references prevent the garbage collector from deleting the relevant object. The object might also not be collected just because another java object has a reference to it or because the garbage collector didn't run in a short period between calls. You shouldn't rely on this and instead keep global references to anything you might need later.
ArrayLists can be resized. Strings are immutable and one always needs to create a new string for functions like substring or append.
I believe the issue with keeping JNIEnv * has to do with thread safety. There is no way for the C++ code to know two different calls don't come from two different threads. Each env needs to be attached to a different thread.
I'm using QtCreator to deploy C++/Java applications on Android. But I think my problem may not be specific to the way QtCreator deploys the app.
I want to create a C++ library providing a specific functionnality. To do so, the library needs to instantiate a Java class, this last one will be used to do some SDK functions class (for stuff that are not available in the NDK/C++ API).
Creating and using java objects from a C++ program works fine. I package the .java file to the application environment during compilation/deployment and then I can use the Java class via two approachs:
Declare JNI_OnLoad, load class id, method id, and later call them using jni
Use Qt QAndroidJniObject objects (this is specific to QtCreator)
Now the problem comes when I want to create and use java objects from a C++ library. It only works if the .java file is packaged with the top-level application. I could not find a way to package the java with and only with the library itself. Meaning that anyone why needs to use my library will not only have to simply link with the library, but will also need to package the .java file(s) needed by my library. This breaks encapsulation and gives a hard time to the end developer writing programs and simply wanting to load a library and expecting it to embed all it needs to work on its own...
My question is: How can the library embed the java file, so that this java file does not need to be part of the top level program package to let the library use it?
Here is a quick sample: MainWindow constrctor calls 4 functions themselves trying to create and use Java objects. Only the first two calls work...
main.cpp:
#include <QApplication>
#include <QMainWindow>
#include "MyLib.h"
#include <QtAndroidExtras/QAndroidJniObject>
#include "jni.h"
#include <assert.h>
// load java classes from main program
JavaVM* s_javaVM = NULL;
jclass s_classID = 0;
jmethodID s_ctorMethodID = 0;
jmethodID s_callmethodID = 0;
bool loadJava( JNIEnv *env )
{
jclass clazz = env->FindClass("my/FooPrg");
if (!clazz)
{
qCritical("Can't find FooPrg class");
return false;
}
// keep a global reference to it
s_classID = (jclass)env->NewGlobalRef(clazz);
// search for its contructor
s_ctorMethodID = env->GetMethodID(s_classID, "<init>", "()V");
if (!s_ctorMethodID )
{
qCritical("Can't find class contructor");
return false;
}
// search for a method
s_callmethodID = env->GetMethodID(s_classID, "Mult", "(I)I");
if (!s_callmethodID )
{
qCritical("Can't find Mult method");
return false;
}
return true;
}
jint JNICALL JNI_OnLoad(JavaVM *vm, void *)
{
s_javaVM = vm;
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
return -1;
loadJava( env );
return JNI_VERSION_1_4;
}
void callJavaFunctionFromPrgWithQt()
{
if ( QAndroidJniObject::isClassAvailable("my/FooPrg") )
{
QAndroidJniObject obj("my/FooPrg","()V");
if ( obj.isValid() )
{
jint res = obj.callMethod<jint>("Mult", "(I)I", 0x0002);
assert( res == 4 );
}
else
{
assert( false );
}
}
else
{
assert( false );
}
}
void callJavaFunctionFromPrgWithJniLoad()
{
if ( s_classID != 0 && s_ctorMethodID != 0 && s_callmethodID != 0 )
{
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
assert(false);
jobject j_object = env->NewGlobalRef( env->NewObject(s_classID, s_ctorMethodID ) );
jint res = env->CallIntMethod(j_object, s_callmethodID, 0x0002 );
assert( res == 4 );
}
else
{
assert( false );
}
}
class MainWindow : public QMainWindow
{
public:
MainWindow()
{
callJavaFunctionFromPrgWithQt(); // works
callJavaFunctionFromPrgWithJniLoad(); // works
callJavaFunctionFromLibWithQt(); // fails, assert
callJavaFunctionFromLibWithJniLoad(); // fails, because libraries JNI_OnLoad can't find FooLib.java!
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
MyLib.h:
#pragma once
void callJavaFunctionFromLibWithQt();
void callJavaFunctionFromLibWithJniLoad();
MyLib.cpp:
#include "MyLib.h"
#include <QtAndroidExtras/QAndroidJniObject>
#include "jni.h"
#include <assert.h>
// load java classes from main program
JavaVM* s_javaVM = NULL;
jclass s_classID = 0;
jmethodID s_ctorMethodID = 0;
jmethodID s_callmethodID = 0;
bool loadJava( JNIEnv *env )
{
jclass clazz = env->FindClass("my/FooLib");
if (!clazz)
{
qDebug("Can't find FooLib class");
return false;
}
// keep a global reference to it
s_classID = (jclass)env->NewGlobalRef(clazz);
// search for its contructor
s_ctorMethodID = env->GetMethodID(s_classID, "<init>", "()V");
if (!s_ctorMethodID )
{
qDebug("Can't find class contructor");
return false;
}
// search for a method
s_callmethodID = env->GetMethodID(s_classID, "Mult", "(I)I");
if (!s_callmethodID )
{
qDebug("Can't find Mult method");
return false;
}
return true;
}
jint JNICALL JNI_OnLoad(JavaVM *vm, void *)
{
s_javaVM = vm;
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
return -1;
// uncommenting this makes the application crash upon load....
//loadJava( env );
return JNI_VERSION_1_4;
}
void callJavaFunctionFromLibWithQt()
{
if ( QAndroidJniObject::isClassAvailable("my/FooLib") )
{
QAndroidJniObject obj("my/FooLib","()V");
if ( obj.isValid() )
{
jint res = obj.callMethod<jint>("Mult", "(I)I", 0x0002);
assert( res == 4 );
}
else
{
assert( false );
}
}
else
{
assert( false ); // this assertion is reached!
}
}
void callJavaFunctionFromLibWithJniLoad()
{
if ( s_classID != 0 && s_ctorMethodID != 0 && s_callmethodID != 0 )
{
JNIEnv* env = NULL;
if (s_javaVM->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4) != JNI_OK)
assert(false);
jobject j_object = env->NewGlobalRef( env->NewObject(s_classID, s_ctorMethodID ) );
jint res = env->CallIntMethod(j_object, s_callmethodID, 0x0002 );
assert( res == 4 );
}
else
{
assert( false ); // this assertion is reached!
}
}
FooPrg.java:
package my;
import java.lang.Integer;
public class FooPrg
{
public FooPrg()
{
}
public int Mult(int val)
{
return val * 2;
}
}
FooLib.java:
package my;
import java.lang.Integer;
public class FooLib
{
public FooLib()
{
}
public int Mult(int val)
{
return val * 2;
}
}
jniload.pro:
TARGET = jniload
CONFIG += qt resources
QT += core gui widgets
android: QT += androidextras
SOURCES += src/main.cpp
TEMPLATE = app
INCLUDEPATH += ifc
LIBS += \
-l$$OUT_PWD/../../lib/jniload_lib/libjniload_lib.so
ANDROID_EXTRA_LIBS += \
$$OUT_PWD/../../lib/jniload_lib/libjniload_lib.so
ANDROID_PACKAGE_SOURCE_DIR = data/android/root
OTHER_FILES += data/android/root/src/my/FooPrg.java
jniload_lib.pro:
TARGET = jniload_lib
CONFIG += qt resources
QT += core gui widgets
android: QT += androidextras
SOURCES += src/MyLib.cpp
HEADERS += ifc/MyLib.h
TEMPLATE = lib
INCLUDEPATH += ifc
# This does has apparently no effect on library
ANDROID_PACKAGE_SOURCE_DIR = data/android/root
OTHER_FILES += data/android/root/src/my/FooLib.java
Finaly got a way to work this out.
I removed ANDROID_PACKAGE_SOURCE_DIR line from jniload.pro file and hanlde manual copy of the .java files through custom build steps:
custom_jniload_lib_step.target = jniload_lib_mockup.h
custom_jniload_lib_step.commands = $(COPY_DIR) data\android\root ..\..\android-build
QMAKE_EXTRA_TARGETS += custom_jniload_lib_step
PRE_TARGETDEPS += jniload_lib_mockup.h
custom_jniload_step.target = jniload_mockup.h
custom_jniload_step.commands = $(COPY_DIR) data\android\root ..\..\android-build
QMAKE_EXTRA_TARGETS += custom_jniload_step
PRE_TARGETDEPS += jniload_mockup.h
Then, upon deployment, android-build/src contains both FooLib.java and FooPrg.java and then both library and program can access them!
I have the following java code
public class Test {
public void sayHello(String msg) {
System.out.println(msg);
}
}
new Test().sayHello("Bonjour");
I have a jvmti agent attached to java where I catch function calls. I want to get parameter value which was passed to my method (e.g. "Bonjour")
static void JNICALL cbMethodEntry(jvmtiEnv *jvmti,
JNIEnv* jni_env, jthread thread, jmethodID method) {
// here I want to get a parameter value "Bonjour"
// which was passed to my method sayHello("Bonjour")
}
jvmtiEventCallbacks callbacks;
callbacks.MethodEntry = &cbMethodEntry;
In the callback itself I have a thread and method ID.
Looking into a jvmti.h header I found only this structure dealing with parameters but there are no values.
typedef struct {
char* name;
jvmtiParamKind kind;
jvmtiParamTypes base_type;
jboolean null_ok;
} jvmtiParamInfo;
How can I get parameter values from my callback?
I'm working on similar tasks. Here are two code examples written in C++. Example 1 shows how to get local variables in the MethodEntry callback using GetLocalVariableTable and GetLocalObject. Example 2 shows how to preform this using BCI (Bytecode Instrumentation).
Example 1:
HandleMethodEntry is the call back method for MethodEntry event. It logs some information about the method's parameters. GetLocalVariableTable retrieves local variable information, which is used by GetLocalObject. Frame at depth zero is the current frame, the first parameter is at slot 0. For non-static frames, slot 0 contains the "this" object. To retrieve "this" object from native method frames, you should use GetLocalInstance instead of GetLocalObject.
The first char of the signature is the value type. This example simply checks the tag of a jobject. For String values, you can use GetStringUTFChars. An example can be found here.
void JNICALL MethodTraceAgent::HandleMethodEntry(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread, jmethodID method)
{
try {
jvmtiError error;
jclass clazz;
char* name;
char* signature;
// get declaring class of the method
error = m_jvmti->GetMethodDeclaringClass(method, &clazz);
Errors::Check(error);
// get the signature of the class
error = m_jvmti->GetClassSignature(clazz, &signature, 0);
Errors::Check(error);
// get method name
error = m_jvmti->GetMethodName(method, &name, NULL, NULL);
Errors::Check(error);
char tmp[1024];
sprintf(tmp, "%s%s", signature, name);
if(pFilter->Match("method", tmp)) { // intrested method?
char out[1024];
jint param_size = 0;
error = m_jvmti->GetArgumentsSize(method, ¶m_size);
int line_len = sprintf(out, "method_entry: %s%s%, param_size:%d", signature, name, param_size);
// visit local variable
jint entry_count = 0;
jvmtiLocalVariableEntry *table_ptr = NULL;
jlocation cur_loc;
// this call may return JVMTI_ERROR_ABSENT_INFORMATION, this error is avoided by initialize entry_count to 0 to escape the following for loop
error = m_jvmti->GetLocalVariableTable(method, &entry_count, &table_ptr);
error = m_jvmti->GetFrameLocation(thread, 0, NULL, &cur_loc);
for(int j=0; j<min(param_size, entry_count); j++) {
if(table_ptr[j].start_location > cur_loc) break;
if(table_ptr[j].signature[0] == 'L') { // fully-qualified-class
jobject param_obj;
jlong param_obj_tag = 0;
error = m_jvmti->GetLocalObject(thread, 0, table_ptr[j].slot, ¶m_obj); // frame at depth zero is the current frame
m_jvmti->GetTag(param_obj, ¶m_obj_tag);
if(param_obj_tag == 0) {
m_jvmti->SetTag(param_obj, theTag);
param_obj_tag = theTag;
++theTag;
}
line_len += sprintf(out + line_len, ", param_obj_tag: %ld", param_obj_tag);
//line_len += sprintf(out+line_len, ", slot:%d, start:%ld, cur:%ld, param:%s%s", table_ptr[j].slot, table_ptr[j].start_location, cur_loc, table_ptr[j].signature, table_ptr[j].name);
jni->DeleteLocalRef(param_obj);
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr[j].signature));
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr[j].name));
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr[j].generic_signature));
}
}
error = m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr));
Errors::Check(error);
// put to log list
logList.push_back(out);
printf("\r%-10d", logList.size());
}
// release resources
error = m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(name));
Errors::Check(error);
error = m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(signature));
Errors::Check(error);
} catch (AgentException& e) {
cout << "Error when enter HandleMethodEntry: " << e.what() << " [" << e.ErrCode() << "]" << endl;
}
}
Example 2:
As mentioned in the answer of a similar question, dealing with it in MethodEntry even callback may have preformance problem. You can consider the BCI approach. MTRACE_native_entry is a native method injected to very beginning of every method call. It's called from MTrace's method_entry method.
In MTRACE_native_entry, you need to track back to the intrested method at frame 2 (current frame of the executing native method is at frame 0). Similar example of param trace can be found in another project stackparam in GitHub. However, performence differences of these two methods is not tested.
Unshown code of this example can be found in the jdk document dir demo/jvmti/mtrace. The core step is to inject method_entry in ClassFileLoadHook event callback using java_crw_demo.
This example also shows how to get an param object's field value.
void JNICALL MethodTraceAgent::MTRACE_native_entry(JNIEnv *jni, jclass klass, jthread thread, jint cnum, jint mnum)
{
/* It's possible we get here right after VmDeath event, be careful */
if ( !pTheAgent->vmInitialized || pTheAgent->vmDead || thread == NULL)
return;
jvmtiError error;
char out[1024];
int line_len = 0;
jvmtiFrameInfo frames[3];
jint cframe;
error = m_jvmti->GetStackTrace(thread, 0, 3, frames, &cframe);
Errors::Check(error);
if(cframe < 3)
return;
jmethodID method = frames[2].method;
jclass dec_cls;
char *mtd_name, *dec_cls_sig;
m_jvmti->GetMethodDeclaringClass(method, &dec_cls);
m_jvmti->GetClassSignature(dec_cls, &dec_cls_sig, NULL);
m_jvmti->GetMethodName(method, &mtd_name, NULL, NULL);
jboolean isNative = false;
m_jvmti->IsMethodNative(method, &isNative);
if(isNative)
return;
line_len += sprintf(out + line_len, "m_en: %s%s", dec_cls_sig, mtd_name);
// operate tags
jint param_size = 0;
jint entry_count = 0;
jvmtiLocalVariableEntry *table_ptr = NULL;
error = m_jvmti->GetArgumentsSize(method, ¶m_size);
error = m_jvmti->GetLocalVariableTable(method, &entry_count, &table_ptr);
Errors::Check(error);
line_len += sprintf(out + line_len, ", %d, %d", param_size, entry_count);
for(int j=0; j<min(param_size, entry_count); j++) {
jobject param_obj = 0;
if(j==0 && strcmp(table_ptr[0].name, "this") == 0) { // this instance
error = m_jvmti->GetLocalInstance(thread, 2, ¶m_obj);
if(thiso == 0) thiso = param_obj;
else {
line_len += sprintf(out + line_len, ", same_this: %d", jni->IsSameObject(thiso, param_obj));
}
jfieldID field = jni->GetFieldID(dec_cls, "a", "I");
jint a = jni->GetIntField(param_obj, field);
line_len += sprintf(out + line_len, ", a: %d", a);
Errors::Check(error);
}
else if(table_ptr[j].signature[0] == 'L') { // object
error = m_jvmti->GetLocalObject(thread, 2, table_ptr[j].slot, ¶m_obj); // frame at depth zero is the current frame
Errors::Check(error);
}
if(param_obj != 0) {
//line_len += sprintf(out + line_len, ", modi: %d, this: %d, same: %d", modied, param_obj, jni->IsSameObject(param_obj, modied));
jlong param_obj_tag = 0;
m_jvmti->GetTag(param_obj, ¶m_obj_tag);
if(param_obj_tag == 0) {
error = m_jvmti->SetTag(param_obj, pTheAgent->ctag);
Errors::Check(error);
param_obj_tag = pTheAgent->ctag;
++pTheAgent->ctag;
}
line_len += sprintf(out + line_len, ", param_obj_tag: %ld", param_obj_tag);
//line_len += sprintf(out+line_len, ", slot:%d, start:%ld, cur:%ld, param:%s%s", table_ptr[j].slot, table_ptr[j].start_location, cur_loc, table_ptr[j].signature, table_ptr[j].name);
jni->DeleteLocalRef(param_obj);
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr[j].signature));
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr[j].name));
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr[j].generic_signature));
}
}
error = m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(table_ptr));
Errors::Check(error);
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(dec_cls_sig));
m_jvmti->Deallocate(reinterpret_cast<unsigned char*>(mtd_name));
logList.push_back(out);
}
The class method used to inject:
public class MTrace {
private static int engaged = 0;
/* At the very beginning of every method, a call to method_entry()
* is injected.
*/
private static native void _method_entry(Object thread, int cnum, int mnum);
public static void method_entry(int cnum, int mnum)
{
if ( engaged != 0 ) {
_method_entry(Thread.currentThread(), cnum, mnum);
}
}
/* Before any of the return bytecodes, a call to method_exit()
* is injected.
*/
private static native void _method_exit(Object thread, int cnum, int mnum);
public static void method_exit(int cnum, int mnum)
{
if ( engaged != 0 ) {
_method_exit(Thread.currentThread(), cnum, mnum);
}
}
}
Note that these two examples is written for test purpose, not all the return value of jvmti functions are checked. Some other problems may also exist.
You are going to want to start by using GetLocalObject. In this respect I was able to find the following example that should help get you going in the right direction.