英文:
JNI: Protect field from dangerous reflective access
问题
I'm designing a Java library that uses a piece of native code exposed via the JNI. The library provides a class that is mapped to a complex native struct that can't easily be serialized. It's not decided yet whether I should store this struct in a ByteBuffer
field, or have an int
field referring to an index in an array of initialized structs.
In both situations, there's a potential issue where user code could try to modify the ByteBuffer
/int
, and cause undefined behavior (illegal struct bit representation, out-of-bounds array access, ...). Of course, it isn't in the user's interest to mess with private fields through reflection, but I see Java as a safe language (in terms of UBs or segfaults) and the mere possibility of these kind of issues being rendered possible by my fault annoys me.
Does Java have a way to enforce actual encapsulation, so the fields would actually be completely private? How do other native libraries deal with this, if they even care in the first place?
Thanks for any help.
英文:
I'm designing a Java library that uses a piece of native code exposed via the JNI. The library provides a class that is mapped to a complex native struct that can't easily be serialized. It's not decided yet whether I should store this struct in a ByteBuffer
field, or have an int
field referring to an index in an array of initialized structs.
In both situations, there's a potential issue where user code could try to modify the ByteBuffer
/int
, and cause undefined behavior (illegal struct bit representation, out-of-bounds array access, ...). Of course, it isn't in the user's interest to mess with private fields through reflection, but I see Java as a safe language (in terms of UBs or segfaults) and the mere possibility of these kind of issues being rendered possible by my fault annoys me.
Does Java have a way to enforce actual encapsulation, so the fields would actually be completely private? How do other native libraries deal with this, if they even care in the first place?
Thanks for any help.
答案1
得分: 0
只有最后的 final
原语不能通过反射修改。但说实话,我不知道如何使用Java代码来修改完全在JVM之外并仅由JNI代码管理的数据结构(好吧,Java代码可以调用JNI代码提供的API来修改数据结构,但这里不是指的那个)。
所根据您的描述,您应该安全地使用整数作为索引到“external”结构中。
英文:
At the very end, only final
primitives cannot be modified through reflection. But to be honest, I have no idea how I could use Java code to modify a data structure that is hold completely outside the JVM and managed only by JNI code (ok, the Java code can call the API provided by the JNI code to modify that data structure, but that's not meant here).
So based on your description, you should be save with the integer used as an index into the 'external' structs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论