2

I had wrote a agent to use the JVMTI on android 9. Code like this, I create an AgentFunction object to monitor the VM. It work's fine.

AgentFunction *agent = 0;

JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM *vm, char *options, void *reserved) {

    agent = new AgentFunction();
    agent->Init(vm);
    agent->ParseOptions(options);
    agent->AddCapability();
    agent->ShowCapabilities();
    agent->RegisterEvent();
    return JNI_OK;
}

Then i want export some interface to java, than user can invoke the JVMTI function directly.

private native boolean applyChangeNative(List<ClassInfo> classes);

The JNI fumction in agent.so

extern "C"
JNIEXPORT jboolean JNICALL Java_com_cc_jvmtiagent_JVMTIFunction_applyChangeNative
        (JNIEnv *jniEnv, jobject, jlong jvmti, jobject classInfo) {

    ...
    jvmtiClassDefinition *def = new jvmtiClassDefinition[total_classes];
    agent->RedefineClasses(total_classes, def);
}

But when invoke the native method applyChangeNative from JAVA, the agent->RedefineClasses crash caused by agent is null. After my test, i found i can't access the object create in JVMTI from JNI.

I had read the JDK souce code , I found it have an InvocationAdapter.cc, When Agent_OnAttach it create the JPLISAgent, then create java.lang.instrument.Instrumentation and save the JPLISAgent in it. Each function from Java will take the JPLISAgent point.

But i want to known , why access the JVMTI object is NULL directly from JNI?


Resolved:

If you want invoke the agent method via JNI, you should use System.Load(agentPath) instead of System.LoadLibrary(libName). It need use the same so file.

It work's on Android 9 and 10, But on Android 8.x, Can't access the agent, i do not know why.

user6361246
  • 93
  • 1
  • 8
  • 1
    I resolved! The agent attached is different from the System.LoadLibrary. – user6361246 Oct 15 '19 at 09:40
  • 1
    It's worth to add an answer with just a couple of words how you acquire the **agent** – Alex Cohn Oct 15 '19 at 15:30
  • 1
    On android 9, you can use the Debug.attachJvmtiAgent(agentPath) method to attach the agent. If you want invoke the agent via JNI, you should use System.Load(agentPath) instead of System.LoadLibrary(libName). Otherwise you can't access the object create in agent vim JNI because there different. – user6361246 Oct 15 '19 at 15:36
  • Thanks! I meant that an [answer](https://stackoverflow.com/help/self-answer) would be more visible and have a good chance to help others – Alex Cohn Oct 15 '19 at 21:25

0 Answers0