How to get parameter values in a MethodEntry callback - java

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, &param_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, &param_obj); // frame at depth zero is the current frame
m_jvmti->GetTag(param_obj, &param_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, &param_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, &param_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, &param_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, &param_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.

Related

JNA - callback method with typedef struct** argument

I am using C dll with this code:
1)
AIC_BRIDGE_API AIC_ERROR_CODE aic2_set_cb_function (
void (*cb2_start_dsts) (AIC2_DSTS_START_STOP),
void (*cb2_stop_dsts) (AIC2_DSTS_START_STOP),
void (*cb2_dsts_rcvd_ex) (unsigned int, unsigned long *, char *, AIC2_DSTS_STO),
void (*cb2_log) (const char *, int, const char *, int)
);
2)
aic2_set_cb_function (NULL, NULL, cb2_dsts_rcvd_ex, NULL);
The dll runs in many apps with C/C++ and .Net code.
My code in Java is this:
1)
public interface ReadCallbackInt extends Callback {
void invoke(int iNumDv, Pointer pMicDv, String pcARName, AIC2_DSTS_STO.ByValue sto);
}
2)
public void aic2_set_cb_function(StartDSCallbackInt fn1,
StopDSCallbackInt fn2,
ReadCallbackInt fnReadCB,
LogCallbackInt fn4);
3)
TestLib.ReadCallbackInt fnReadCB = new TestLib.ReadCallbackInt() {
long[] IntArray;
#Override
public void invoke(int iNumDv, Pointer pMicDv, String pcARName, AIC2_DSTS_STO.ByValue sto) {
if (sto.bTsNamePres > 0) {
System.out.println("iNumDv: " + iNumDv);
System.out.println("pMicDv: " + pMicDv);
System.out.println("pcARName: " + pcARName);
System.out.println("sto: " + sto.TsName);
if (pMicDv!=null) {
IntArray = new long[iNumDv];
IntArray = pMicDv.getLongArray(0, iNumDv);
if (IntArray != null) {
System.out.println("IntArray: " + IntArray +" First El. " + IntArray[0]);
}
}
}
}
}
...............
...............
4)
TestLib.INSTANCE.aic2_set_cb_function(null, null, fnReadCB, null);
The issue is that in IntArray I get all elements as zero. Can you help me?
5) Original C code:
void cb2_dsts_rcvd_ex (unsigned int iNumDv, unsigned long *piMicDv, char *pcARName, AIC2_DSTS_STO sto)
{
unsigned int i;
AIC2_DV *pdv;
printf ("\nRemote %s: ", pcARName);
if (sto.bTsNamePres)
printf ("Report (%s/%s) received\n", sto.TsName.pcDomainName, sto.TsName.pcName);
else
printf ("Report (unknown) received\n");
for (i = 0; i < iNumDv; i++)
if (piMicDv[i] != AIC_ID_DV_INVALID)
{
pdv = aic2_get_dv_info (piMicDv[i]);
log_data_values_aic2 (pdv, stdout);
if (pdv) aic2_free_dv_info(pdv);
}
}

How to return a vector<Point> from a jni C++ function?

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.

How to Get the values of method local variables and class variables using jvmti

I am trying to capture the variable values using JVMTI, when an exception event is generated, i went through the jvmti documentation and found that there are no functions which let me retrieve the values of the fields(variables), how can this be achieved ?
Below is the Agent code:
#include<jni.h>
#include<jvmti.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct {
jvmtiEnv *jvmti;
jrawMonitorID lock;
} GlobalAgentData;
static GlobalAgentData *gdata;
static bool 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 false;
}
return true;
}
static void deallocate(jvmtiEnv *jvmti,void *ptr){
jvmtiError error;
error = (*jvmti)->Deallocate(jvmti,ptr);
check_jvmti_error(jvmti,error,"Cannot deallocate memory");
}
static void allocate(jvmtiEnv *jvmti,jint len){
jvmtiError error;
void *ptr;
error = (*jvmti)->Allocate(jvmti,len,(unsigned char **)&ptr);
check_jvmti_error(jvmti,error,"Cannot allocate memory");
}
JNICALL jint objectCountingCallback(jlong class_tag,jlong size,jlong* tag_ptr,jint length,void* user_data){
int* count = (int*)user_data;
*count+=1;
return JVMTI_VISIT_OBJECTS;
}
JNIEXPORT jint JNICALL Java_Test_countInstances(JNIEnv *env,jclass thisClass,jclass klass){
int count =0 ;
jvmtiError error;
jvmtiHeapCallbacks callbacks;
jvmtiEnv *jvmti;
(void)memset(&callbacks,0,sizeof(callbacks));
callbacks.heap_iteration_callback = &objectCountingCallback;
jvmti = gdata->jvmti;
error = (*jvmti)->IterateThroughHeap(jvmti,0,klass,&callbacks,&count);
// check_jvmti_error(*gdata->jvmti,error,"Unable to iterate through the heap");
return count;
}
static void enter_critical_section(jvmtiEnv *jvmti){
jvmtiError error;
error = (*jvmti)->RawMonitorEnter(jvmti,gdata->lock);
check_jvmti_error(jvmti,error,"Cannot enter with raw monitor");
}
static void exit_critical_section(jvmtiEnv *jvmti){
jvmtiError error;
error = (*jvmti)->RawMonitorExit(jvmti,gdata->lock);
check_jvmti_error(jvmti,error,"Cannot exit with raw monitor");
}
static void JNICALL callbackVMInit(jvmtiEnv *jvmti,JNIEnv *env,jthread thread){
jvmtiError error;
// enter_critical_section(jvmti);{ /* not needed since we are just setting event notifications */
printf("Initializing JVM\n");
error = (*jvmti)->SetEventNotificationMode(jvmti,JVMTI_ENABLE,JVMTI_EVENT_EXCEPTION,(jthread)NULL);
// error = (*jvmti)->SetEventNotificationMode(jvmti,JVMTI_ENABLE,JVMTI_EVENT_METHOD_ENTRY,(jthread)NULL);
check_jvmti_error(jvmti,error,"Cannot set Exception Event notification");
// } exit_critical_section(jvmti);
}
static void callbackMethodEntry(jvmtiEnv *jvmti,JNIEnv *env,jthread thread,jmethodID method){
jvmtiError error;
jvmtiLocalVariableEntry **table_ptr;
jint count,entry_count_ptr;
jobject value_ptr;
int j;
error = (*jvmti)->GetLocalVariableTable(jvmti,method,&entry_count_ptr,table_ptr);
if(check_jvmti_error(jvmti,error,"Cannot Get Local Variable table\n")){
printf("local variable table entry size : %d %s\n",entry_count_ptr,(*table_ptr)[0].name);
}
// for(j=0;j<*entry_count_ptr;j++){
// error = (*jvmti)->GetLocalObject(jvmti,thread,0,(*table_ptr)[j].slot,&value_ptr);
// printf("Field Name:%s\n",(*table_ptr)[j].name);
// }
}
static void JNICALL callbackException(jvmtiEnv *jvmti,JNIEnv *env,jthread thread,jmethodID method,jlocation location,jobject exception,jmethodID catch_method,jlocation catch_location){
jvmtiFrameInfo frames[10];
jint count,entry_count_ptr;
int i,j;
jvmtiError error;
jobject* value_ptr;
char *name,*sig,*gsig;
jclass declaring_class_ptr;
jvmtiLocalVariableEntry *table_ptr;
error = (*jvmti)->GetStackTrace(jvmti,thread,0,10,frames,&count);
if(check_jvmti_error(jvmti,error,"Cannot Get Frame") && count >=1){
char *methodName,*className;
for(i=0;i<count;i++){
error = (*jvmti)->GetMethodName(jvmti, frames[i].method,&methodName,&sig,&gsig);
if(check_jvmti_error(jvmti,error,"Cannot Get method name")){
error = (*jvmti)->GetMethodDeclaringClass(jvmti,frames[i].method,&declaring_class_ptr);
check_jvmti_error(jvmti,error,"Cannot Get method declaring class");
error = (*jvmti)->GetClassSignature(jvmti,declaring_class_ptr,&className,NULL);
check_jvmti_error(jvmti,error,"Cannot get class signature");
// printf("Got Exception in Method: %s at Line: %ld with Signature:%s,%s within Class:%s\n",methodName,frames[i].location,sig,gsig,className);
for(j=0;j<entry_count_ptr;j++){
callbackMethodEntry(jvmti,env,thread,frames[j].method);
error = (*jvmti)->GetLocalObject(jvmti,thread,i,table_ptr[j].slot,value_ptr);// change the value of the slot parameter
printf("Field Name:%s\n",table_ptr[j].name);
}
}
}
}
/* error = (*jvmti)->GetMethodName(jvmti,method,&name,&sig,&gsig);
check_jvmti_error(jvmti,error,"Cannot Get Method name");
printf("Exception in Method: %s%s at line number: %ld\n",name,sig,location);*/
}
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm,char *options,void *reserved){
jvmtiEnv *jvmti;
jvmtiCapabilities capabilities;
jvmtiError error;
jint result;
jvmtiEventCallbacks callbacks;
result = (*jvm)->GetEnv(jvm,(void **)&jvmti,JVMTI_VERSION_1);
if(result!=JNI_OK){
printf("Unable to access JVMTI! \n");
}
gdata = (GlobalAgentData*)malloc(sizeof(GlobalAgentData));
gdata->jvmti=jvmti;
(void)memset(&capabilities,0,sizeof(jvmtiCapabilities));
capabilities.can_tag_objects = 1;
capabilities.can_signal_thread=1;
capabilities.can_get_owned_monitor_info=1;
capabilities.can_generate_method_entry_events=1;
capabilities.can_generate_exception_events=1;
capabilities.can_tag_objects=1;
capabilities.can_access_local_variables=1;
error = (*(gdata->jvmti))->AddCapabilities(gdata->jvmti,&capabilities);
check_jvmti_error(gdata->jvmti,error,"Unable to set Capabilities");
(void)memset(&callbacks,0,sizeof(callbacks));
callbacks.VMInit = &callbackVMInit;
callbacks.Exception = &callbackException;
//callbacks.MethodEntry = &callbackMethodEntry;
error = (*(gdata->jvmti))->SetEventCallbacks(gdata->jvmti,&callbacks,(jint)sizeof(callbacks));
check_jvmti_error(gdata->jvmti,error,"Cannot set event callbacks");
error = (*(gdata->jvmti))->SetEventNotificationMode(gdata->jvmti,JVMTI_ENABLE,JVMTI_EVENT_VM_INIT,(jthread)NULL);
check_jvmti_error(gdata->jvmti,error,"Cannot set event notification");
error = (*(gdata->jvmti))->CreateRawMonitor(gdata->jvmti,"agent data",&(gdata->lock));
check_jvmti_error(gdata->jvmti,error,"Cannot create raw monitor");
printf("A message from my custom super agent!!\n");
return JNI_OK;
}
Below is the output :
ERROR: JVMTI: 101(JVMTI_ERROR_ABSENT_INFORMATION): Cannot Get Local Variable table
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f3faab0cefa, pid=14869, tid=0x00007f3fad251700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_111-b14) (build 1.8.0_111-b14)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.111-b14 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C [liblearnAgent.so+0xefa] callbackException+0x277
#
# Core dump written. Default location: /home/kumard/Desktop/core or core.14869
#
# An error report file with more information is saved as:
# /home/kumard/Desktop/hs_err_pid14869.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
[1] 14869 abort (core dumped) java -agentlib:learnAgent SimpleThread
This is not the complete answer, but it does resolve some of the problems in your agent and prints out the values for basic data types when exception hits. We have resolved problems in the comment chat. So I'm simply posting the code here. Anyone interested in knowing more about it can see the chat. You're most welcome to give your insights on the problem too.
#include <jni.h>
#include <jvmti.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct {
jvmtiEnv *jvmti;
jrawMonitorID lock;
} GlobalAgentData;
static GlobalAgentData *gdata;
static bool 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 false;
}
return true;
}
static void JNICALL callbackException(jvmtiEnv *jvmti, JNIEnv *env,
jthread thread, jmethodID method, jlocation location, jobject exception,
jmethodID catch_method, jlocation catch_location) {
jvmtiFrameInfo frames[10];
jint count, entry_count_ptr;
int i, j;
jvmtiError error;
char *sig, *gsig;
jclass declaring_class_ptr;
jvmtiLocalVariableEntry *table_ptr;
error = (*jvmti)->GetStackTrace(jvmti, thread, 0, 10, frames, &count);
if (check_jvmti_error(jvmti, error, "Cannot Get Frame") && count >= 1) {
char *methodName, *className;
for (i = 0; i < count; i++) {
error = (*jvmti)->GetMethodName(jvmti, frames[i].method,
&methodName, &sig, &gsig);
if (check_jvmti_error(jvmti, error, "Cannot Get method name")) {
error = (*jvmti)->GetMethodDeclaringClass(jvmti,
frames[i].method, &declaring_class_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get method declaring class");
error = (*jvmti)->GetClassSignature(jvmti, declaring_class_ptr,
&className, NULL);
check_jvmti_error(jvmti, error, "Cannot get class signature");
error = (*jvmti)->GetLocalVariableTable(jvmti, frames[i].method,
&entry_count_ptr, &table_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Table");
printf(
"Got Exception in Method: %s at Line: %ld with Signature:%s,%s within Class:%s\n",
methodName, frames[i].location, sig, gsig, className);
if (strstr(className, "java") == NULL
&& strstr(className, "javax") == NULL
&& strstr(className, "sun") == NULL) {
for (j = 0; j < entry_count_ptr; j++) {
switch (*(table_ptr[j].signature)) {
case 'B': {
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Byte");
printf("Value of Field %s is %d.\n", table_ptr[j].name, (jbyte)value_ptr);
break;
}
case 'C': {
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Char");
printf("Value of Field %s is %c.\n", table_ptr[j].name, (jchar)value_ptr);
break;
}
case 'D': {
jdouble value_ptr;
error = (*jvmti)->GetLocalDouble(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Double");
printf("Value of Field %s is %f.\n", table_ptr[j].name, value_ptr);
break;
}
case 'F': {
jfloat value_ptr;
error = (*jvmti)->GetLocalFloat(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Float");
printf("Value of Field %s is %f.\n", table_ptr[j].name, value_ptr);
break;
}
case 'I': {
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Integer");
printf("Value of Field %s is %d.\n", table_ptr[j].name, value_ptr);
break;
}
case 'J': {
jlong value_ptr;
error = (*jvmti)->GetLocalLong(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Long");
printf("Value of Field %s is %ld.\n", table_ptr[j].name, value_ptr);
break;
}
case 'S':{
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Short");
printf("Value of Field %s is %d.\n", table_ptr[j].name, (jshort)value_ptr);
break;
}
case 'Z':{
jint value_ptr;
error = (*jvmti)->GetLocalInt(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Boolean");
printf("Value of Field %s is %d.\n", table_ptr[j].name, (jboolean)value_ptr);
break;
}
case 'L':{
jobject value_ptr;
error = (*jvmti)->GetLocalObject(jvmti, thread, i,
table_ptr[j].slot, &value_ptr);
check_jvmti_error(jvmti, error,
"Cannot Get Local Variable Object");
printf("Value of Field %s is .\n", table_ptr[j].name);
break;
}
default:
printf("Can't get %s type.\n",
table_ptr[j].signature);
}
printf("Field Signature:%s\n", table_ptr[j].signature);
}
}
}
}
}
}
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
jvmtiEnv *jvmti;
jvmtiCapabilities capabilities;
jvmtiError error;
jint result;
jvmtiEventCallbacks callbacks;
result = (*jvm)->GetEnv(jvm, (void **) &jvmti, JVMTI_VERSION_1);
if (result != JNI_OK) {
printf("Unable to access JVMTI! \n");
}
gdata = (GlobalAgentData*) malloc(sizeof(GlobalAgentData));
gdata->jvmti = jvmti;
(void) memset(&capabilities, 0, sizeof(jvmtiCapabilities));
capabilities.can_generate_exception_events = 1;
capabilities.can_access_local_variables = 1;
error = (*(gdata->jvmti))->AddCapabilities(gdata->jvmti, &capabilities);
check_jvmti_error(gdata->jvmti, error, "Unable to set Capabilities");
error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE,
JVMTI_EVENT_EXCEPTION, (jthread) NULL);
check_jvmti_error(jvmti, error, "Cannot set Exception Event notification");
(void) memset(&callbacks, 0, sizeof(callbacks));
callbacks.Exception = &callbackException;
error = (*(gdata->jvmti))->SetEventCallbacks(gdata->jvmti, &callbacks,
(jint) sizeof(callbacks));
check_jvmti_error(gdata->jvmti, error, "Cannot set event callbacks");
error = (*(gdata->jvmti))->CreateRawMonitor(gdata->jvmti, "agent data",
&(gdata->lock));
check_jvmti_error(gdata->jvmti, error, "Cannot create raw monitor");
printf("A message from my custom super agent!!\n");
return JNI_OK;
}

Embed java code from a C++ library without needing top-level program to embed it?

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!

JNI: Catching Init-Time Exceptions

Okay, I'm all out of ideas on this one. Does anyone have any idea how I can hook into Java's exception pipeline in order to catch (and log to a text file) all exceptions that are occurring?
The situation is this: I have a library in a JAR file (A) which in turn depends on a second JAR file (B). A has no main class, as it's simply a class library, which I'm accessing and invoking through the JNI. The problem I'm having is this. When I attempt to initialise the JNI with A loaded, the JNI returns an unspecified error.
I strongly suspect that this error originates from an instantiation of Log4J's logger unit, which is occurring in static code (outside of a method) in B, which I believe is throwing an IOException as a result of permissions problems on the log file. I'm having issues finding out what's going on, however, as the exception (which I suspect is the cause of the problem) is being thrown during the linking stage (when A imports B) and so cannot be caught by a try-catch block. Also, since there is no main method there is no obvious place to put a try-catch block in order to catch this exception.
I would like some way of catching all exceptions that arise in either JAR and dumping them into a text file. I cannot (easily) modify B (I do not have the decompiled JAR). Any ideas?
Here is the C code which invokes the JNI with the specified libraries and options:
_DLL_EXPORT PyObject *initVM(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwnames[] = {
"classpath", "initialheap", "maxheap", "maxstack",
"vmargs", NULL
};
char *classpath = NULL;
char *initialheap = NULL, *maxheap = NULL, *maxstack = NULL;
char *vmargs = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|zzzzz", kwnames,
&classpath,
&initialheap, &maxheap, &maxstack,
&vmargs))
return NULL;
if (env->vm)
{
PyObject *module_cp = NULL;
if (initialheap || maxheap || maxstack || vmargs)
{
PyErr_SetString(PyExc_ValueError,
"JVM is already running, options are ineffective");
return NULL;
}
if (classpath == NULL && self != NULL)
{
module_cp = PyObject_GetAttrString(self, "CLASSPATH");
if (module_cp != NULL)
classpath = PyString_AsString(module_cp);
}
if (classpath && classpath[0])
env->setClassPath(classpath);
Py_XDECREF(module_cp);
return getVMEnv(self);
}
else
{
JavaVMInitArgs vm_args;
JavaVMOption vm_options[32];
JNIEnv *vm_env;
JavaVM *vm;
unsigned int nOptions = 0;
PyObject *module_cp = NULL;
vm_args.version = JNI_VERSION_1_4;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
if (classpath == NULL && self != NULL)
{
module_cp = PyObject_GetAttrString(self, "CLASSPATH");
if (module_cp != NULL)
classpath = PyString_AsString(module_cp);
}
#ifdef _jcc_lib
PyObject *jcc = PyImport_ImportModule("jcc");
PyObject *cp = PyObject_GetAttrString(jcc, "CLASSPATH");
if (classpath)
add_paths("-Djava.class.path=", PyString_AsString(cp), classpath,
&vm_options[nOptions++]);
else
add_option("-Djava.class.path=", PyString_AsString(cp),
&vm_options[nOptions++]);
Py_DECREF(cp);
Py_DECREF(jcc);
#else
if (classpath)
add_option("-Djava.class.path=", classpath,
&vm_options[nOptions++]);
#endif
Py_XDECREF(module_cp);
if (initialheap)
add_option("-Xms", initialheap, &vm_options[nOptions++]);
if (maxheap)
add_option("-Xmx", maxheap, &vm_options[nOptions++]);
if (maxstack)
add_option("-Xss", maxstack, &vm_options[nOptions++]);
if (vmargs)
{
#ifdef _MSC_VER
char *buf = _strdup(vmargs);
#else
char *buf = strdup(vmargs);
#endif
char *sep = ",";
char *option;
for (option = strtok(buf, sep); option; option = strtok(NULL, sep))
{
if (nOptions < sizeof(vm_options) / sizeof(JavaVMOption))
add_option("", option, &vm_options[nOptions++]);
else
{
free(buf);
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
PyErr_Format(PyExc_ValueError, "Too many options (> %d)",
nOptions);
return NULL;
}
}
free(buf);
}
//vm_options[nOptions++].optionString = "-verbose:gc";
//vm_options[nOptions++].optionString = "-Xcheck:jni";
vm_args.nOptions = nOptions;
vm_args.ignoreUnrecognized = JNI_FALSE;
vm_args.options = vm_options;
if (JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args) < 0)
{
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
PyErr_Format(PyExc_ValueError,
"An error occurred while creating Java VM");
return NULL;
}
env->set_vm(vm, vm_env);
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
t_jccenv *jccenv = (t_jccenv *) PY_TYPE(JCCEnv).tp_alloc(&PY_TYPE(JCCEnv), 0);
jccenv->env = env;
#ifdef _jcc_lib
registerNatives(vm_env);
#endif
return (PyObject *) jccenv;
}
}
Okay, so I've got the solution I was after. The solution is an update to the following segment of the code listed in the question:
if (JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args) < 0)
{
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
PyErr_Format(PyExc_ValueError,
"An error occurred while creating Java VM");
return NULL;
}
The adaptation supports the construction of a more detailed error message which adds two specific pieces of information:
The error code (if any) which is returned by the JNI_CreateJavaVM method;
The detailed Java exception which occurs in the event that such an error code arises.
The above snippet from the original code was replaced with the following:
vmInitSuccess = JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args);
if (vmInitSuccess < 0)
{
for (unsigned int i = 0; i < nOptions; i++)
delete vm_options[i].optionString;
//Set up basic error message
sprintf(strVMInitSuccess, "%d", vmInitSuccess);
strcpy(strVMError, "An error occurred while creating Java VM (No Exception): ");
strcat(strVMError, strVMInitSuccess);
//Get exception if there is one
if((exc = vm_env->ExceptionOccurred()))
{
//Clear the exception since we have it now
vm_env->ExceptionClear();
//Get the getMessage() method
if ((java_class = vm_env->FindClass ("java/lang/Throwable")))
{
if ((method = vm_env->GetMethodID(java_class, "getMessage", "()Ljava/lang/String;")))
{
int size;
strExc = static_cast<jstring>(vm_env->CallObjectMethod(exc, method));
charExc = vm_env->GetStringUTFChars(strExc, NULL);
size = sizeof(strVMError) + sizeof(charExc);
char strVMException[size];
strcpy(strVMException, "An error occurred while creating Java VM (Exception): ");
strcat(strVMException, charExc);
PyErr_Format(PyExc_ValueError, strVMException);
return NULL;
}
}
}
PyErr_Format(PyExc_ValueError, strVMError);
return NULL;
}
Thanks to #Parsifal for help with this solution.

Categories