[foreign-abi] RFR 8237899: Add support for scoped allocation

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Mon Jan 27 19:14:23 UTC 2020


Hi,
after having programmed a quite a bit with both the old and new jextract 
bindings, I noted a mismatch (which was recently pointed out by Michael 
too); in C local variables are just... variables allocated on stack. If 
you need a pointer to them, you can just use C's dereference operator 
(&) and be done.

In Panama-ized code, going from a regular variable (e.g. an int) to a 
variable that can be dereferenced (e.g. a MemoryAddress containing an 
int) is quite convoluted - and involves creating a segment and filling 
its contents with the desired value (in the old API, we could use 
Pointer - but same story holds). Even worse, the Panama model forces a 
malloc for each variable, where in the C code all such variables are 
stack-allocated at basically zero cost.

On top of the performance issue, there's also a usability issue, in that 
the user is responsible for manually cleaning up all such variable 
segments at the end of the method.

The solution is to build a so called AllocationScope on top of a 
segment, of fixed size, which makes a single upfront allocation request 
(using malloc, for now) and then keeps returning slices from that same 
segment. The allocation scope makes use of the acquire() API, to make 
sure that returned segments cannot be closed by the user - deallocation 
happens when the entire allocation scope is closed.

A number of overloads allows to support the allocate/initialize pattern 
so that a new int variable can be created as follows:

scope.allocate(C_INT, 42)

This relatively simple API massively simplifies the task of turning C 
code into Panama code, at least in the examples I've come across, and 
should help reducing allocation bottlenecks too (although we should do 
more investigation as to whether something better than malloc/free can 
be used here).

Webrev:

http://cr.openjdk.java.net/~mcimadamore/panama/8237899/

Maurizio





More information about the panama-dev mailing list