The code generated by jextract requires to use --enable-native-access where it should not

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Sep 19 11:28:02 UTC 2024


On 19/09/2024 11:45, Jonathan Rosenne wrote:

> One cannot rely on the C code being proper or safe. The C code may
> define an array of a single int but actually use it for a much larger
> array, or even use the variable for a completely different purpose. This
>   is a "feature" of C, after all. So the default of jextract should not
> be changed. However, if the user of jextract is certain that it is safe,
>   then it is conceivable to provide such an option, whether global or
> specific to a specific pointer.

I suppose what I’m asking is a bit different - e.g. not saying we should 
trust all C pointers. More the opposite.

Say we have a C function like this:

|char* API_VERSION(void); |

Then jextract will generate a binding for it, like so:

|MemorySegment API_VERSION(); |

The question is: how do you interact with this binding? In the current 
“unsafe” world you can do this:

|String apiVersion = API_VERSION.getString(0); |

Note that, for this to work, you need an unsafe derefrence of the 
pointer returned by the C function. This is why jextract code needs 
“—enable-native-access”.

An alternative would be to just leave C pointers as zero-length memory 
segments [1]. So that this code:

|String apiVersion = API_VERSION.getString(0) // throws IndexOutOfBounds |

Will fail - as we’re attempting to read from a segment whose size is 
zero. Instead, this would be required:

|String apiVersion = API_VERSION.reinterpret(someLength).getString(0) // ok |

What is |someLength| ? Maybe the client knows - however, in most cases, 
esp. for strings, my feeling is that the client does not know (which is 
why we opted for unsafely reinterpreting all C pointers to Long.MAX_VALUE).

And, note that we have just moved where the unsafe operation occurs: 
instead of having the unsafe resize happen inside jextract generated 
code, the resize here would be explicit in the client code. So it’s not 
like the resulting code would be any safer, just more explicit (which, 
for some use cases, might be a good thing).

Maurizio

​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/jextract-dev/attachments/20240919/cfa2fd47/attachment.htm>


More information about the jextract-dev mailing list