如何加载JDK的本机方法? [英] How are native methods for JDK loaded?

查看:86
本文介绍了如何加载JDK的本机方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读JDK源代码时,我发现有些方法是本机的,但是它们的静态块中没有System.loadLibrarySystem.load,那么这些方法实际上是如何装载的?

While reading JDK source code, I found that some methods are native, but there's no System.loadLibrary or System.load in their static block, so how are those methods actually loaded?

所以我想那些方法是内置在JVM中的.只是想知道如何为特定类加载它们.说,StrictMath.如下:

So I guess those methods are built-in in the JVM. Just wonder how are them loaded for specific class. Say, StrictMath. As follows:

public final StrictMath {
    public static native double cos(double a);
}

所以我可以找到此本地方法的源代码,只是想知道如何为该特定类加载它.

So I can find the source code for this native method, just wonder how is it loaded for this specific class.

推荐答案

除非第一个调用JNI

The binding of all native methods is performed lazily on the first invocation, unless those methods were explicitly bound earlier by a call to JNI RegisterNatives function.

因此,在首次调用本机方法时,JVM要求动态链接器在已加载的共享库之一中找到名为Java_package_Class_method的符号.例如,在Linux上,调用 dlsym 会执行工作.

So, on the first invocation of a native method JVM asks the dynamic linker to find a symbol named Java_package_Class_method in one of the loaded shared libraries. For instance, on Linux a call to dlsym does the job.

对于StrictMath方法,不需要调用System.loadLibrary,因为带有StrictMath符号的共享库(在Linux上是libjava.so在Windows上是java.dll)已被加载.实际上,JVM会在启动阶段的早期就加载libjava.so,因为该库包含VM引导所需的核心Java方法的本地实现.

As to StrictMath methods, there is no need to call System.loadLibrary, because the shared library with StrictMath symbols (libjava.so on Linux or java.dll on Windows) is already loaded. Actually, JVM loads libjava.so early at start up phase, because this library contains the native implementation of the core Java methods required for VM bootstrap.

检查libjava.so包含哪些符号:

$ nm /usr/java/jdk-11.0.1/lib/libjava.so | grep Java_

....
00000000000146c0 T Java_java_lang_StrictMath_acos
00000000000146b0 T Java_java_lang_StrictMath_asin
00000000000146d0 T Java_java_lang_StrictMath_atan
0000000000014710 T Java_java_lang_StrictMath_atan2
0000000000014680 T Java_java_lang_StrictMath_cos
0000000000014730 T Java_java_lang_StrictMath_cosh
0000000000014770 T Java_java_lang_StrictMath_expm1
...

这篇关于如何加载JDK的本机方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆