Introducing PaddingLayout 2 – Foreign (Function) Memory API

0 Comments

Hooking size, alignment, stride, and padding

Before continuing working with padding, we need to cover some notions which are closely related to each other and work hand in hand with padding.

Hooking size

By size, we understand the amount of memory (in bytes/bits) occupied by a memory layout (data type, C-like struct, C-like union, sequence layout, and so on). We know that a Java int consumes 4 bytes, a Java byte consumes 1 byte, a C-like struct consumes a number of bytes calculated as the sum of each property’s size, a C-like union consumes a number of bytes equal to the bigger property’s size, and so on.We can easily query the size via byteSize()/bitSize(). Here it is some examples:

long size = ValueLayout.JAVA_INT.byteSize();   // 4
long size = ValueLayout.JAVA_BYTE.byteSize();  // 1
long size = npStruct.byteSize();               // 8
long size = wpStruct.byteSize();               // 16

The npStruct and wpStruct have been introduced earlier in this problem.

Hooking alignment

We know that each member layout starts in a memory segment at a specific address. We say that this address is k-byte aligned if this address is a multiple of k (where k is any power of 2) or if this address is evenly divisible by k. Commonly, k is 1, 2, 4, or 8. Alignment is useful for sustaining CPU performance which reads data in chunks of k bytes instead of reading byte-by-byte. If CPU attempts to access a member layout that is not correctly aligned then we’ll get an IllegalArgumentException: Misaligned access at address …In the case of basic data types (int, double, float, byte, char, and so on) the alignment value is equal to their size. For instance, an 8-bit (1 byte) Java byte has a size of 1 byte and needs to be aligned to 1 byte. A 32-bit (4 bytes) Java int has a size of 4 bytes and needs to be aligned to 4 bytes. In the case of a C-like struct/union, the alignment is the maximum alignment of all its member layouts.We can easily query the size via byteAlignment()/bitAlignment(). Here it is some examples:

long align = ValueLayout.JAVA_INT.byteAlignment();   // 4
long align = ValueLayout.JAVA_BYTE.byteAlignment();  // 1
long align = npStruct.byteAlignment();               // 4
long align = wpStruct.byteAlignment();               // 4

So, in a nutshell, a member layout should start with an address that must be at a multiple of its alignment. This applies to any kind of member layout (basic data type, C-like struct, C-like union, and so on).


Leave a Reply

Your email address will not be published. Required fields are marked *