On Thu, 28 May 2026 21:56:58 GMT, Vladimir Ivanov <[email protected]> wrote:

>> On bytecode level booleans are represented as ints and HotSpot JVM 
>> normalizes boolean values on memory accesses. It unconditionally applies 
>> normalization on boolean stores, but trusts on-heap boolean locations to 
>> hold normalized values. Normalization is applied on loads for off-heap and 
>> mismatched unsafe accesses .  
>> 
>> There are 2 normalization procedures used: (1) cast int to byte and test it 
>> against zero; and (2) truncation to least-significant bit.  Truncation is 
>> preferred (due to performance considerations), but JNI mandates testing 
>> against zero and, historically, `#1` was used for off-heap unsafe accesses 
>> as well. It complicated the implementation (leading to subtle bugs) and 
>> introduced divergence in behavior at runtime (depending on execution mode 
>> and JIT-compilation peculiarities). 
>> 
>> The fix uses truncation uniformly across all execution modes. It simplifies 
>> implementation and eliminates possible divergence in behavior between 
>> execution modes. Also, it drastically simplifies future Unsafe API 
>> refactorings.
>> 
>> There's one scenario left when it's possible to observe non-normalized 
>> values: when mismatched access pollutes the Java heap with a bogus boolean 
>> value, but then the value is read with a well-typed boolean access.
>> 
>> Testing: hs-tier1 - hs-tier6
>>  
>> - [x] I confirm that I make this contribution in accordance with the 
>> [OpenJDK Interim AI Policy](https://openjdk.org/legal/ai).
>
> Vladimir Ivanov has updated the pull request incrementally with one 
> additional commit since the last revision:
> 
>   normalize_for_read/normalize_for_write => normalize

test/hotspot/jtreg/compiler/unsafe/UnsafeBooleanTest.java line 170:

> 168:         }
> 169:     }
> 170: 

// Model what we expect the interpreter and/or JIT to do
// when accessing a boolean in memory.  The `x!=0`
// behavior is historical, while `x&1` (truncation) is current.
// Note that the interpreter and/or JIT sometimes omit
// the normalization step, if the boolean in question is
// a being READ from a Java heap variable that is strongly
// typed as a boolean.  (Not an unsafely generated address,
// not off-heap.)  When WRITING booleans to the Java heap,
// the interpreter and JIT both make sure to normalize as `x&1`,
// so the Java heap is never polluted.

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/31249#discussion_r3321054829

Reply via email to