前提条件:已下载openjdk的源码。

以System类的arraycopy为例:

1. 根据关键字定位文件:grep -rn '"arraycopy"' ./openjdk
关键字:"arraycopy"
文件:./openjdk/jdk/src/share/native/java/lang/System.c

/* Only register the performance-critical methods */
static JNINativeMethod methods[] = {
  {"currentTimeMillis", "()J", (void *)&JVM_CurrentTimeMillis},
  {"nanoTime", "()J", (void *)&JVM_NanoTime},
  {"arraycopy", "(" OBJ "I" OBJ "II)V", (void *)&JVM_ArrayCopy},
};

2. 然后查找JVM_ArrayCopy的实现:grep -rn 'JVM_ArrayCopy' ./hotspot
文件:./openjdk/hotspot/src/share/vm/prims/jvm.cpp
关键字:JVM_ArrayCopy

JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos, jobject dst, jint dst_pos, jint length))
  JVMWrapper("JVM_ArrayCopy");
  // Check if we have null pointers
  if (src == NULL || dst == NULL) {
    THROW(vmSymbols::java_lang_NullPointerException());
  }
  arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
  arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
  assert(s->is_oop(), "JVM_ArrayCopy: src not an oop");
  assert(d->is_oop(), "JVM_ArrayCopy: dst not an oop");
  // Do copy
  s->klass()->copy_array(s, src_pos, d, dst_pos, length, thread);
JVM_END

3. 想看看类arrayOop的定义:但是用 grep -rn 'class arrayOop' ./hotspot 查不到结果
于是 grep -rn 'arrayOop' ./hotspot 从输出中一行一行排查,结果发现./openjdk/hotspot/src/share/vm/oops/oopsHierarchy.hpp文件中有一行:
typedef class arrayOopDesc* arrayOop;
这又是什么语法呢?

不管如何,定位jdk native方法的c++源码,大致流程如上。

其实文件命名应该是有规律可循的,System.java对应System.c文件,而Unsafe.java对应的却是unsafe.cpp文件。