-
Enhancement
-
Resolution: Fixed
-
P3
-
None
-
repo-panama
The main way to create unsafe native segments is by using the MemorySegment::ofAddress API. For instance, to create a new segment with new size and scope from an unsafe segment obtained from the linker one can do the following:
MemorySegment malloc(long size, Arena arena) {
MemorySegment raw = <MALLOC_HANDLE>.invokeExact(size);
return MemorySegment.ofAddress(raw.address(), size, arena, () -> StdLib.free(raw));
}
The above code is suboptimal in a number of ways:
* clients need a throwaway local variable where to store the raw segment returned from the linker API;
* to create a new segment with ofAddress, one has to retrieve the address from the old segment and pass it to the factory;
* the cleanup action has to carefully refer to the old segment - that's because the new segment will be invalidated when the arena is closed.
The API should have a better way to deal with this situation, which can be very common when attempting to retroactively secure segments allocated from native libraries.
MemorySegment malloc(long size, Arena arena) {
MemorySegment raw = <MALLOC_HANDLE>.invokeExact(size);
return MemorySegment.ofAddress(raw.address(), size, arena, () -> StdLib.free(raw));
}
The above code is suboptimal in a number of ways:
* clients need a throwaway local variable where to store the raw segment returned from the linker API;
* to create a new segment with ofAddress, one has to retrieve the address from the old segment and pass it to the factory;
* the cleanup action has to carefully refer to the old segment - that's because the new segment will be invalidated when the arena is closed.
The API should have a better way to deal with this situation, which can be very common when attempting to retroactively secure segments allocated from native libraries.