From 1c69a5cf0f50901dcb0fe0abc9e79006f11b6214 Mon Sep 17 00:00:00 2001 From: Kevin Walls Date: Thu, 19 Nov 2026 09:09:15 +0000 Subject: [PATCH 01/95] 8397572: RMIConnector needs to handle a possible null from FilterInfo.serialClass() Reviewed-by: sspitsyn, alanb --- .../classes/javax/management/remote/rmi/RMIConnector.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java index c2bed0c1b78..70c37dca7ad 100644 --- a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java +++ b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java @@ -1871,6 +1871,9 @@ public Status checkInput(FilterInfo info) { // Finally, permit client socket factory or RMIServer, to avoid requiring an exhaustive filter. // Otherwise, return REJECTED. Class c = info.serialClass(); + if (c == null) { + return Status.UNDECIDED; + } if (RMIClientSocketFactory.class.isAssignableFrom(c) || RMIServer.class.isAssignableFrom(c)) { return Status.ALLOWED; From a9e1d4faff39f42fee8d4815490b1bb433193926 Mon Sep 17 00:00:00 2001 From: David Briemann Date: Thu, 19 Nov 2026 09:58:50 +0000 Subject: [PATCH 02/95] 8396119: [PPC64] Use VSX instructions for MoveI2F and MoveF2I Reviewed-by: mdoerr, rrich --- src/hotspot/cpu/ppc/assembler_ppc.hpp | 6 + src/hotspot/cpu/ppc/assembler_ppc.inline.hpp | 4 + src/hotspot/cpu/ppc/foreignGlobals_ppc.cpp | 6 +- src/hotspot/cpu/ppc/macroAssembler_ppc.hpp | 3 + .../cpu/ppc/macroAssembler_ppc.inline.hpp | 17 ++ src/hotspot/cpu/ppc/ppc.ad | 228 +++--------------- 6 files changed, 63 insertions(+), 201 deletions(-) diff --git a/src/hotspot/cpu/ppc/assembler_ppc.hpp b/src/hotspot/cpu/ppc/assembler_ppc.hpp index 37eee6e670d..5f10495608e 100644 --- a/src/hotspot/cpu/ppc/assembler_ppc.hpp +++ b/src/hotspot/cpu/ppc/assembler_ppc.hpp @@ -546,6 +546,7 @@ class Assembler : public AbstractAssembler { MTVSRD_OPCODE = (31u << OPCODE_SHIFT | 179u << 1), MTVSRDD_OPCODE = (31u << OPCODE_SHIFT | 435u << 1), MTVSRWZ_OPCODE = (31u << OPCODE_SHIFT | 243u << 1), + MTVSRWS_OPCODE = (31u << OPCODE_SHIFT | 403u << 1), MFVSRD_OPCODE = (31u << OPCODE_SHIFT | 51u << 1), MFVSRLD_OPCODE = (31u << OPCODE_SHIFT | 307u << 1), MTVSRWA_OPCODE = (31u << OPCODE_SHIFT | 211u << 1), @@ -579,6 +580,7 @@ class Assembler : public AbstractAssembler { XVSQRTSP_OPCODE= (60u << OPCODE_SHIFT | 139u << 2), XVSQRTDP_OPCODE= (60u << OPCODE_SHIFT | 203u << 2), XSCVDPSPN_OPCODE=(60u << OPCODE_SHIFT | 267u << 2), + XSCVSPDPN_OPCODE=(60u << OPCODE_SHIFT | 331u << 2), XVADDDP_OPCODE = (60u << OPCODE_SHIFT | 96u << 3), XVSUBDP_OPCODE = (60u << OPCODE_SHIFT | 104u << 3), XVMULSP_OPCODE = (60u << OPCODE_SHIFT | 80u << 3), @@ -2420,6 +2422,7 @@ class Assembler : public AbstractAssembler { inline void mfvsrld( Register d, VectorSRegister a); // Requires Power9. inline void mtvsrdd( VectorSRegister d, Register a, Register b); inline void mtvsrwz( VectorSRegister d, Register a); + inline void mtvsrws( VectorSRegister d, Register a); // Requires Power9. inline void mfvsrwz( Register d, VectorSRegister a); inline void xxspltw( VectorSRegister d, VectorSRegister b, int ui2); inline void xxlor( VectorSRegister d, VectorSRegister a, VectorSRegister b); @@ -2446,6 +2449,7 @@ class Assembler : public AbstractAssembler { inline void xvsqrtsp( VectorSRegister d, VectorSRegister b); inline void xvsqrtdp( VectorSRegister d, VectorSRegister b); inline void xscvdpspn(VectorSRegister d, VectorSRegister b); + inline void xscvspdpn(VectorSRegister d, VectorSRegister b); inline void xvadddp( VectorSRegister d, VectorSRegister a, VectorSRegister b); inline void xvsubdp( VectorSRegister d, VectorSRegister a, VectorSRegister b); inline void xvmulsp( VectorSRegister d, VectorSRegister a, VectorSRegister b); @@ -2479,6 +2483,8 @@ class Assembler : public AbstractAssembler { // Vector-Scalar (VSX) instructions. inline void mtfprd( FloatRegister d, Register a); inline void mtfprwa( FloatRegister d, Register a); + inline void mtfprwz( FloatRegister d, Register a); + inline void mtfprws( FloatRegister d, Register a); // Requires Power9. inline void mffprd( Register a, FloatRegister d); // Deliver A Random Number (introduced with POWER9) diff --git a/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp b/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp index 75a2e35d940..e2399bdc757 100644 --- a/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp +++ b/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp @@ -866,6 +866,7 @@ inline void Assembler::mtvsrdd( VectorSRegister d, Register a, Register b) { e inline void Assembler::mfvsrd( Register d, VectorSRegister a) { emit_int32( MFVSRD_OPCODE | vsrs(a) | ra(d)); } inline void Assembler::mfvsrld( Register d, VectorSRegister a) { emit_int32( MFVSRLD_OPCODE | vsrs(a) | ra(d)); } inline void Assembler::mtvsrwz( VectorSRegister d, Register a) { emit_int32( MTVSRWZ_OPCODE | vsrt(d) | ra(a)); } +inline void Assembler::mtvsrws( VectorSRegister d, Register a) { emit_int32( MTVSRWS_OPCODE | vsrt(d) | ra(a)); } inline void Assembler::mfvsrwz( Register d, VectorSRegister a) { emit_int32( MFVSRWZ_OPCODE | vsrs(a) | ra(d)); } inline void Assembler::xxspltib(VectorSRegister d, int ui8) { emit_int32( XXSPLTIB_OPCODE | vsrt(d) | imm8(ui8)); } inline void Assembler::xxspltw( VectorSRegister d, VectorSRegister b, int ui2) { emit_int32( XXSPLTW_OPCODE | vsrt(d) | vsrb(b) | xxsplt_uim(uimm(ui2,2))); } @@ -888,6 +889,7 @@ inline void Assembler::xvnegdp( VectorSRegister d, VectorSRegister b) inline void Assembler::xvsqrtsp(VectorSRegister d, VectorSRegister b) { emit_int32( XVSQRTSP_OPCODE| vsrt(d) | vsrb(b)); } inline void Assembler::xvsqrtdp(VectorSRegister d, VectorSRegister b) { emit_int32( XVSQRTDP_OPCODE| vsrt(d) | vsrb(b)); } inline void Assembler::xscvdpspn(VectorSRegister d, VectorSRegister b) { emit_int32( XSCVDPSPN_OPCODE | vsrt(d) | vsrb(b)); } +inline void Assembler::xscvspdpn(VectorSRegister d, VectorSRegister b) { emit_int32( XSCVSPDPN_OPCODE | vsrt(d) | vsrb(b)); } inline void Assembler::xvadddp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVADDDP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } inline void Assembler::xvsubdp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVSUBDP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } inline void Assembler::xvmulsp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVMULSP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } @@ -934,6 +936,8 @@ inline void Assembler::xxswapd( VectorSRegister d, VectorSRegister a) // Vector-Scalar (VSX) instructions. inline void Assembler::mtfprd( FloatRegister d, Register a) { emit_int32( MTVSRD_OPCODE | frt(d) | ra(a)); } inline void Assembler::mtfprwa( FloatRegister d, Register a) { emit_int32( MTVSRWA_OPCODE | frt(d) | ra(a)); } +inline void Assembler::mtfprwz( FloatRegister d, Register a) { emit_int32( MTVSRWZ_OPCODE | frt(d) | ra(a)); } +inline void Assembler::mtfprws( FloatRegister d, Register a) { emit_int32( MTVSRWS_OPCODE | frt(d) | ra(a)); } inline void Assembler::mffprd( Register a, FloatRegister d) { emit_int32( MFVSRD_OPCODE | frt(d) | ra(a)); } inline void Assembler::vpkpx( VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VPKPX_OPCODE | vrt(d) | vra(a) | vrb(b)); } diff --git a/src/hotspot/cpu/ppc/foreignGlobals_ppc.cpp b/src/hotspot/cpu/ppc/foreignGlobals_ppc.cpp index 49830ba8f96..c23668cf714 100644 --- a/src/hotspot/cpu/ppc/foreignGlobals_ppc.cpp +++ b/src/hotspot/cpu/ppc/foreignGlobals_ppc.cpp @@ -109,8 +109,7 @@ static void move_reg64(MacroAssembler* masm, int out_stk_bias, // FP arguments can get passed in GP reg! (Only in Upcall with HFA usage.) assert(from_reg.segment_mask() == to_reg.segment_mask(), "sanity"); if (to_reg.segment_mask() == REG32_MASK) { - __ stw(as_Register(from_reg), -8, R1_SP); - __ lfs(as_FloatRegister(to_reg), -8, R1_SP); // convert to double precision format + __ intBitsToFloat(as_FloatRegister(to_reg), as_Register(from_reg)); } else { __ mtfprd(as_FloatRegister(to_reg), as_Register(from_reg)); } @@ -142,8 +141,7 @@ static void move_float(MacroAssembler* masm, int out_stk_bias, // FP arguments can get passed in GP reg! (Only for VarArgs for which we don't use FP regs.) assert(from_reg.segment_mask() == to_reg.segment_mask(), "sanity"); if (from_reg.segment_mask() == REG32_MASK) { - __ stfs(as_FloatRegister(from_reg), -8, R1_SP); // convert to single precision format - __ lwa(as_Register(to_reg), -8, R1_SP); + __ floatToIntBits(as_Register(to_reg), as_FloatRegister(from_reg), F0_SCRATCH); } else { __ mffprd(as_Register(to_reg), as_FloatRegister(from_reg)); } diff --git a/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp b/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp index 85311e1702c..d6596a127de 100644 --- a/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp +++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp @@ -187,6 +187,9 @@ class MacroAssembler: public Assembler { // Convert between half precision float encoded into a short and a float in a FloatRegister. void inline f2hf(Register dst, FloatRegister src, FloatRegister tmp); void inline hf2f(FloatRegister dst, Register src); + // Bitwise move between an int and a float (reinterpret, not a numeric conversion). + void inline intBitsToFloat(FloatRegister dst, Register src); + void inline floatToIntBits(Register dst, FloatRegister src, FloatRegister tmp); inline void pd_patch_instruction(address branch, address target, const char* file, int line); NOT_PRODUCT(static void pd_print_patched_instruction(address branch);) diff --git a/src/hotspot/cpu/ppc/macroAssembler_ppc.inline.hpp b/src/hotspot/cpu/ppc/macroAssembler_ppc.inline.hpp index 440b8e72dbe..b13fbc8819f 100644 --- a/src/hotspot/cpu/ppc/macroAssembler_ppc.inline.hpp +++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.inline.hpp @@ -303,6 +303,23 @@ inline void MacroAssembler::hf2f(FloatRegister dst, Register src) { xscvhpdp(dst->to_vsr(), dst->to_vsr()); } +inline void MacroAssembler::intBitsToFloat(FloatRegister dst, Register src) { + // Single precision values in FloatRegisters use double precision format on PPC64. + if (PowerArchitecturePPC64 >= 9) { + mtfprws(dst, src); // Move int into all word elements. + } else { + mtfprwz(dst, src); // Move int into word element 1. + xxspltw(dst->to_vsr(), dst->to_vsr(), 1); // Replicate it into word element 0. + } + xscvspdpn(dst->to_vsr(), dst->to_vsr()); // Convert from word element 0. +} + +inline void MacroAssembler::floatToIntBits(Register dst, FloatRegister src, FloatRegister tmp) { + // Single precision values in FloatRegisters use double precision format on PPC64. + xscvdpspn(tmp->to_vsr(), src->to_vsr()); + mfvsrwz(dst, tmp->to_vsr()); +} + // Convenience bc_far versions inline void MacroAssembler::blt_far(ConditionRegister crx, Label& L, int optimize) { MacroAssembler::bc_far(bcondCRbiIs1, bi0(crx, less), L, optimize); } inline void MacroAssembler::bgt_far(ConditionRegister crx, Label& L, int optimize) { MacroAssembler::bc_far(bcondCRbiIs1, bi0(crx, greater), L, optimize); } diff --git a/src/hotspot/cpu/ppc/ppc.ad b/src/hotspot/cpu/ppc/ppc.ad index b14471333d7..8990e0c1558 100644 --- a/src/hotspot/cpu/ppc/ppc.ad +++ b/src/hotspot/cpu/ppc/ppc.ad @@ -2928,14 +2928,6 @@ encode %{ __ bind(done); %} - enc_class enc_cmove_bso_stackSlotL(iRegLdst dst, flagsRegSrc crx, stackSlotL mem ) %{ - int Idisp = $mem$$disp + frame_slots_bias($mem$$base, ra_); - Label done; - __ bso($crx$$CondRegister, done); - __ ld($dst$$Register, Idisp, $mem$$base$$Register); - __ bind(done); - %} - enc_class enc_bc(flagsRegSrc crx, cmpOp cmp, Label lbl) %{ Label d; // dummy __ bind(d); @@ -4409,76 +4401,6 @@ operand indOffset16NarrowAlg4_klass(iRegNsrc reg, immL16Alg4 offset) %{ %} %} -//----------Special Memory Operands-------------------------------------------- -// Stack Slot Operand -// -// This operand is used for loading and storing temporary values on -// the stack where a match requires a value to flow through memory. -operand stackSlotI(sRegI reg) %{ - constraint(ALLOC_IN_RC(stack_slots)); - op_cost(100); - //match(RegI); - format %{ "[sp+$reg]" %} - interface(MEMORY_INTER) %{ - base(0x1); // R1_SP - index(0x0); - scale(0x0); - disp($reg); // Stack Offset - %} -%} - -operand stackSlotL(sRegL reg) %{ - constraint(ALLOC_IN_RC(stack_slots)); - op_cost(100); - //match(RegL); - format %{ "[sp+$reg]" %} - interface(MEMORY_INTER) %{ - base(0x1); // R1_SP - index(0x0); - scale(0x0); - disp($reg); // Stack Offset - %} -%} - -operand stackSlotP(sRegP reg) %{ - constraint(ALLOC_IN_RC(stack_slots)); - op_cost(100); - //match(RegP); - format %{ "[sp+$reg]" %} - interface(MEMORY_INTER) %{ - base(0x1); // R1_SP - index(0x0); - scale(0x0); - disp($reg); // Stack Offset - %} -%} - -operand stackSlotF(sRegF reg) %{ - constraint(ALLOC_IN_RC(stack_slots)); - op_cost(100); - //match(RegF); - format %{ "[sp+$reg]" %} - interface(MEMORY_INTER) %{ - base(0x1); // R1_SP - index(0x0); - scale(0x0); - disp($reg); // Stack Offset - %} -%} - -operand stackSlotD(sRegD reg) %{ - constraint(ALLOC_IN_RC(stack_slots)); - op_cost(100); - //match(RegD); - format %{ "[sp+$reg]" %} - interface(MEMORY_INTER) %{ - base(0x1); // R1_SP - index(0x0); - scale(0x0); - disp($reg); // Stack Offset - %} -%} - // Operands for expressing Control Flow // NOTE: Label is a predefined operand which should not be redefined in // the AD file. It is generically handled within the ADLC. @@ -8886,10 +8808,9 @@ instruct andcL_reg_reg(iRegLdst dst, iRegLsrc src1, iRegLsrc src2) %{ //----------Moves between int/long and float/double---------------------------- // -// The following rules move values from int/long registers/stack-locations -// to float/double registers/stack-locations and vice versa, without doing any -// conversions. These rules are used to implement the bit-conversion methods -// of java.lang.Float/Double, e.g. +// The following rules move values from int/long registers to float/double +// registers and vice versa, without doing any value conversion. These rules are +// used to implement the bit-conversion methods of java.lang.Float etc., e.g. // int floatToIntBits(float value) // float intBitsToFloat(int bits) @@ -8926,101 +8847,37 @@ instruct moveI2D_reg(regD dst, iRegIsrc src) %{ ins_pipe(pipe_class_default); %} -//---------- Chain stack slots between similar types -------- - -// These are needed so that the rules below can match. - -// Load integer from stack slot -instruct stkI_to_regI(iRegIdst dst, stackSlotI src) %{ - match(Set dst src); - ins_cost(MEMORY_REF_COST); - - format %{ "LWZ $dst, $src" %} - size(4); - ins_encode( enc_lwz(dst, src) ); - ins_pipe(pipe_class_memory); -%} - -// Store integer to stack slot -instruct regI_to_stkI(stackSlotI dst, iRegIsrc src) %{ - match(Set dst src); - ins_cost(MEMORY_REF_COST); - - format %{ "STW $src, $dst \t// stk" %} - size(4); - ins_encode( enc_stw(src, dst) ); // rs=rt - ins_pipe(pipe_class_memory); -%} - -// Load long from stack slot -instruct stkL_to_regL(iRegLdst dst, stackSlotL src) %{ - match(Set dst src); - ins_cost(MEMORY_REF_COST); - - format %{ "LD $dst, $src \t// long" %} - size(4); - ins_encode( enc_ld(dst, src) ); - ins_pipe(pipe_class_memory); -%} - -// Store long to stack slot -instruct regL_to_stkL(stackSlotL dst, iRegLsrc src) %{ - match(Set dst src); - ins_cost(MEMORY_REF_COST); - - format %{ "STD $src, $dst \t// long" %} - size(4); - ins_encode( enc_std(src, dst) ); // rs=rt - ins_pipe(pipe_class_memory); -%} - //----------Moves between int and float - -// Move float value from float stack-location to integer register. -instruct moveF2I_stack_reg(iRegIdst dst, stackSlotF src) %{ +instruct moveF2I_reg_reg(iRegIdst dst, regF src, regF tmp) %{ match(Set dst (MoveF2I src)); - ins_cost(MEMORY_REF_COST); - - format %{ "LWZ $dst, $src \t// MoveF2I" %} - size(4); - ins_encode( enc_lwz(dst, src) ); - ins_pipe(pipe_class_memory); -%} - -// Move float value from float register to integer stack-location. -instruct moveF2I_reg_stack(stackSlotI dst, regF src) %{ - match(Set dst (MoveF2I src)); - ins_cost(MEMORY_REF_COST); - - format %{ "STFS $src, $dst \t// MoveF2I" %} - size(4); - ins_encode( enc_stfs(src, dst) ); - ins_pipe(pipe_class_memory); -%} - -// Move integer value from integer stack-location to float register. -instruct moveI2F_stack_reg(regF dst, stackSlotI src) %{ - match(Set dst (MoveI2F src)); - ins_cost(MEMORY_REF_COST); + effect(TEMP tmp); - format %{ "LFS $dst, $src \t// MoveI2F" %} - size(4); + format %{ "XSCVDPSPN $tmp, $src \t// MoveF2I\n\t" + "MFVSRWZ $dst, $tmp" %} + size(8); ins_encode %{ - int Idisp = $src$$disp + frame_slots_bias($src$$base, ra_); - __ lfs($dst$$FloatRegister, Idisp, $src$$base$$Register); + __ floatToIntBits($dst$$Register, $src$$FloatRegister, $tmp$$FloatRegister); %} - ins_pipe(pipe_class_memory); + ins_pipe(pipe_class_default); %} -// Move integer value from integer register to float stack-location. -instruct moveI2F_reg_stack(stackSlotF dst, iRegIorL2I src) %{ +instruct moveI2F_reg_reg(regF dst, iRegIorL2I src) %{ match(Set dst (MoveI2F src)); - ins_cost(MEMORY_REF_COST); - format %{ "STW $src, $dst \t// MoveI2F" %} - size(4); - ins_encode( enc_stw(src, dst) ); - ins_pipe(pipe_class_memory); + format %{ $$template + if (PowerArchitecturePPC64 >= 9) { + $$emit$$"MTVSRWS $dst, $src \t// MoveI2F\n\t" + } else { + $$emit$$"MTVSRWZ $dst, $src \t// MoveI2F\n\t" + $$emit$$"XXSPLTW $dst, $dst, 1\n\t" + } + $$emit$$"XSCVSPDPN $dst, $dst" + %} + size((PowerArchitecturePPC64 >= 9 ? 8 : 12)); + ins_encode %{ + __ intBitsToFloat($dst$$FloatRegister, $src$$Register); + %} + ins_pipe(pipe_class_default); %} //----------Register Move Instructions----------------------------------------- @@ -9389,17 +9246,6 @@ instruct convL2I_reg(iRegIdst dst, iRegLsrc src) %{ ins_pipe(pipe_class_default); %} -instruct cmovI_bso_stackSlotL(iRegIdst dst, flagsRegSrc crx, stackSlotL src) %{ - // no match-rule, false predicate - effect(DEF dst, USE crx, USE src); - predicate(false); - - format %{ "CMOVI $crx, $dst, $src" %} - size(8); - ins_encode( enc_cmove_bso_stackSlotL(dst, crx, src) ); - ins_pipe(pipe_class_default); -%} - instruct cmovI_bso_reg_con0(iRegIdst dst, flagsRegSrc crx, regD src) %{ // no match-rule, false predicate effect(DEF dst, USE crx, USE src); @@ -9510,17 +9356,6 @@ instruct zeroExtendL_regL(iRegLdst dst, iRegLsrc src, immL_32bits mask) %{ ins_pipe(pipe_class_default); %} -instruct cmovL_bso_stackSlotL(iRegLdst dst, flagsRegSrc crx, stackSlotL src) %{ - // no match-rule, false predicate - effect(DEF dst, USE crx, USE src); - predicate(false); - - format %{ "CMOVL $crx, $dst, $src" %} - size(8); - ins_encode( enc_cmove_bso_stackSlotL(dst, crx, src) ); - ins_pipe(pipe_class_default); -%} - instruct cmovL_bso_reg_con0(iRegLdst dst, flagsRegSrc crx, regD src) %{ // no match-rule, false predicate effect(DEF dst, USE crx, USE src); @@ -12047,19 +11882,18 @@ instruct repl4I_immIminus1(vecX dst, immI_minus1 src) %{ ins_pipe(pipe_class_default); %} -// Move float to int register via stack, replicate. +// Move float to int register, replicate. instruct repl2F_reg_Ex(iRegLdst dst, regF src) %{ match(Set dst (Replicate src)); predicate(n->as_Vector()->length() == 2 && Matcher::vector_element_basic_type(n) == T_FLOAT); - ins_cost(2 * MEMORY_REF_COST + DEFAULT_COST); + ins_cost(3 * DEFAULT_COST); expand %{ - stackSlotL tmpS; iRegIdst tmpI; - moveF2I_reg_stack(tmpS, src); // Move float to stack. - moveF2I_stack_reg(tmpI, tmpS); // Move stack to int reg. - moveReg(dst, tmpI); // Move int to long reg. - repl32(dst); // Replicate bitpattern. + regF tmpF; + moveF2I_reg_reg(tmpI, src, tmpF); // Move float bits to int reg. + moveReg(dst, tmpI); // Move int to long reg. + repl32(dst); // Replicate bitpattern. %} %} From d65bc4b262564e535c431aa8d4b58a1f7630fa64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20H=C3=A4ssig?= Date: Thu, 19 Nov 2026 10:26:40 +0000 Subject: [PATCH 03/95] 8397679: Unproblemlist tests for closed issues Reviewed-by: mchevalier --- test/hotspot/jtreg/ProblemList-AotJdk.txt | 4 ---- test/jdk/ProblemList.txt | 2 -- 2 files changed, 6 deletions(-) diff --git a/test/hotspot/jtreg/ProblemList-AotJdk.txt b/test/hotspot/jtreg/ProblemList-AotJdk.txt index e772230bc31..27d5ccde9e7 100644 --- a/test/hotspot/jtreg/ProblemList-AotJdk.txt +++ b/test/hotspot/jtreg/ProblemList-AotJdk.txt @@ -58,10 +58,6 @@ compiler/ciReplay/TestInliningProtectionDomain.java 0000000 generic-all # different Java application: TestSetupAOT.java compiler/stringopts/TestStringConcatIR.java 0000000 generic-all -# These tests fail often with AotJdk due to JDK-8323727 -compiler/arguments/TestStressReflectiveCode.java 8323727 generic-all -compiler/arraycopy/TestCloneWithStressReflectiveCode.java 8323727 generic-all - serviceability/sa/TestJhsdbJstackMixedWithXComp.java#xcomp-disable-tiered-compilation 8382548 linux-aarch64 compiler/calls/NativeCalls.java 8383780 generic-all diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index 972c9e06876..eb2f64245d8 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -646,6 +646,4 @@ tools/sincechecker/modules/jdk.management.jfr/JdkManagementJfrCheckSince.java 83 java/awt/image/multiresolution/MultiResolutionToolkitImageTest.java 8375778 macosx-aarch64 -java/util/Arrays/largeMemory/ParallelPrefix.java 8386501 generic-all - sun/tools/jhsdb/JStackStressTest.java 8247940 macosx-aarch64 From 8ef2f5dd58a42a77909639d0c04ca09ebe4cdf73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Gr=C3=B6nlund?= Date: Thu, 19 Nov 2026 11:21:18 +0000 Subject: [PATCH 04/95] 8392362: Lambda proxy classes accumulate after repeated class retransformation Co-authored-by: Alan Bateman Reviewed-by: sspitsyn, apangin, alanb, dholmes --- .../share/classes/java/lang/Class.java | 7 + .../share/classes/java/lang/System.java | 3 + .../invoke/InnerClassLambdaMetafactory.java | 16 +- .../java/lang/runtime/ObjectMethods.java | 17 +- .../java/lang/runtime/SwitchBootstraps.java | 12 +- .../jdk/internal/access/JavaLangAccess.java | 6 + .../lang/instrument/LambdaClassUnloading.java | 253 ++++++++++++++++++ 7 files changed, 307 insertions(+), 7 deletions(-) create mode 100644 test/jdk/java/lang/instrument/LambdaClassUnloading.java diff --git a/src/java.base/share/classes/java/lang/Class.java b/src/java.base/share/classes/java/lang/Class.java index 75fe976311c..a16c86325aa 100644 --- a/src/java.base/share/classes/java/lang/Class.java +++ b/src/java.base/share/classes/java/lang/Class.java @@ -2935,6 +2935,13 @@ private static class ReflectionData { // that redefines this class or a superclass. private transient volatile int classRedefinedCount; + + // Returns whether this class or any of its superclasses has been + // redefined or retransformed. + boolean hasBeenRedefined() { + return classRedefinedCount != 0; + } + // Lazily create and cache ReflectionData private ReflectionData reflectionData() { SoftReference> reflectionData = this.reflectionData; diff --git a/src/java.base/share/classes/java/lang/System.java b/src/java.base/share/classes/java/lang/System.java index 8084f2ef385..fa3f36f446e 100644 --- a/src/java.base/share/classes/java/lang/System.java +++ b/src/java.base/share/classes/java/lang/System.java @@ -2019,6 +2019,9 @@ public Method findMethod(Class klass, boolean publicOnly, String name, Class< public jdk.internal.reflect.ConstantPool getConstantPool(Class klass) { return klass.getConstantPool(); } + public boolean hasBeenRedefined(Class klass) { + return klass.hasBeenRedefined(); + } public boolean casAnnotationType(Class klass, AnnotationType oldType, AnnotationType newType) { return klass.casAnnotationType(oldType, newType); } diff --git a/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java b/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java index 5d65be3976e..5e35cbd7cf4 100644 --- a/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java +++ b/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java @@ -25,6 +25,8 @@ package java.lang.invoke; +import jdk.internal.access.JavaLangAccess; +import jdk.internal.access.SharedSecrets; import jdk.internal.constant.ClassOrInterfaceDescImpl; import jdk.internal.misc.CDS; import jdk.internal.util.ClassFileDumper; @@ -69,6 +71,8 @@ private static final @Stable String[] ARG_NAME_CACHE = {"arg$1", "arg$2", "arg$3", "arg$4", "arg$5", "arg$6", "arg$7", "arg$8"}; private static final ClassDesc[] EMPTY_CLASSDESC_ARRAY = ConstantUtils.EMPTY_CLASSDESC; + private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); + // For dumping generated classes to disk, for debugging purposes private static final ClassFileDumper lambdaProxyClassFileDumper; @@ -351,9 +355,17 @@ else if (finalAccidentallySerializable) // Define the generated class in this VM. try { - // this class is linked at the indy callsite; so define a hidden nestmate + // This class is linked at the indy callsite; so define a hidden nestmate. + // Redefinition or retransformation of the caller can cause lambda call + // sites to be linked again, generating additional proxy classes. + // If the caller or a superclass has been redefined, allow newly generated + // proxies to unload independently of the defining class loader. + int flags = NESTMATE_CLASS; + if (!JLA.hasBeenRedefined(caller.lookupClass())) { + flags |= STRONG_LOADER_LINK; + } var classdata = useImplMethodHandle? implementation : null; - return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, NESTMATE_CLASS | STRONG_LOADER_LINK) + return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, flags) .defineClass(!disableEagerInitialization, classdata); } catch (Throwable t) { diff --git a/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java b/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java index 922ac651f7e..5c9e2964800 100644 --- a/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java +++ b/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java @@ -43,6 +43,9 @@ import java.util.List; import java.util.Objects; +import jdk.internal.access.JavaLangAccess; +import jdk.internal.access.SharedSecrets; + import static java.lang.classfile.ClassFile.ACC_STATIC; import static java.lang.constant.ConstantDescs.*; import static java.util.Objects.requireNonNull; @@ -60,6 +63,8 @@ public final class ObjectMethods { private ObjectMethods() { } + private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); + private static final int MAX_STRING_CONCAT_SLOTS = 20; private static final MethodHandle FALSE = MethodHandles.zero(boolean.class); @@ -257,7 +262,11 @@ private static MethodHandle makeEquals(MethodHandles.Lookup lookup, Class rec } }); - var specializerLookup = lookup.defineHiddenClass(bytes, true, MethodHandles.Lookup.ClassOption.STRONG); + // Relinking after redefinition or retransformation can leave obsolete + // specializers behind. Allow them to unload independently of the loader. + var specializerLookup = JLA.hasBeenRedefined(lookup.lookupClass()) + ? lookup.defineHiddenClass(bytes, true) + : lookup.defineHiddenClass(bytes, true, MethodHandles.Lookup.ClassOption.STRONG); for (int i = 0; i < size; i++) { if (equalators[i] == null) { @@ -333,7 +342,11 @@ private static MethodHandle makeHashCode(MethodHandles.Lookup lookup, Class r } }); - var specializerLookup = lookup.defineHiddenClass(bytes, true, MethodHandles.Lookup.ClassOption.STRONG); + // Relinking after redefinition or retransformation can leave obsolete + // specializers behind. Allow them to unload independently of the loader. + var specializerLookup = JLA.hasBeenRedefined(lookup.lookupClass()) + ? lookup.defineHiddenClass(bytes, true) + : lookup.defineHiddenClass(bytes, true, MethodHandles.Lookup.ClassOption.STRONG); for (int i = 0; i < size; i++) { if (hashers[i] == null) { diff --git a/src/java.base/share/classes/java/lang/runtime/SwitchBootstraps.java b/src/java.base/share/classes/java/lang/runtime/SwitchBootstraps.java index c52fc9ec75c..fdde3fbb445 100644 --- a/src/java.base/share/classes/java/lang/runtime/SwitchBootstraps.java +++ b/src/java.base/share/classes/java/lang/runtime/SwitchBootstraps.java @@ -45,6 +45,7 @@ import java.util.function.BiPredicate; import java.util.function.Consumer; +import jdk.internal.access.JavaLangAccess; import jdk.internal.access.SharedSecrets; import java.lang.classfile.ClassFile; import java.lang.classfile.Label; @@ -81,6 +82,8 @@ public final class SwitchBootstraps { private SwitchBootstraps() {} + private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); + private static final Object SENTINEL = new Object(); private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); private static final boolean previewEnabled = PreviewFeatures.isEnabled(); @@ -764,9 +767,12 @@ private static MethodHandle generateTypeSwitch(MethodHandles.Lookup caller, Clas }); try { - // this class is linked at the indy callsite; so define a hidden nestmate - MethodHandles.Lookup lookup; - lookup = caller.defineHiddenClass(classBytes, true, NESTMATE, STRONG); + // This class is linked at the indy callsite; so define a hidden nestmate. + // Allow obsolete helpers from relinking after redefinition or + // retransformation to unload independently of the loader. + MethodHandles.Lookup lookup = JLA.hasBeenRedefined(caller.lookupClass()) + ? caller.defineHiddenClass(classBytes, true, NESTMATE) + : caller.defineHiddenClass(classBytes, true, NESTMATE, STRONG); MethodHandle typeSwitch = lookup.findStatic(lookup.lookupClass(), "typeSwitch", addExtraInfo ? MT_TYPE_SWITCH_EXTRA : MT_TYPE_SWITCH); diff --git a/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java b/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java index e92410a053e..06366859684 100644 --- a/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java +++ b/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java @@ -77,6 +77,12 @@ public interface JavaLangAccess { */ ConstantPool getConstantPool(Class klass); + /** + * Returns whether the given class or any of its superclasses has been + * redefined or retransformed. + */ + boolean hasBeenRedefined(Class klass); + /** * Compare-And-Set the AnnotationType instance corresponding to this class. * (This method only applies to annotation types.) diff --git a/test/jdk/java/lang/instrument/LambdaClassUnloading.java b/test/jdk/java/lang/instrument/LambdaClassUnloading.java new file mode 100644 index 00000000000..7f6b90037ff --- /dev/null +++ b/test/jdk/java/lang/instrument/LambdaClassUnloading.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8392362 + * @summary Obsolete lambda, record, and switch helpers can unload after redefinition or retransformation + * @requires vm.jvmti & (vm.gc != "Epsilon") + * @library /test/lib + * @modules java.instrument + * @build LambdaClassUnloading + * @run driver jdk.test.lib.util.JavaAgentBuilder + * LambdaClassUnloading LambdaClassUnloading.jar + * @run main/othervm -javaagent:LambdaClassUnloading.jar -Xshare:off + * -XX:+ClassUnloading -XX:-DisableExplicitGC -XX:-ExplicitGCInvokesConcurrent + * LambdaClassUnloading retransform + * @run main/othervm -javaagent:LambdaClassUnloading.jar -Xshare:off + * -XX:+ClassUnloading -XX:-DisableExplicitGC -XX:-ExplicitGCInvokesConcurrent + * LambdaClassUnloading redefine + */ + +import java.io.InputStream; +import java.lang.instrument.ClassDefinition; +import java.lang.instrument.Instrumentation; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; +import java.util.function.IntSupplier; + +import jdk.test.lib.Asserts; +import jdk.test.lib.Utils; +import jdk.test.lib.util.ForceGC; + +public class LambdaClassUnloading { + private static Instrumentation instrumentation; + + public static class Host { + public static IntSupplier capturing(int value) { + return () -> value; + } + + public static IntSupplier nonCapturing() { + return () -> 4711; + } + } + + public record RecordHost(Object value) {} + + public static class SwitchHost { + public static int typeSwitch(Object value) { + return switch (value) { + case String text -> text.length(); + case Integer number -> number.intValue(); + default -> -1; + }; + } + } + + public static void premain(String arguments, Instrumentation agent) { + instrumentation = agent; + } + + public static void main(String[] arguments) throws Exception { + boolean retransform = switch (arguments[0]) { + case "retransform" -> true; + case "redefine" -> false; + default -> throw new IllegalArgumentException(arguments[0]); + }; + if (arguments.length == 2) { + testHelpers(retransform, arguments[1]); + return; + } + byte[] originalBytes; + try (InputStream stream = Host.class.getResourceAsStream("LambdaClassUnloading$Host.class")) { + originalBytes = stream.readAllBytes(); + } + ClassLoader loader = Host.class.getClassLoader(); + Asserts.assertTrue(instrumentation.isModifiableClass(Host.class)); + List>> classes = exercise(retransform, originalBytes); + awaitUnloading(classes, "Released lambda implementation classes remain reachable"); + Reference.reachabilityFence(Host.class); + Reference.reachabilityFence(loader); + System.out.println(arguments[0] + ": all " + classes.size() + " implementation classes reclaimed"); + + testHelpers(retransform, "recordEquals"); + testHelpers(retransform, "recordHashCode"); + testHelpers(retransform, "typeSwitch"); + } + + private static List>> exercise(boolean retransform, byte[] originalBytes) throws Exception { + List>> classes = new ArrayList<>(); + transform(retransform, originalBytes); + IntSupplier retainedCapturing = Host.capturing(123); + IntSupplier retainedNonCapturing = Host.nonCapturing(); + track(classes, retainedCapturing, 123); + track(classes, retainedNonCapturing, 4711); + + for (int generation = 0; generation < 10; generation++) { + transform(retransform, originalBytes); + generate(classes, generation); + } + transform(retransform, originalBytes); + awaitUnloading(classes.subList(2, classes.size()), "Obsolete lambda implementation classes remain reachable"); + Asserts.assertFalse(classes.get(0).refersTo(null), "Retained capturing lambda class reclaimed"); + Asserts.assertFalse(classes.get(1).refersTo(null), "Retained noncapturing lambda class reclaimed"); + Asserts.assertEquals(retainedCapturing.getAsInt(), 123); + Asserts.assertEquals(retainedNonCapturing.getAsInt(), 4711); + Reference.reachabilityFence(retainedCapturing); + Reference.reachabilityFence(retainedNonCapturing); + return classes; + } + + private static void transform(boolean retransform, byte[] originalBytes) throws Exception { + transform(retransform, Host.class, originalBytes); + } + + private static void transform(boolean retransform, Class host, byte[] originalBytes) throws Exception { + if (retransform) { + instrumentation.retransformClasses(host); + } else { + instrumentation.redefineClasses(new ClassDefinition(host, originalBytes)); + } + } + + private static void testHelpers(boolean retransform, String kind) throws Exception { + Class host = switch (kind) { + case "recordEquals", "recordHashCode" -> RecordHost.class; + case "typeSwitch" -> SwitchHost.class; + default -> throw new IllegalArgumentException(kind); + }; + String suffix = switch (kind) { + case "recordEquals" -> "$$EqualatorSpecializer/"; + case "recordHashCode" -> "$$HasherSpecializer/"; + case "typeSwitch" -> "$$TypeSwitch/"; + default -> throw new IllegalArgumentException(kind); + }; + byte[] originalBytes; + try (InputStream stream = host.getResourceAsStream(host.getName() + ".class")) { + originalBytes = stream.readAllBytes(); + } + ClassLoader loader = host.getClassLoader(); + Asserts.assertTrue(instrumentation.isModifiableClass(host)); + List>> classes = new ArrayList<>(); + for (int generation = 0; generation <= 10; generation++) { + // Transform before the first link too, avoiding an initial STRONG helper. + transform(retransform, host, originalBytes); + runHelperWorkload(kind); + trackNewHelper(classes, host.getName() + suffix); + } + + // The current call site must keep its helper alive while obsolete + // generations unload. The weak references themselves retain no classes. + awaitUnloading(classes.subList(0, classes.size() - 1), kind + ": obsolete helper classes remain reachable"); + Asserts.assertFalse(classes.getLast().refersTo(null), kind + ": current call site's helper reclaimed"); + runHelperWorkload(kind); + + // Unlink the final site without invoking it again. + transform(retransform, host, originalBytes); + awaitUnloading(classes, kind + ": released helper classes remain reachable"); + Reference.reachabilityFence(host); + Reference.reachabilityFence(loader); + System.out.println(kind + ": all " + classes.size() + " helper classes reclaimed"); + } + + private static void runHelperWorkload(String kind) { + switch (kind) { + case "recordEquals" -> { + RecordHost value = new RecordHost("payload"); + Asserts.assertTrue(value.equals(new RecordHost("payload"))); + Asserts.assertFalse(value.equals(new RecordHost("different"))); + } + case "recordHashCode" -> + Asserts.assertEquals(new RecordHost("payload").hashCode(), "payload".hashCode()); + case "typeSwitch" -> { + Asserts.assertEquals(SwitchHost.typeSwitch("payload"), 7); + Asserts.assertEquals(SwitchHost.typeSwitch(Integer.valueOf(4711)), 4711); + Asserts.assertEquals(SwitchHost.typeSwitch(Boolean.TRUE), -1); + } + default -> throw new IllegalArgumentException(kind); + } + } + + private static void trackNewHelper(List>> classes, String prefix) { + Class found = null; + // Keep the enumeration's strong Class references inside this method, + // so none survives into the unloading checks. + for (Class candidate : instrumentation.getAllLoadedClasses()) { + if (!candidate.getName().startsWith(prefix) || alreadyTracked(classes, candidate)) { + continue; + } + Asserts.assertTrue(candidate.isHidden(), "Expected a hidden helper class"); + Asserts.assertNull(found, "More than one new helper for " + prefix); + found = candidate; + } + Asserts.assertNotNull(found, "No new helper for " + prefix); + classes.add(new WeakReference<>(found)); + } + + private static boolean alreadyTracked(List>> classes, Class candidate) { + for (WeakReference> reference : classes) { + if (reference.refersTo(candidate)) { + return true; + } + } + return false; + } + + private static void generate(List>> classes, int value) { + track(classes, Host.capturing(value), value); + track(classes, Host.nonCapturing(), 4711); + } + + private static void track(List>> classes, IntSupplier instance, int expected) { + Asserts.assertEquals(instance.getAsInt(), expected); + Asserts.assertTrue(instance.getClass().isHidden(), "Expected a hidden lambda implementation class"); + Asserts.assertFalse(alreadyTracked(classes, instance.getClass()), "Expected a new lambda implementation class"); + classes.add(new WeakReference<>(instance.getClass())); + } + + private static void awaitUnloading(List>> classes, String message) { + Asserts.assertTrue(ForceGC.waitFor(() -> allCleared(classes), Utils.adjustTimeout(10_000)), message); + } + + private static boolean allCleared(List>> classes) { + for (WeakReference> reference : classes) { + if (!reference.refersTo(null)) { + return false; + } + } + return true; + } +} From 068a37ef63b792e1044569a6164de854ecfd8c33 Mon Sep 17 00:00:00 2001 From: Stefan Karlsson Date: Thu, 19 Nov 2026 13:17:53 +0000 Subject: [PATCH 05/95] 8397016: ZGC: AArch64: SIGILL in barrier with -XX:-UseLSE Reviewed-by: aph, jsikstro, eosterlund, tschatzl --- src/hotspot/cpu/aarch64/assembler_aarch64.hpp | 3 +++ .../cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp | 5 ++++- src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp index 9b14148c9a3..ec7f425709c 100644 --- a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp @@ -1258,6 +1258,9 @@ class Assembler : public AbstractAssembler { void store_exclusive(Register status, Register new_val, Register addr, enum operand_size sz, bool ordered) { + assert_different_registers(status, new_val); + assert_different_registers(status, addr); + guarantee(status != new_val && status != addr, "unpredictable instruction"); load_store_exclusive(status, new_val, dummy_reg, addr, sz, 0b000, ordered); } diff --git a/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp index 69a04f0fac5..58ad7d8c60c 100644 --- a/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp @@ -284,6 +284,9 @@ void ZBarrierSetAssembler::store_barrier_medium(MacroAssembler* masm, // If we get this far, we know there is a young raw null value in the field. __ relocate(barrier_Relocation::spec(), ZBarrierRelocationFormatStoreGoodBeforeMov); __ movzw(rtmp1, barrier_Relocation::unpatched); + // Be careful to not use rscratch1 for the addr or new_val + assert_different_registers(rtmp1, rscratch1); + assert_different_registers(rtmp2, rscratch1); __ cmpxchg_weak(rtmp2, zr, rtmp1, Assembler::xword, memory_order_relaxed, rtmp3); __ br(Assembler::NE, slow_path); @@ -1169,8 +1172,8 @@ void ZBarrierSetAssembler::generate_c2_store_barrier_stub(MacroAssembler* masm, store_barrier_medium(masm, stub->ref_addr(), stub->new_zpointer(), - rscratch1, rscratch2, + rscratch1, stub->is_native(), stub->is_atomic(), *stub->continuation(), diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp index 49ba595ba6d..28692b7b10d 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp @@ -26,6 +26,7 @@ #include "asm/assembler.hpp" #include "asm/assembler.inline.hpp" +#include "asm/register.hpp" #include "cds/archiveBuilder.hpp" #include "ci/ciEnv.hpp" #include "ci/ciValueKlass.hpp" @@ -3664,6 +3665,14 @@ void MacroAssembler::cmpxchg(Register addr, Register expected, enum atomic_memory_order order, bool weak, Register result) { + // Be careful to not use overlapping register with rscratch1 and result + assert_different_registers(rscratch1, addr); + assert_different_registers(rscratch1, expected); + assert_different_registers(rscratch1, new_val); + assert_different_registers(result, addr); + assert_different_registers(result, expected); + assert_different_registers(result, new_val); + bool acquire, release; switch (order) { From 03eda7782a07e2b81f4243f187728f48c33b5187 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20H=C3=A4ssig?= Date: Thu, 19 Nov 2026 14:23:36 +0000 Subject: [PATCH 06/95] 8397213: Test compiler/c1/TestMemoryEffects.java fails on aarch64 Reviewed-by: thartmann, mchevalier --- test/hotspot/jtreg/ProblemList.txt | 2 - .../jtreg/compiler/c1/TestMemoryEffects.java | 48 ++++++++++++++----- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index ad66e0e20dd..31976c9dc61 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -71,8 +71,6 @@ compiler/escapeAnalysis/TestBCEscapeAnalyzerOverflow.java 8387392 windows-aarch6 compiler/igvn/TestIncorrectDeadPathTypeNode.java 8392354 generic-all -compiler/c1/TestMemoryEffects.java 8397213 generic-aarch64 - ############################################################################# # :hotspot_gc diff --git a/test/hotspot/jtreg/compiler/c1/TestMemoryEffects.java b/test/hotspot/jtreg/compiler/c1/TestMemoryEffects.java index 4d0e6d471e6..9e6babdf4de 100644 --- a/test/hotspot/jtreg/compiler/c1/TestMemoryEffects.java +++ b/test/hotspot/jtreg/compiler/c1/TestMemoryEffects.java @@ -28,9 +28,7 @@ * @library /test/lib / * @modules java.base/jdk.internal.misc * @requires vm.compiler1.enabled & vm.flagless - * @build jdk.test.whitebox.WhiteBox - * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox - * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI ${test.main.class} + * @run driver ${test.main.class} */ package compiler.c1; @@ -40,11 +38,9 @@ import compiler.lib.ir_framework.*; import jdk.test.lib.Asserts; -import jdk.test.whitebox.WhiteBox; public class TestMemoryEffects { private static final Unsafe UNSAFE = Unsafe.getUnsafe(); - private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox(); public static void main(String[] args) { TestFramework tf = new TestFramework(); @@ -93,6 +89,7 @@ static class BoxWithVolatiles { int value; volatile int sync; volatile boolean start; + volatile int next; volatile boolean stop; } @@ -107,11 +104,17 @@ static void runVolatileLoad(RunInfo info) { Thread writer = new Thread(() -> { int counter = 1; box.start = true; + int last = box.next; while (!box.stop) { + last = box.next; + box.sync = counter++; box.value = 42; // Make the non-volatile write above visible with a release-acquire handshake by // writing and reading the same volatile field. box.sync = counter++; + while (!box.stop && last == box.next) { + Thread.onSpinWait(); + } } }); @@ -120,30 +123,51 @@ static void runVolatileLoad(RunInfo info) { Thread.onSpinWait(); } + // Count number of successful handshakes where the value is wrong. + // A conservative estimate for the test failing due to reordering + // is 9/20. With 200 handshakes the probability of the test randomly + // failing is about 4.39E-70. + final int maxHandshakes = 200; + int successfulHandshakes = 0; + // Limit the number of attempts to check if the test is still working. + final int maxAttempts = 50_000; + int attempts = 1; try { - for (int attempts = 1; attempts <= 500; attempts++) { + for (; attempts <= maxAttempts && successfulHandshakes < maxHandshakes; attempts++) { VolatileTestResults results = null; try { results = (VolatileTestResults)info.getTest(testName).invoke(null, box, 0xcafe); } catch (Exception e) { /* make javac happy */ } - // The release-acquire handshake worked if before and after are not the same. - if (results.before != results.after) { + // The release-acquire handshake worked if before and after + // are different by 2 and both even. + final int steps = results.after - results.before; + if (Integer.compareUnsigned(steps, 2) == 0 && + (results.before & 1) == 0 && (results.after & 1) == 0) { + if (results.value != 42) { + successfulHandshakes++; + continue; + } + // If we reach here, the test has passed. box.stop = true; writer.join(); - Asserts.assertEQ(42, results.value, "wrong execution for testVolatileLoad:"); - // If we reach here, the test has passed. return; } } box.stop = true; writer.join(); } catch (InterruptedException e) { /* make javac happy */ } - throw new RuntimeException("The handshake for testVolatileLoad did not work."); + if (attempts >= 50_000 && successfulHandshakes < 200) { + throw new RuntimeException("The handshake for testVolatileLoad did not work."); + } else { + throw new RuntimeException("Wrong execution for " + testName); + } }); } @Test(compLevel = CompLevel.C1_SIMPLE) static VolatileTestResults testVolatileLoad(BoxWithVolatiles box, int delay) { + // Start another round in the writer. + box.next++; box.value = 0; // Establish fact in C1 MemoryBuffer. // The test depends on the write above not getting reordered below the read below. C1 emits instructions // inside a block in source order, so this works. C2, however, moves anything not nailed down, which is @@ -368,6 +392,8 @@ static VolatileTestResults testVolatileLoad(BoxWithVolatiles box, int delay) { static VolatileTestResults testUnsafeVolatileLoad(BoxWithVolatiles box, int delay) throws NoSuchFieldException { long syncOffset = UNSAFE.objectFieldOffset(BoxWithVolatiles.class.getDeclaredField("sync")); + // Start another round in the writer. + box.next++; box.value = 0; // Establish fact in C1 MemoryBuffer. // The test depends on the write above not getting reordered below the read below. C1 emits instructions // inside a block in source order, so this works. C2, however, moves anything not nailed down, which is From 3f324b8cd01478432eb26ff41e21fb14ff1bbe55 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 19 Nov 2026 15:59:17 +0000 Subject: [PATCH 07/95] 8397074: [Leyden] Cleanup usage of #if INCLUDE_CDS Reviewed-by: shade, iklam, iveresov, sspitsyn --- .../cpu/aarch64/c1_LIRAssembler_aarch64.cpp | 7 +----- .../gc/g1/g1BarrierSetAssembler_aarch64.cpp | 5 +--- .../gc/shared/barrierSetAssembler_aarch64.cpp | 5 +--- .../shenandoahBarrierSetAssembler_aarch64.cpp | 10 ++------ .../gc/z/zBarrierSetAssembler_aarch64.cpp | 5 +--- .../cpu/aarch64/macroAssembler_aarch64.cpp | 22 +++------------- .../cpu/riscv/c1_LIRAssembler_riscv.cpp | 2 -- .../gc/g1/g1BarrierSetAssembler_riscv.cpp | 5 +--- .../gc/shared/barrierSetAssembler_riscv.cpp | 5 +--- .../shenandoahBarrierSetAssembler_riscv.cpp | 10 ++------ .../riscv/gc/z/zBarrierSetAssembler_riscv.cpp | 5 +--- .../cpu/riscv/macroAssembler_riscv.cpp | 12 ++------- src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp | 7 +----- .../x86/gc/g1/g1BarrierSetAssembler_x86.cpp | 9 +------ .../x86/gc/shared/barrierSetAssembler_x86.cpp | 5 +--- .../cardTableBarrierSetAssembler_x86.cpp | 10 ++------ .../shenandoahBarrierSetAssembler_x86.cpp | 10 ++------ .../cpu/x86/gc/z/zBarrierSetAssembler_x86.cpp | 5 +--- src/hotspot/cpu/x86/macroAssembler_x86.cpp | 20 +++------------ src/hotspot/os/posix/vmError_posix.cpp | 2 -- src/hotspot/os/windows/vmError_windows.cpp | 2 -- src/hotspot/share/cds/aotClassLocation.hpp | 2 +- .../share/cds/aotConstantPoolResolver.hpp | 2 +- src/hotspot/share/cds/aotMetaspace.hpp | 2 +- src/hotspot/share/cds/archiveBuilder.hpp | 2 +- src/hotspot/share/cds/cdsConfig.hpp | 2 +- src/hotspot/share/ci/ciEnv.cpp | 2 -- src/hotspot/share/ci/ciInstanceKlass.cpp | 5 +--- src/hotspot/share/ci/ciMethod.cpp | 2 -- src/hotspot/share/classfile/classLoader.cpp | 2 -- src/hotspot/share/classfile/classLoader.hpp | 4 +-- src/hotspot/share/classfile/klassFactory.cpp | 2 -- src/hotspot/share/classfile/symbolTable.cpp | 2 -- .../share/classfile/systemDictionary.cpp | 12 +++------ src/hotspot/share/classfile/vmClasses.cpp | 4 --- src/hotspot/share/code/aotCodeCache.cpp | 25 ++++++++++++++++++- src/hotspot/share/code/nmethod.cpp | 4 +-- .../share/compiler/compilationPolicy.cpp | 13 +--------- .../share/compiler/compilerDirectives.cpp | 2 -- .../gc/shared/c1/cardTableBarrierSetC1.cpp | 5 +--- .../gc/shared/c2/cardTableBarrierSetC2.cpp | 2 -- src/hotspot/share/interpreter/rewriter.cpp | 4 --- src/hotspot/share/memory/metaspace.cpp | 2 +- src/hotspot/share/memory/universe.cpp | 11 +------- src/hotspot/share/oops/cpCache.cpp | 2 -- src/hotspot/share/oops/trainingData.cpp | 9 ++++--- src/hotspot/share/oops/trainingData.hpp | 4 +-- src/hotspot/share/opto/parse1.cpp | 2 +- src/hotspot/share/prims/jvm.cpp | 6 ----- src/hotspot/share/prims/jvmtiAgent.cpp | 4 --- .../share/prims/jvmtiRedefineClasses.cpp | 4 --- src/hotspot/share/runtime/init.cpp | 4 --- src/hotspot/share/runtime/java.cpp | 10 ++------ src/hotspot/share/runtime/sharedRuntime.cpp | 2 -- src/hotspot/share/runtime/stubRoutines.cpp | 3 --- src/hotspot/share/runtime/stubRoutines.hpp | 4 +-- src/hotspot/share/runtime/threads.cpp | 5 +--- src/hotspot/share/utilities/vmError.cpp | 4 +-- 58 files changed, 83 insertions(+), 256 deletions(-) diff --git a/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp index 20752382465..c7d4f35081f 100644 --- a/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp @@ -493,7 +493,6 @@ void LIR_Assembler::return_op(LIR_Opr result, C1SafepointPollStub* code_stub) { if (vk->can_be_returned_as_fields()) { address unpack_handler = vk->unpack_handler(); assert(unpack_handler != nullptr, "must be"); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { // in AOT compiled code call the unpack handler indirectly // via the klass. The handler's blob does not currently get @@ -504,9 +503,7 @@ void LIR_Assembler::return_op(LIR_Opr result, C1SafepointPollStub* code_stub) { __ ldr(rscratch1, Address(rscratch1, ValueKlass::adr_members_offset())); __ ldr(rscratch1, Address(rscratch1, ValueKlass::unpack_handler_offset())); __ blr(rscratch1); - } else -#endif - { + } else { __ far_call(RuntimeAddress(unpack_handler)); } } @@ -601,7 +598,6 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: { assert(patch_code == lir_patch_none, "no patching handled here"); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { address b = c->as_pointer(); if (b == (address)ThreadIdentifier::unsafe_offset()) { @@ -619,7 +615,6 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod break; } } -#endif __ mov(dest->as_register_lo(), (intptr_t)c->as_jlong()); break; } diff --git a/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp index 98ae760ca89..9756de27c9b 100644 --- a/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp @@ -246,7 +246,6 @@ static void generate_post_barrier(MacroAssembler* masm, assert_different_registers(store_addr, new_val, thread, tmp1, tmp2, noreg, rscratch1); // Does store cross heap regions? -#if INCLUDE_CDS // AOT code needs to load the barrier grain shift from the aot // runtime constants area in the code cache otherwise we can compile // it as an immediate operand @@ -257,9 +256,7 @@ static void generate_post_barrier(MacroAssembler* masm, __ ldrb(tmp2, tmp2); __ lsrv(tmp1, tmp1, tmp2); __ cbz(tmp1, done); - } else -#endif - { + } else { __ eor(tmp1, store_addr, new_val); // tmp1 := store address ^ new value __ lsr(tmp1, tmp1, G1HeapRegion::LogOfHRGrainBytes); // tmp1 := ((store address ^ new value) >> LogOfHRGrainBytes) __ cbz(tmp1, done); diff --git a/src/hotspot/cpu/aarch64/gc/shared/barrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/shared/barrierSetAssembler_aarch64.cpp index c8629136bdd..3a075bb1e17 100644 --- a/src/hotspot/cpu/aarch64/gc/shared/barrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/shared/barrierSetAssembler_aarch64.cpp @@ -394,16 +394,13 @@ void BarrierSetAssembler::c2i_entry_barrier(MacroAssembler* masm) { void BarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Register tmp1, Register tmp2, Label& error) { assert_different_registers(obj, tmp1, tmp2); // Check if the oop is in the right area of memory -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ ldr(tmp2, Address(tmp2)); __ andr(tmp1, obj, tmp2); __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); __ ldr(tmp2, Address(tmp2)); - } else -#endif - { + } else { __ mov(tmp2, (intptr_t) Universe::verify_oop_mask()); __ andr(tmp1, obj, tmp2); __ mov(tmp2, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp index 84e92e2551f..1a491646022 100644 --- a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp @@ -217,16 +217,13 @@ void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, // Test for in-cset if (is_strong) { -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(rscratch2, ExternalAddress(AOTRuntimeConstants::cset_base_address())); __ ldr(rscratch2, Address(rscratch2)); __ lea(rscratch1, ExternalAddress(AOTRuntimeConstants::grain_shift_address())); __ ldrw(rscratch1, Address(rscratch1)); __ lsrv(rscratch1, r0, rscratch1); - } else -#endif - { + } else { __ mov(rscratch2, ShenandoahHeap::in_cset_fast_test_addr()); __ lsr(rscratch1, r0, ShenandoahHeapRegion::region_size_bytes_shift_jint()); } @@ -430,16 +427,13 @@ void ShenandoahBarrierSetAssembler::try_peek_weak_handle_in_nmethod(MacroAssembl void ShenandoahBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Register tmp1, Register tmp2, Label& L_error) { assert_different_registers(obj, tmp1, tmp2); // Check if the oop is in the right area of memory -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ ldr(tmp2, Address(tmp2)); __ andr(tmp1, obj, tmp2); __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); __ ldr(tmp2, Address(tmp2)); - } else -#endif - { + } else { __ mov(tmp2, (intptr_t) Universe::verify_oop_mask()); __ andr(tmp1, obj, tmp2); __ mov(tmp2, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp index 58ad7d8c60c..ffde8cbab4b 100644 --- a/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/z/zBarrierSetAssembler_aarch64.cpp @@ -1395,16 +1395,13 @@ void ZBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Registe __ bind(check_zaddress); // Check if the oop is in the right area of memory -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(tmp1, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ ldr(tmp1, Address(tmp1)); __ andr(tmp1, tmp1, obj); __ lea(obj, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); __ ldr(obj, Address(obj)); - } else -#endif - { + } else { __ mov(tmp1, (intptr_t) Universe::verify_oop_mask()); __ andr(tmp1, tmp1, obj); __ mov(obj, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp index 28692b7b10d..96ba171d966 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp @@ -2057,13 +2057,10 @@ void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, ResourceMark rm; stringStream ss; ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump() && !code_section()->scratch_emit()) { // this will duplicate string to preserve it b = AOTCodeCache::add_C_string(ss.as_string()); - } else -#endif - { + } else { b = code_string(ss.as_string()); } } @@ -2101,13 +2098,10 @@ void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* f ResourceMark rm; stringStream ss; ss.print("verify_oop_addr: %s (%s:%d)", s, file, line); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump() && !code_section()->scratch_emit()) { // this will duplicate string to preserve it b = AOTCodeCache::add_C_string(ss.as_string()); - } else -#endif - { + } else { b = code_string(ss.as_string()); } } @@ -5956,14 +5950,12 @@ void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_off } void MacroAssembler::load_byte_map_base(Register reg) { -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { address byte_map_base_adr = AOTRuntimeConstants::card_table_base_address(); lea(reg, ExternalAddress(byte_map_base_adr)); ldr(reg, Address(reg)); return; } -#endif CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set(); // Strictly speaking the card table base isn't an address at all, and it might @@ -7134,12 +7126,9 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i if (vk != nullptr) { // Called from C1, where the return type is statically known. -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { mov_metadata(klass, vk->constant_encoding()); - } else -#endif - { + } else { movptr(klass, (intptr_t)vk->get_ValueKlass()); } jint lh = vk->layout_helper(); @@ -7180,7 +7169,6 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i } // 3. Initialize its fields with a value class specific handler if (vk != nullptr) { -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { // in AOT compiled code call the pack handler indirectly via // the klass. The handler's blob does not currently get saved @@ -7191,9 +7179,7 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i ldr(tmp1, Address(tmp1, ValueKlass::adr_members_offset())); ldr(tmp1, Address(tmp1, ValueKlass::pack_handler_offset())); blr(tmp1); - } else -#endif - { + } else { far_call(RuntimeAddress(vk->pack_handler())); // no need for call info as this will not safepoint. } } else { diff --git a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp index ffb3394b3bb..df2de59e677 100644 --- a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp @@ -445,7 +445,6 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: assert(patch_code == lir_patch_none, "no patching handled here"); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { address b = c->as_pointer(); if (b == (address)ThreadIdentifier::unsafe_offset()) { @@ -463,7 +462,6 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod break; } } -#endif __ mv(dest->as_register_lo(), (intptr_t)c->as_jlong()); break; diff --git a/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp index 7bba2bdaf0b..5cda49845c1 100644 --- a/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp @@ -258,7 +258,6 @@ static void generate_post_barrier(MacroAssembler* masm, assert(thread == xthread, "must be"); assert_different_registers(store_addr, new_val, thread, tmp1, tmp2, noreg); // Does store cross heap regions? -#if INCLUDE_CDS // AOT code needs to load the barrier grain shift from the aot // runtime constants area in the code cache otherwise we can compile // it as an immediate operand @@ -267,9 +266,7 @@ static void generate_post_barrier(MacroAssembler* masm, __ lwu(tmp2, ExternalAddress(AOTRuntimeConstants::grain_shift_address())); __ srl(tmp1, tmp1, tmp2); __ beqz(tmp1, done); - } else -#endif - { + } else { __ xorr(tmp1, store_addr, new_val); // tmp1 := store address ^ new value __ srli(tmp1, tmp1, G1HeapRegion::LogOfHRGrainBytes); // tmp1 := ((store address ^ new value) >> LogOfHRGrainBytes) __ beqz(tmp1, done); diff --git a/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp index 26b71ec6835..73a61255b92 100644 --- a/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp @@ -361,14 +361,11 @@ void BarrierSetAssembler::c2i_entry_barrier(MacroAssembler* masm) { void BarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Register tmp1, Register tmp2, Label& error) { assert_different_registers(obj, tmp1, tmp2); // Check if the oop is in the right area of memory -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ ld(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ andr(tmp1, obj, tmp2); __ ld(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); - } else -#endif - { + } else { __ mv(tmp2, (intptr_t) Universe::verify_oop_mask()); __ andr(tmp1, obj, tmp2); __ mv(tmp2, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp index 329e0c3d3b2..fa4f6fc9ea6 100644 --- a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp @@ -223,14 +223,11 @@ void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, // Test for in-cset if (is_strong) { -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ ld(t1, ExternalAddress(AOTRuntimeConstants::cset_base_address())); __ lwu(t0, ExternalAddress(AOTRuntimeConstants::grain_shift_address())); __ srl(t0, x10, t0); - } else -#endif - { + } else { __ mv(t1, ShenandoahHeap::in_cset_fast_test_addr()); __ srli(t0, x10, ShenandoahHeapRegion::region_size_bytes_shift_jint()); } @@ -449,14 +446,11 @@ void ShenandoahBarrierSetAssembler::try_peek_weak_handle_in_nmethod(MacroAssembl void ShenandoahBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Register tmp1, Register tmp2, Label& L_error) { assert_different_registers(obj, tmp1, tmp2); // Check if the oop is in the right area of memory -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ ld(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ andr(tmp1, obj, tmp2); __ ld(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); - } else -#endif - { + } else { __ mv(tmp2, (intptr_t) Universe::verify_oop_mask()); __ andr(tmp1, obj, tmp2); __ mv(tmp2, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp index 0ee69fae757..db96f003416 100644 --- a/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp @@ -1045,14 +1045,11 @@ void ZBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Registe __ bind(check_zaddress); // Check if the oop is the right area of memory -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ ld(tmp1, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ andr(tmp1, tmp1, obj); __ ld(obj, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); - } else -#endif - { + } else { __ mv(tmp1, (intptr_t) Universe::verify_oop_mask()); __ andr(tmp1, tmp1, obj); __ mv(obj, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp index 7044eb64f06..3e527aba68e 100644 --- a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp @@ -522,13 +522,10 @@ void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, ResourceMark rm; stringStream ss; ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump() && !code_section()->scratch_emit()) { // This will duplicate string to preserve it. b = AOTCodeCache::add_C_string(ss.as_string()); - } else -#endif - { + } else { b = code_string(ss.as_string()); } } @@ -713,13 +710,10 @@ void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* f ResourceMark rm; stringStream ss; ss.print("verify_oop_addr: %s (%s:%d)", s, file, line); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump() && !code_section()->scratch_emit()) { // This will duplicate string to preserve it. b = AOTCodeCache::add_C_string(ss.as_string()); - } else -#endif - { + } else { b = code_string(ss.as_string()); } } @@ -5681,13 +5675,11 @@ void MacroAssembler::get_thread(Register thread) { } void MacroAssembler::load_byte_map_base(Register reg) { -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { address byte_map_base_adr = AOTRuntimeConstants::card_table_base_address(); ld(reg, ExternalAddress(byte_map_base_adr)); return; } -#endif CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set(); // Strictly speaking the card table base isn't an address at all, and it might // even be negative. It is thus materialised as a constant. diff --git a/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp b/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp index 2e8cc44bb23..78abd13ba97 100644 --- a/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp @@ -484,7 +484,6 @@ void LIR_Assembler::return_op(LIR_Opr result, C1SafepointPollStub* code_stub) { if (vk->can_be_returned_as_fields()) { address unpack_handler = vk->unpack_handler(); assert(unpack_handler != nullptr, "must be"); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { // in AOT compiled code call the unpack handler indirectly // via the klass. The handler's blob does not currently get @@ -495,9 +494,7 @@ void LIR_Assembler::return_op(LIR_Opr result, C1SafepointPollStub* code_stub) { __ movptr(rdi, Address(rdi, ValueKlass::adr_members_offset())); __ movptr(rdi, Address(rdi, ValueKlass::unpack_handler_offset())); __ call(rdi); - } else -#endif - { + } else { __ call(RuntimeAddress(unpack_handler)); } } @@ -599,7 +596,6 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: { assert(patch_code == lir_patch_none, "no patching handled here"); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { address b = c->as_pointer(); if (b == (address)ThreadIdentifier::unsafe_offset()) { @@ -617,7 +613,6 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod break; } } -#endif __ movptr(dest->as_register_lo(), (intptr_t)c->as_jlong()); break; } diff --git a/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp index 3e246230d59..4eefd10b7fc 100644 --- a/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp @@ -269,15 +269,12 @@ void G1BarrierSetAssembler::g1_write_barrier_pre(MacroAssembler* masm, __ bind(done); } -#if INCLUDE_CDS // return a register that differs from reg1, reg2, reg3 and reg4 - static Register pick_different_reg(Register reg1, Register reg2 = noreg, Register reg3= noreg, Register reg4 = noreg) { RegSet available = (RegSet::of(rscratch1, rscratch2, rax, rbx) + rdx - RegSet::of(reg1, reg2, reg3, reg4)); return *(available.begin()); } -#endif // INCLUDE_CDS static void generate_post_barrier(MacroAssembler* masm, const Register store_addr, @@ -291,11 +288,9 @@ static void generate_post_barrier(MacroAssembler* masm, Label L_done; // Does store cross heap regions? -#if INCLUDE_CDS // AOT code needs to load the barrier grain shift from the aot // runtime constants area in the code cache otherwise we can compile // it as an immediate operand - if (AOTCodeCache::is_on_for_dump()) { address grain_shift_addr = AOTRuntimeConstants::grain_shift_address(); Register save = pick_different_reg(rcx, tmp1, new_val, store_addr); @@ -309,9 +304,7 @@ static void generate_post_barrier(MacroAssembler* masm, __ pop(rcx); __ pop(save); __ jcc(Assembler::equal, L_done); - } else -#endif // INCLUDE_CDS - { + } else { __ movptr(tmp1, store_addr); // tmp1 := store address __ xorptr(tmp1, new_val); // tmp1 := store address ^ new value __ shrptr(tmp1, G1HeapRegion::LogOfHRGrainBytes); // ((store address ^ new value) >> LogOfHRGrainBytes) == 0? diff --git a/src/hotspot/cpu/x86/gc/shared/barrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/shared/barrierSetAssembler_x86.cpp index d94f4826dc0..49adbea8e0a 100644 --- a/src/hotspot/cpu/x86/gc/shared/barrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/shared/barrierSetAssembler_x86.cpp @@ -353,16 +353,13 @@ void BarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Register assert_different_registers(obj, tmp1, tmp2); // Check if the oop is in the right area of memory __ movptr(tmp1, obj); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ movptr(tmp2, Address(tmp2)); __ andptr(tmp1, tmp2); __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); __ movptr(tmp2, Address(tmp2)); - } else -#endif - { + } else { __ movptr(tmp2, (intptr_t) Universe::verify_oop_mask()); __ andptr(tmp1, tmp2); __ movptr(tmp2, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp index c05f37a3bea..5e1d2c5a51f 100644 --- a/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp @@ -112,13 +112,10 @@ void CardTableBarrierSetAssembler::gen_write_ref_array_post_barrier(MacroAssembl __ shrptr(end, CardTable::card_shift()); __ subptr(end, addr); // end --> cards count -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(tmp, ExternalAddress(AOTRuntimeConstants::card_table_base_address())); __ movq(tmp, Address(tmp, 0)); - } else -#endif - { + } else { __ mov64(tmp, (intptr_t)ctbs->card_table_base_const()); } __ addptr(addr, tmp); @@ -147,14 +144,11 @@ void CardTableBarrierSetAssembler::store_check(MacroAssembler* masm, Register ob // never need to be relocated. On 64bit however the value may be too // large for a 32bit displacement. intptr_t byte_map_base = (intptr_t)ctbs->card_table_base_const(); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(rscratch, ExternalAddress(AOTRuntimeConstants::card_table_base_address())); __ movq(rscratch, Address(rscratch, 0)); card_addr = Address(rscratch, obj, Address::times_1, 0); - } else -#endif - if (__ is_simm32(byte_map_base)) { + } else if (__ is_simm32(byte_map_base)) { card_addr = Address(noreg, obj, Address::times_1, byte_map_base); } else { // By doing it as an ExternalAddress 'byte_map_base' could be converted to a rip-relative diff --git a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp index 53bcd1300fc..364a1316569 100644 --- a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp @@ -267,7 +267,6 @@ void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, // Optimized cset-test __ movptr(tmp1, dst); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { assert_different_registers(tmp1, tmp2, rcx); __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::grain_shift_address())); @@ -277,9 +276,7 @@ void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, __ pop(rcx); __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::cset_base_address())); __ movptr(tmp2, Address(tmp2)); - } else -#endif - { + } else { __ shrptr(tmp1, ShenandoahHeapRegion::region_size_bytes_shift_jint()); __ movptr(tmp2, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr()); } @@ -514,16 +511,13 @@ void ShenandoahBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj assert_different_registers(obj, tmp1, tmp2); // Check if the oop is in the right area of memory __ movptr(tmp1, obj); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ movptr(tmp2, Address(tmp2)); __ andptr(tmp1, tmp2); __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); __ movptr(tmp2, Address(tmp2)); - } else -#endif - { + } else { __ movptr(tmp2, (intptr_t) Universe::verify_oop_mask()); __ andptr(tmp1, tmp2); __ movptr(tmp2, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/x86/gc/z/zBarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/z/zBarrierSetAssembler_x86.cpp index 4234d6fddc1..a64b9229904 100644 --- a/src/hotspot/cpu/x86/gc/z/zBarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/z/zBarrierSetAssembler_x86.cpp @@ -1564,16 +1564,13 @@ void ZBarrierSetAssembler::check_oop(MacroAssembler* masm, Register obj, Registe __ bind(check_zaddress); // Check if the oop is in the right area of memory __ movptr(tmp1, obj); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_mask_address())); __ movptr(tmp2, Address(tmp2)); __ andptr(tmp1, tmp2); __ lea(tmp2, ExternalAddress(AOTRuntimeConstants::verify_oop_bits_address())); __ movptr(tmp2, Address(tmp2)); - } else -#endif - { + } else { __ movptr(tmp2, (intptr_t) Universe::verify_oop_mask()); __ andptr(tmp1, tmp2); __ movptr(tmp2, (intptr_t) Universe::verify_oop_bits()); diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.cpp b/src/hotspot/cpu/x86/macroAssembler_x86.cpp index f6e274ab09e..abd55737e18 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp @@ -4894,13 +4894,10 @@ void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, ResourceMark rm; stringStream ss; ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump() && !code_section()->scratch_emit()) { // this will duplicate string to preserve it b = AOTCodeCache::add_C_string(ss.as_string()); - } else -#endif - { + } else { b = code_string(ss.as_string()); } } @@ -5167,13 +5164,10 @@ void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* f ResourceMark rm; stringStream ss; ss.print("verify_oop_addr: %s (%s:%d)", s, file, line); -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump() && !code_section()->scratch_emit()) { // this will duplicate string to preserve it b = AOTCodeCache::add_C_string(ss.as_string()); - } else -#endif - { + } else { b = code_string(ss.as_string()); } } @@ -6030,12 +6024,9 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i mov(rscratch1, rax); // save rax for slow_case since *_allocate may corrupt it when allocation failed if (vk != nullptr) { // Called from C1, where the return type is statically known. -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { mov_metadata(rbx, vk->constant_encoding()); - } else -#endif - { + } else { movptr(rbx, (intptr_t)vk->get_ValueKlass()); } jint lh = vk->layout_helper(); @@ -6079,7 +6070,6 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i } // 3. Initialize its fields with a value class specific handler if (vk != nullptr) { -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { // in AOT compiled code call the pack handler indirectly via // the klass. The handler's blob does not currently get saved @@ -6090,9 +6080,7 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i movptr(rbx, Address(rbx, ValueKlass::adr_members_offset())); movptr(rbx, Address(rbx, ValueKlass::pack_handler_offset())); call(rbx); - } else -#endif - { + } else { call(RuntimeAddress(vk->pack_handler())); // no need for call info as this will not safepoint. } } else { diff --git a/src/hotspot/os/posix/vmError_posix.cpp b/src/hotspot/os/posix/vmError_posix.cpp index 81eeea6c168..0e34b64651d 100644 --- a/src/hotspot/os/posix/vmError_posix.cpp +++ b/src/hotspot/os/posix/vmError_posix.cpp @@ -111,7 +111,6 @@ void VMError::install_secondary_signal_handler() { // Write a hint to the stream in case siginfo relates to a segv/bus error // and the offending address points into CDS archive. void VMError::check_failing_cds_access(outputStream* st, const void* siginfo) { -#if INCLUDE_CDS if (siginfo && CDSConfig::is_using_archive()) { const siginfo_t* const si = (siginfo_t*)siginfo; if (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) { @@ -124,7 +123,6 @@ void VMError::check_failing_cds_access(outputStream* st, const void* siginfo) { } } } -#endif } bool VMError::was_assert_poison_crash(const void* siginfo) { diff --git a/src/hotspot/os/windows/vmError_windows.cpp b/src/hotspot/os/windows/vmError_windows.cpp index 66df38d2734..1ade03955f6 100644 --- a/src/hotspot/os/windows/vmError_windows.cpp +++ b/src/hotspot/os/windows/vmError_windows.cpp @@ -45,7 +45,6 @@ void VMError::install_secondary_signal_handler() { // Write a hint to the stream in case siginfo relates to a segv/bus error // and the offending address points into CDS archive. void VMError::check_failing_cds_access(outputStream* st, const void* siginfo) { -#if INCLUDE_CDS if (siginfo && CDSConfig::is_using_archive()) { const EXCEPTION_RECORD* const er = (const EXCEPTION_RECORD*)siginfo; if (er->ExceptionCode == EXCEPTION_IN_PAGE_ERROR && @@ -59,7 +58,6 @@ void VMError::check_failing_cds_access(outputStream* st, const void* siginfo) { } } } -#endif } // Error reporting cancellation: there is no easy way to implement this on Windows, because we do diff --git a/src/hotspot/share/cds/aotClassLocation.hpp b/src/hotspot/share/cds/aotClassLocation.hpp index 03873b8c1c6..15408395ca0 100644 --- a/src/hotspot/share/cds/aotClassLocation.hpp +++ b/src/hotspot/share/cds/aotClassLocation.hpp @@ -254,7 +254,7 @@ class AOTClassLocationConfig : public CHeapObj { int get_module_shared_path_index(Symbol* location) const; // Functions used only during dumptime - static void dumptime_init(JavaThread* current); + static void dumptime_init(JavaThread* current) NOT_CDS_RETURN; static void dumptime_set_has_app_classes() { _dumptime_instance->_has_app_classes = true; diff --git a/src/hotspot/share/cds/aotConstantPoolResolver.hpp b/src/hotspot/share/cds/aotConstantPoolResolver.hpp index ecf2ac27061..ce8688a1536 100644 --- a/src/hotspot/share/cds/aotConstantPoolResolver.hpp +++ b/src/hotspot/share/cds/aotConstantPoolResolver.hpp @@ -88,7 +88,7 @@ class AOTConstantPoolResolver : AllStatic { static void preresolve_indy_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray* preresolve_list); static void preresolve_string_cp_entries(InstanceKlass* ik, TRAPS); - static bool is_resolution_deterministic(ConstantPool* cp, int cp_index); + static bool is_resolution_deterministic(ConstantPool* cp, int cp_index) NOT_CDS_RETURN_(false); }; #endif // SHARE_CDS_AOTCONSTANTPOOLRESOLVER_HPP diff --git a/src/hotspot/share/cds/aotMetaspace.hpp b/src/hotspot/share/cds/aotMetaspace.hpp index 6493643b06b..a0110a65e1b 100644 --- a/src/hotspot/share/cds/aotMetaspace.hpp +++ b/src/hotspot/share/cds/aotMetaspace.hpp @@ -96,7 +96,7 @@ class AOTMetaspace : AllStatic { static void get_aot_code_region_size() NOT_CDS_RETURN; static char* get_archived_cpu_features() NOT_CDS_RETURN_(nullptr); - static void print_on(outputStream* st); + static void print_on(outputStream* st) NOT_CDS_RETURN; static void set_static_archive_validation_failed() { _static_archive_validation_failed = true; diff --git a/src/hotspot/share/cds/archiveBuilder.hpp b/src/hotspot/share/cds/archiveBuilder.hpp index 43c8eb7812c..3fde22eb99a 100644 --- a/src/hotspot/share/cds/archiveBuilder.hpp +++ b/src/hotspot/share/cds/archiveBuilder.hpp @@ -503,7 +503,7 @@ class ArchiveBuilder : public StackObj { // narrow Klass IDs. // TinyClassPointer Mode: // We use the highest possible shift value to maximize the encoding range size. - static int precomputed_narrow_klass_shift(); + static int precomputed_narrow_klass_shift() NOT_CDS_RETURN_(0); }; diff --git a/src/hotspot/share/cds/cdsConfig.hpp b/src/hotspot/share/cds/cdsConfig.hpp index 20942ca441b..49a357ad0fe 100644 --- a/src/hotspot/share/cds/cdsConfig.hpp +++ b/src/hotspot/share/cds/cdsConfig.hpp @@ -103,7 +103,7 @@ class CDSConfig : public AllStatic { static bool check_vm_args_consistency(bool patch_mod_javabase, bool mode_flag_cmd_line) NOT_CDS_RETURN_(true); static const char* type_of_archive_being_loaded(); static const char* type_of_archive_being_written(); - static void prepare_for_dumping(); + static void prepare_for_dumping() NOT_CDS_RETURN; static bool is_at_aot_safepoint() { return CDS_ONLY(_is_at_aot_safepoint) NOT_CDS(false); } static void set_is_at_aot_safepoint(bool value) { CDS_ONLY(_is_at_aot_safepoint = value); } diff --git a/src/hotspot/share/ci/ciEnv.cpp b/src/hotspot/share/ci/ciEnv.cpp index c8ded6c2214..24ae1ac8282 100644 --- a/src/hotspot/share/ci/ciEnv.cpp +++ b/src/hotspot/share/ci/ciEnv.cpp @@ -837,13 +837,11 @@ ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool, assert(index < cpool->cache()->resolved_indy_entries_length(), "impossible"); ResolvedIndyEntry* indy_info = cpool->resolved_indy_entry_at(index); Method* adapter = indy_info->method(); -#if INCLUDE_CDS if (is_aot_compile() && !AOTConstantPoolResolver::is_resolution_deterministic(cpool(), indy_info->constant_pool_index())) { // This is an indy callsite that was resolved as a side effect of VM bootstrap, but // it cannot be cached in the resolved state, so AOT code should not reference it. adapter = nullptr; } -#endif // Resolved if the adapter is non null. if (adapter != nullptr) { return get_method(adapter); diff --git a/src/hotspot/share/ci/ciInstanceKlass.cpp b/src/hotspot/share/ci/ciInstanceKlass.cpp index e6cc2263c43..a80e9f4ea04 100644 --- a/src/hotspot/share/ci/ciInstanceKlass.cpp +++ b/src/hotspot/share/ci/ciInstanceKlass.cpp @@ -165,13 +165,10 @@ InstanceKlass::ClassState ciInstanceKlass::compute_init_state() { InstanceKlass::ClassState ciInstanceKlass::compute_init_state(InstanceKlass* ik) { ASSERT_IN_VM; -#if INCLUDE_CDS ciEnv* env = CURRENT_ENV; if (env != nullptr && env->is_aot_compile()) { return env->compute_init_state_for_aot_compile(ik); - } else -#endif - { + } else { return ik->init_state(); } } diff --git a/src/hotspot/share/ci/ciMethod.cpp b/src/hotspot/share/ci/ciMethod.cpp index a5563666956..1e6412d000b 100644 --- a/src/hotspot/share/ci/ciMethod.cpp +++ b/src/hotspot/share/ci/ciMethod.cpp @@ -1309,7 +1309,6 @@ bool ciMethod::is_not_reached(int bci) { // ------------------------------------------------------------------ // ciMethod::was_never_executed bool ciMethod::was_executed_more_than(int times) { -#if INCLUDE_CDS if (CURRENT_ENV->is_aot_compile()) { // Look only on training data // Invocation counter is reset when the Method* is compiled. // If the method has compiled code we therefore assume it has @@ -1321,7 +1320,6 @@ bool ciMethod::was_executed_more_than(int times) { } return (method_data()->invocation_count() > times); } -#endif VM_ENTRY_MARK; return get_Method()->was_executed_more_than(times); } diff --git a/src/hotspot/share/classfile/classLoader.cpp b/src/hotspot/share/classfile/classLoader.cpp index 4fb4430ab60..8e324e797e3 100644 --- a/src/hotspot/share/classfile/classLoader.cpp +++ b/src/hotspot/share/classfile/classLoader.cpp @@ -677,13 +677,11 @@ void ClassLoader::setup_bootstrap_search_path_impl(JavaThread* current, const ch ClasspathStream cp_stream(class_path); bool set_base_piece = true; -#if INCLUDE_CDS if (CDSConfig::is_dumping_archive()) { if (!Arguments::has_jimage()) { vm_exit_during_initialization("CDS is not supported in exploded JDK build", nullptr); } } -#endif while (cp_stream.has_next()) { const char* path = cp_stream.get_next(); diff --git a/src/hotspot/share/classfile/classLoader.hpp b/src/hotspot/share/classfile/classLoader.hpp index eafcb04f881..5c1131c63c0 100644 --- a/src/hotspot/share/classfile/classLoader.hpp +++ b/src/hotspot/share/classfile/classLoader.hpp @@ -347,10 +347,10 @@ class ClassLoader: AllStatic { static bool is_in_patch_mod_entries(Symbol* module_name); + static void record_result(JavaThread* current, InstanceKlass* ik, + const ClassFileStream* stream, bool redefined) NOT_CDS_RETURN; #if INCLUDE_CDS static char* uri_to_path(const char* uri); - static void record_result(JavaThread* current, InstanceKlass* ik, - const ClassFileStream* stream, bool redefined); static void record_result_for_builtin_loader(s2 classpath_index, InstanceKlass* result, bool redefined); static void record_hidden_class(InstanceKlass* ik); static void append_boot_classpath(ClassPathEntry* new_entry); diff --git a/src/hotspot/share/classfile/klassFactory.cpp b/src/hotspot/share/classfile/klassFactory.cpp index 3ad908c38a0..418e6981634 100644 --- a/src/hotspot/share/classfile/klassFactory.cpp +++ b/src/hotspot/share/classfile/klassFactory.cpp @@ -218,11 +218,9 @@ InstanceKlass* KlassFactory::create_from_stream(ClassFileStream* stream, JFR_ONLY(Jfr::on_klass_creation(result, parser, THREAD);) -#if INCLUDE_CDS if (CDSConfig::is_dumping_archive()) { ClassLoader::record_result(THREAD, result, stream, old_stream != stream); } -#endif // INCLUDE_CDS return result; } diff --git a/src/hotspot/share/classfile/symbolTable.cpp b/src/hotspot/share/classfile/symbolTable.cpp index 20aa7f0776d..d84fd5767fa 100644 --- a/src/hotspot/share/classfile/symbolTable.cpp +++ b/src/hotspot/share/classfile/symbolTable.cpp @@ -145,13 +145,11 @@ class SymbolTableConfig : public AllStatic { // If #2, then the symbol is dead (refcount==0) assert(value.is_permanent() || (value.refcount() == 1) || (value.refcount() == 0), "refcount %d", value.refcount()); -#if INCLUDE_CDS if (CDSConfig::is_dumping_static_archive()) { // We have allocated with AOTMetaspace::symbol_space_alloc(). No deallocation is needed. // Unreferenced Symbols will not be copied into the archive. return; } -#endif if (value.refcount() == 1) { value.decrement_refcount(); assert(value.refcount() == 0, "expected dead symbol"); diff --git a/src/hotspot/share/classfile/systemDictionary.cpp b/src/hotspot/share/classfile/systemDictionary.cpp index 061978ae5b8..16bdb165a64 100644 --- a/src/hotspot/share/classfile/systemDictionary.cpp +++ b/src/hotspot/share/classfile/systemDictionary.cpp @@ -24,6 +24,7 @@ #include "cds/aotClassLocation.hpp" #include "cds/aotHeap.hpp" +#include "cds/aotSystemDictionary.hpp" #include "cds/cdsConfig.hpp" #include "classfile/classFileParser.hpp" #include "classfile/classFileStream.hpp" @@ -85,9 +86,6 @@ #include "utilities/growableArray.hpp" #include "utilities/macros.hpp" #include "utilities/utf8.hpp" -#if INCLUDE_CDS -#include "cds/aotSystemDictionary.hpp" -#endif #if INCLUDE_JFR #include "jfr/jfr.hpp" #endif @@ -1750,12 +1748,10 @@ void SystemDictionary::initialize(TRAPS) { ResolutionErrorTable::initialize(); LoaderConstraintTable::initialize(); PlaceholderTable::initialize(); -#if INCLUDE_CDS AOTSystemDictionary::initialize(); if (CDSConfig::is_dumping_archive()) { AOTClassLocationConfig::dumptime_init(THREAD); } -#endif // Resolve basic classes vmClasses::resolve_all(CHECK); // Resolve classes used by archived heap objects @@ -1937,14 +1933,12 @@ bool SystemDictionary::add_loader_constraint(Symbol* class_name, InstanceKlass* klass2 = dictionary2->find_class(current, constraint_name); bool result = LoaderConstraintTable::add_entry(constraint_name, klass1, loader_data1, klass2, loader_data2); -#if INCLUDE_CDS if (CDSConfig::is_dumping_archive() && klass_being_linked != nullptr && !klass_being_linked->in_aot_cache()) { AOTSystemDictionary::record_linking_constraint(constraint_name, InstanceKlass::cast(klass_being_linked), class_loader1, class_loader2); } -#endif // INCLUDE_CDS if (Signature::is_array(class_name)) { constraint_name->decrement_refcount(); } @@ -2585,7 +2579,7 @@ bool SystemDictionary::is_nonpublic_Object_method(Method* m) { // ---------------------------------------------------------------------------- void SystemDictionary::print_on(outputStream *st) { - CDS_ONLY(AOTSystemDictionary::print_on(st)); + AOTSystemDictionary::print_on(st); GCMutexLocker mu(SystemDictionary_lock); ClassLoaderDataGraph::print_dictionary(st); @@ -2617,7 +2611,7 @@ void SystemDictionary::dump(outputStream *st, bool verbose) { if (verbose) { print_on(st); } else { - CDS_ONLY(AOTSystemDictionary::print_table_statistics(st)); + AOTSystemDictionary::print_table_statistics(st); ClassLoaderDataGraph::print_table_statistics(st); LoaderConstraintTable::print_table_statistics(st); } diff --git a/src/hotspot/share/classfile/vmClasses.cpp b/src/hotspot/share/classfile/vmClasses.cpp index 396d7e5b61e..3306ae55f20 100644 --- a/src/hotspot/share/classfile/vmClasses.cpp +++ b/src/hotspot/share/classfile/vmClasses.cpp @@ -84,7 +84,6 @@ bool vmClasses::contain(Klass* k) { bool vmClasses::resolve(vmClassID id, TRAPS) { InstanceKlass** klassp = &_klasses[as_int(id)]; -#if INCLUDE_CDS if (CDSConfig::is_using_archive() && !JvmtiExport::should_post_class_prepare()) { InstanceKlass* k = *klassp; assert(k->defined_by_boot_loader(), "must be"); @@ -93,7 +92,6 @@ bool vmClasses::resolve(vmClassID id, TRAPS) { resolve_shared_class(k, loader_data, Handle(), CHECK_false); return true; } -#endif // INCLUDE_CDS if (!is_loaded(*klassp)) { int sid = vm_class_name_ids[as_int(id)]; @@ -125,11 +123,9 @@ void vmClasses::resolve_all(TRAPS) { // after vmSymbols::initialize() is called but before any classes are pre-loaded. ClassLoader::classLoader_init2(THREAD); -#if INCLUDE_CDS if (CDSConfig::is_using_aot_linked_classes()) { AOTLinkedClassBulkLoader::preload_classes(THREAD); } -#endif // Preload commonly used klasses vmClassID scan = vmClassID::FIRST; diff --git a/src/hotspot/share/code/aotCodeCache.cpp b/src/hotspot/share/code/aotCodeCache.cpp index b2fc7af4924..f7d6eb344e3 100644 --- a/src/hotspot/share/code/aotCodeCache.cpp +++ b/src/hotspot/share/code/aotCodeCache.cpp @@ -1363,6 +1363,7 @@ AOTCodeEntry* AOTCodeCache::find_code_entry(const methodHandle& method, uint com const char* target_name = method->name_and_sig_as_C_string(); log.print_cr("Missing entry for '%s' (comp_level %d, id: " UINT32_FORMAT_X_0 ")", target_name, (uint)comp_level, id); } + return nullptr; #ifdef ASSERT } else { assert(!entry->has_clinit_barriers(), "only preload code should have clinit barriers"); @@ -1373,8 +1374,30 @@ AOTCodeEntry* AOTCodeCache::find_code_entry(const methodHandle& method, uint com #endif } + if (entry->not_entrant()) { + return nullptr; + } + + // There is harmless concurrency here when reading fields in the AOTCodeEntry. + // The _loaded field is monotonic. It is set in nmethod::new_nmethod under + // CodeCache_lock while ciEnv::register_aot_method holds MethodCompileQueue_lock. + // We might race with other threads which quickly queue and then load + // the method, and harmlessly conclude that this code entry is still loadable. + // Even if we manage to queue a second load concurrently, + // CompileBroker::compile_method_base checks, under the MCQ lock, with + // compilation_is_in_queue and compilation_is_complete, to avoid duplicate work. + if (entry->is_loaded()) { + return nullptr; // AOT code for this entry was loaded already by other thread. + } + + if (entry->is_verified()) { + // With VerifyAOTCode AOT code is only verified without installation + assert(VerifyAOTCode, "sanity"); + return nullptr; // AOT code was already verified + } + #ifdef COMPILER2 - if (entry != nullptr && entry->has_vectors() && !EnableVectorSupport) { + if (entry->has_vectors() && !EnableVectorSupport) { log_debug(aot, codecache, nmethod)("AOT Tier4 code skipped: incompatible EnableVectorSupport: true vs current %u", EnableVectorSupport); return nullptr; } diff --git a/src/hotspot/share/code/nmethod.cpp b/src/hotspot/share/code/nmethod.cpp index 4742914deb7..aa5c331438e 100644 --- a/src/hotspot/share/code/nmethod.cpp +++ b/src/hotspot/share/code/nmethod.cpp @@ -2628,15 +2628,13 @@ void nmethod::post_delayed_compiled_method_load_events() { // new method for install_code() path // Transfer information from compilation to jvmti void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) { -#if INCLUDE_CDS - if (!ServiceThread::has_started()) { + if (CDSConfig::is_using_aot_linked_classes() && !ServiceThread::has_started()) { // With AOT-linked classes, we could compile wrappers for native methods before the // ServiceThread has been started, so we must delay the events to be posted later. assert(state == nullptr, "must be"); add_delayed_compiled_method_load_event(this); return; } -#endif // This is a bad time for a safepoint. We don't want // this nmethod to get unloaded while we're queueing the event. diff --git a/src/hotspot/share/compiler/compilationPolicy.cpp b/src/hotspot/share/compiler/compilationPolicy.cpp index 4c1f2e727c1..8f18d9dfbe1 100644 --- a/src/hotspot/share/compiler/compilationPolicy.cpp +++ b/src/hotspot/share/compiler/compilationPolicy.cpp @@ -91,18 +91,7 @@ AOTCodeEntry* find_aot_code_entry(const methodHandle& method, int comp_level, compile_reason == CompileTask::Reason_Tiered || compile_reason == CompileTask::Reason_MustBeCompiled); if (AOTCodeCache::is_using_code()) { - AOTCodeEntry* aot_code_entry = AOTCodeCache::find_code_entry(method, comp_level); - // There is harmless concurrency here when reading fields in the AOTCodeEntry. - // The _loaded field is monotonic, going true in ciEnv::register_aot_method under - // MethodCompileQueue_lock. We might race with other threads which quickly queue - // and then load the method, and harmlessly conclude that this code entry is - // still loadable. Even if we manage to queue a second load concurrently, - // CompileBroker::compile_method_base checks, under the MCQ lock, with - // compilation_is_in_queue and compilation_is_complete, to avoid duplicate work. - if (aot_code_entry != nullptr && !aot_code_entry->is_loaded() && - !aot_code_entry->not_entrant() && !aot_code_entry->is_verified()) { - return aot_code_entry; - } + return AOTCodeCache::find_code_entry(method, comp_level); } return nullptr; } diff --git a/src/hotspot/share/compiler/compilerDirectives.cpp b/src/hotspot/share/compiler/compilerDirectives.cpp index 03649addc60..3fa19d45e1c 100644 --- a/src/hotspot/share/compiler/compilerDirectives.cpp +++ b/src/hotspot/share/compiler/compilerDirectives.cpp @@ -216,12 +216,10 @@ bool DirectiveSet::should_print_memstat() const { size_t DirectiveSet::mem_limit() const { size_t limit = MemLimitOption < 0 ? -MemLimitOption : MemLimitOption; -#if INCLUDE_CDS if (CDSConfig::is_dumping_aot_code()) { // Double limit for AOT compilation because it generates more code. limit = limit * 2; } -#endif return limit; } diff --git a/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp b/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp index f8efea8979d..f07b5f0b81d 100644 --- a/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp +++ b/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp @@ -190,7 +190,6 @@ void CardTableBarrierSetC1::post_barrier(LIRAccess& access, LIR_Opr addr, LIR_Op } LIR_Address* card_addr; -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { // load the card table address from the AOT Runtime Constants area LIR_Opr byte_map_base_adr = LIR_OprFact::intptrConst(AOTRuntimeConstants::card_table_base_address()); @@ -199,9 +198,7 @@ void CardTableBarrierSetC1::post_barrier(LIRAccess& access, LIR_Opr addr, LIR_Op LIR_Address* byte_map_base_indirect = new LIR_Address(byte_map_base_reg, 0, T_LONG); __ move(byte_map_base_indirect, byte_map_base_reg); card_addr = new LIR_Address(tmp, byte_map_base_reg, T_BYTE); - } else -#endif - if (gen->can_inline_as_constant(card_table_base)) { + } else if (gen->can_inline_as_constant(card_table_base)) { card_addr = new LIR_Address(tmp, card_table_base->as_jint(), T_BYTE); } else { card_addr = new LIR_Address(tmp, gen->load_constant(card_table_base), T_BYTE); diff --git a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp index 769f31fa7df..47760ed9e75 100644 --- a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp +++ b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp @@ -145,13 +145,11 @@ Node* CardTableBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access Node* CardTableBarrierSetC2::byte_map_base_node(IdealKit* kit) const { // Get base of card map -#if INCLUDE_CDS if (AOTCodeCache::is_on_for_dump()) { // load the card table address from the AOT Runtime Constants area Node* byte_map_base_adr = kit->makecon(TypeRawPtr::make(AOTRuntimeConstants::card_table_base_address())); return kit->load_aot_const(byte_map_base_adr, TypeRawPtr::NOTNULL); } -#endif CardTable::CardValue* card_table_base = ci_card_table_address_const(); if (card_table_base != nullptr) { return kit->makecon(TypeRawPtr::make((address)card_table_base, relocInfo::none)); diff --git a/src/hotspot/share/interpreter/rewriter.cpp b/src/hotspot/share/interpreter/rewriter.cpp index c62ae1494a3..2048414e3ee 100644 --- a/src/hotspot/share/interpreter/rewriter.cpp +++ b/src/hotspot/share/interpreter/rewriter.cpp @@ -132,7 +132,6 @@ void Rewriter::make_constant_pool_cache(TRAPS) { _pool->initialize_resolved_references(loader_data, _resolved_references_map, _resolved_reference_limit, THREAD); -#if INCLUDE_CDS if (!HAS_PENDING_EXCEPTION && CDSConfig::is_dumping_archive()) { if (_pool->pool_holder()->in_aot_cache()) { assert(CDSConfig::is_dumping_dynamic_archive(), "must be"); @@ -141,7 +140,6 @@ void Rewriter::make_constant_pool_cache(TRAPS) { // need to save its CpCaches. } } -#endif // Clean up constant pool cache if initialize_resolved_references() failed. if (HAS_PENDING_EXCEPTION) { @@ -576,11 +574,9 @@ void Rewriter::rewrite_bytecodes(TRAPS) { } void Rewriter::rewrite(InstanceKlass* klass, TRAPS) { -#if INCLUDE_CDS if (klass->in_aot_cache()) { assert(!klass->is_rewritten(), "rewritten classes in the AOT cache cannot be rewritten again"); } -#endif // INCLUDE_CDS ResourceMark rm(THREAD); constantPoolHandle cpool(THREAD, klass->constants()); Rewriter rw(klass, cpool, klass->methods(), CHECK); diff --git a/src/hotspot/share/memory/metaspace.cpp b/src/hotspot/share/memory/metaspace.cpp index 8cc67d77dad..f5c47572ae7 100644 --- a/src/hotspot/share/memory/metaspace.cpp +++ b/src/hotspot/share/memory/metaspace.cpp @@ -851,7 +851,7 @@ void Metaspace::global_initialize() { LogTarget(Info, gc, metaspace) lt; if (lt.is_enabled()) { LogStream ls(lt); - CDS_ONLY(AOTMetaspace::print_on(&ls);) + AOTMetaspace::print_on(&ls); Metaspace::print_compressed_class_space(&ls); CompressedKlassPointers::print_mode(&ls); } diff --git a/src/hotspot/share/memory/universe.cpp b/src/hotspot/share/memory/universe.cpp index 29ff059dd69..0f4556bc958 100644 --- a/src/hotspot/share/memory/universe.cpp +++ b/src/hotspot/share/memory/universe.cpp @@ -458,16 +458,13 @@ void Universe::genesis(TRAPS) { s = StringTable::intern("-2147483648", CHECK); _the_min_jint_string = OopHandle(vm_global(), s); -#if INCLUDE_CDS if (CDSConfig::is_using_archive()) { // Verify shared interfaces array. assert(_the_array_interfaces_array->at(0) == vmClasses::Cloneable_klass(), "u3"); assert(_the_array_interfaces_array->at(1) == vmClasses::Serializable_klass(), "u3"); - } else -#endif - { + } else { // Set up shared interfaces array. (Do this before supers are set up.) _the_array_interfaces_array->at_put(0, vmClasses::Cloneable_klass()); _the_array_interfaces_array->at_put(1, vmClasses::Serializable_klass()); @@ -925,17 +922,14 @@ jint universe_init() { // as it might need to access the string table. StringTable::create_table(); -#if INCLUDE_CDS if (CDSConfig::is_using_archive()) { // Read the data structures supporting the shared spaces (shared // system dictionary, symbol table, etc.) AOTMetaspace::initialize_shared_spaces(); } -#endif ClassLoaderData::init_null_class_loader_data(); -#if INCLUDE_CDS #if INCLUDE_CDS_JAVA_HEAP if (CDSConfig::is_using_full_module_graph()) { AOTModules::restore_archived_entries_for_null_class_loader_data(); @@ -944,7 +938,6 @@ jint universe_init() { if (CDSConfig::is_dumping_archive()) { CDSConfig::prepare_for_dumping(); } -#endif SymbolTable::create_table(); @@ -1203,9 +1196,7 @@ bool universe_post_init() { // Complete initialization Universe::heap()->post_initialize(); -#if INCLUDE_CDS AOTMetaspace::post_initialize(CHECK_false); -#endif return true; } diff --git a/src/hotspot/share/oops/cpCache.cpp b/src/hotspot/share/oops/cpCache.cpp index 2c100403bf3..88124cd97ed 100644 --- a/src/hotspot/share/oops/cpCache.cpp +++ b/src/hotspot/share/oops/cpCache.cpp @@ -697,7 +697,6 @@ void ConstantPoolCache::deallocate_contents(ClassLoaderData* data) { set_resolved_references(OopHandle()); MetadataFactory::free_array(data, _reference_map); set_reference_map(nullptr); -#if INCLUDE_CDS if (_resolved_indy_entries != nullptr) { MetadataFactory::free_array(data, _resolved_indy_entries); _resolved_indy_entries = nullptr; @@ -710,7 +709,6 @@ void ConstantPoolCache::deallocate_contents(ClassLoaderData* data) { MetadataFactory::free_array(data, _resolved_method_entries); _resolved_method_entries = nullptr; } -#endif } #if INCLUDE_CDS_JAVA_HEAP diff --git a/src/hotspot/share/oops/trainingData.cpp b/src/hotspot/share/oops/trainingData.cpp index eabeca333c1..bb7673e1ad2 100644 --- a/src/hotspot/share/oops/trainingData.cpp +++ b/src/hotspot/share/oops/trainingData.cpp @@ -80,7 +80,7 @@ void TrainingData::initialize() { }); } - if (have_data() && AOTVerifyTrainingData) { + if (have_data()) { TrainingDataLocker l; verify(); } @@ -93,6 +93,9 @@ static void verify_archived_entry(TrainingData* td, const TrainingData::Key* k) } void TrainingData::verify() { + if (!AOTVerifyTrainingData) { + return; + } if (have_data() && !need_data() && !assembling_data()) { archived_training_data_dictionary()->iterate_all([&](TrainingData* td) { if (td->is_KlassTrainingData()) { @@ -591,9 +594,7 @@ void TrainingData::init_dumptime_table(TRAPS) { TrainingDataLocker::snapshot(); } - if (AOTVerifyTrainingData) { - TrainingData::verify(); - } + TrainingData::verify(); } void TrainingData::dumptime_iterate_roots(MetaspaceClosure* it) { diff --git a/src/hotspot/share/oops/trainingData.hpp b/src/hotspot/share/oops/trainingData.hpp index 939265abcd3..854d05a14be 100644 --- a/src/hotspot/share/oops/trainingData.hpp +++ b/src/hotspot/share/oops/trainingData.hpp @@ -339,7 +339,7 @@ class TrainingData : public Metadata { static void initialize() NOT_CDS_RETURN; - static void verify(); + static void verify() NOT_CDS_RETURN; // Widget for recording dependencies, as an N-to-M graph relation, // possibly cyclic. @@ -489,7 +489,7 @@ class TrainingData : public Metadata { return nullptr; } - static void cleanup_after_redefinition(); + static void cleanup_after_redefinition() NOT_CDS_RETURN; }; // Training data that is associated with an InstanceKlass diff --git a/src/hotspot/share/opto/parse1.cpp b/src/hotspot/share/opto/parse1.cpp index 32ee4d8dbe8..1c3e1360835 100644 --- a/src/hotspot/share/opto/parse1.cpp +++ b/src/hotspot/share/opto/parse1.cpp @@ -1607,7 +1607,7 @@ void Parse::do_method_entry() { } } - CDS_ONLY( count_aot_code_calls(); ) + count_aot_code_calls(); } //------------------------------init_blocks------------------------------------ diff --git a/src/hotspot/share/prims/jvm.cpp b/src/hotspot/share/prims/jvm.cpp index 4664ab72c19..1f1fd9e8726 100644 --- a/src/hotspot/share/prims/jvm.cpp +++ b/src/hotspot/share/prims/jvm.cpp @@ -233,7 +233,6 @@ extern void trace_class_resolution(Klass* to_class) { // java.lang.System ////////////////////////////////////////////////////////////////////// JVM_ENTRY(jboolean, JVM_AOTEndRecording(JNIEnv *env)) -#if INCLUDE_CDS if (CDSConfig::is_dumping_aot_configuration()) { if (!AOTMetaspace::aot_configuration_dumped()) { AOTMetaspace::dump_static_archive(THREAD); @@ -241,9 +240,6 @@ JVM_ENTRY(jboolean, JVM_AOTEndRecording(JNIEnv *env)) } } return JNI_FALSE; -#else - return JNI_FALSE; -#endif // INCLUDE_CDS JVM_END JVM_LEAF(jlong, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored)) @@ -2914,7 +2910,6 @@ static void thread_entry(JavaThread* thread, TRAPS) { JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)) -#if INCLUDE_CDS if (CDSConfig::allow_only_single_java_thread()) { // During java -Xshare:dump, if we allow multiple Java threads to // execute in parallel, symbols and classes may be loaded in @@ -2933,7 +2928,6 @@ JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)) } return; } -#endif JavaThread *native_thread = nullptr; // We cannot hold the Threads_lock when we throw an exception, diff --git a/src/hotspot/share/prims/jvmtiAgent.cpp b/src/hotspot/share/prims/jvmtiAgent.cpp index a021ad8f6f8..720e9586184 100644 --- a/src/hotspot/share/prims/jvmtiAgent.cpp +++ b/src/hotspot/share/prims/jvmtiAgent.cpp @@ -582,7 +582,6 @@ static bool invoke_Agent_OnAttach(JvmtiAgent* agent, outputStream* st) { return true; } -#if INCLUDE_CDS static void check_cds_dump(JvmtiAgent* agent) { if (CDSConfig::new_aot_flags_used()) { // JEP 483 // Agents are allowed with -XX:AOTMode=record and -XX:AOTMode=required/auto. @@ -593,7 +592,6 @@ static void check_cds_dump(JvmtiAgent* agent) { vm_exit_during_cds_dumping("JVMTI agents are not allowed when dumping CDS archives"); } } -#endif // INCLUDE_CDS // Loading the agent by invoking Agent_OnLoad. static bool invoke_Agent_OnLoad(JvmtiAgent* agent) { @@ -601,11 +599,9 @@ static bool invoke_Agent_OnLoad(JvmtiAgent* agent) { assert(!agent->is_xrun(), "invariant"); assert(!agent->is_dynamic(), "invariant"); assert(JvmtiEnvBase::get_phase() == JVMTI_PHASE_ONLOAD, "invariant"); -#if INCLUDE_CDS if (CDSConfig::is_dumping_archive()) { check_cds_dump(agent); } -#endif OnLoadEntry_t on_load_entry = lookup_Agent_OnLoad_entry_point(agent, /* vm exit on error */ true); assert(on_load_entry != nullptr, "invariant"); // Invoke the Agent_OnLoad function diff --git a/src/hotspot/share/prims/jvmtiRedefineClasses.cpp b/src/hotspot/share/prims/jvmtiRedefineClasses.cpp index aea0c6c32f8..e6a0643d7ec 100644 --- a/src/hotspot/share/prims/jvmtiRedefineClasses.cpp +++ b/src/hotspot/share/prims/jvmtiRedefineClasses.cpp @@ -251,7 +251,6 @@ void VM_RedefineClasses::doit() { _timer_vm_op_doit.start(); } -#if INCLUDE_CDS if (CDSConfig::is_using_archive()) { // Sharing is enabled so we remap the shared readonly space to // shared readwrite, private just in case we need to redefine @@ -264,7 +263,6 @@ void VM_RedefineClasses::doit() { return; } } -#endif // Mark methods seen on stack and everywhere else so old methods are not // cleaned up if they're on the stack. @@ -276,9 +274,7 @@ void VM_RedefineClasses::doit() { redefine_single_class(current, _class_defs[i].klass, _scratch_classes[i]); } -#if INCLUDE_CDS TrainingData::cleanup_after_redefinition(); -#endif // Flush all compiled code that depends on the classes redefined. flush_dependent_code(); diff --git a/src/hotspot/share/runtime/init.cpp b/src/hotspot/share/runtime/init.cpp index 03d478c2a45..a24b64c6ef3 100644 --- a/src/hotspot/share/runtime/init.cpp +++ b/src/hotspot/share/runtime/init.cpp @@ -69,9 +69,7 @@ void icache_init2(); void initialize_stub_info(); // must precede all blob/stub generation void preuniverse_stubs_init(); -#if INCLUDE_CDS void stubs_AOTAddressTable_init(); -#endif // INCLUDE_CDS void initial_stubs_init(); jint universe_init(); // depends on codeCache_init and preuniverse_stubs_init @@ -153,10 +151,8 @@ jint init_globals() { AOTCodeCache::init2(); // depends on universe_init, must be before initial_stubs_init AsyncLogWriter::initialize(); -#if INCLUDE_CDS stubs_AOTAddressTable_init(); // publish external addresses used by stubs // depends on AOTCodeCache::init2 -#endif // INCLUDE_CDS initial_stubs_init(); // stubgen initial stub routines // stack overflow exception blob is referenced by the interpreter SharedRuntime::generate_initial_stubs(); diff --git a/src/hotspot/share/runtime/java.cpp b/src/hotspot/share/runtime/java.cpp index 4950408d2c9..867b50442fc 100644 --- a/src/hotspot/share/runtime/java.cpp +++ b/src/hotspot/share/runtime/java.cpp @@ -23,7 +23,6 @@ */ #include "cds/aotMetaspace.hpp" -#include "cds/cds_globals.hpp" #include "cds/cdsConfig.hpp" #include "cds/classListWriter.hpp" #include "cds/dynamicArchive.hpp" @@ -63,6 +62,7 @@ #include "oops/objArrayOop.hpp" #include "oops/oop.inline.hpp" #include "oops/symbol.hpp" +#include "oops/trainingData.hpp" #include "prims/jvmtiAgentList.hpp" #include "prims/jvmtiExport.hpp" #include "runtime/continuation.hpp" @@ -448,13 +448,11 @@ void before_exit(JavaThread* thread, bool halt) { // Actual shutdown logic begins here. -#if INCLUDE_CDS ClassListWriter::write_resolved_constants(); if (CDSConfig::is_dumping_aot_configuration()) { AOTMetaspace::dump_static_archive(thread); } -#endif // Hang forever on exit if we're reporting an error. if (ShowMessageBoxOnError && VMError::is_error_reported()) { @@ -506,11 +504,7 @@ void before_exit(JavaThread* thread, bool halt) { // Note: we don't wait until it actually dies. os::terminate_signal_thread(); - #if INCLUDE_CDS - if (AOTVerifyTrainingData) { - TrainingData::verify(); - } - #endif + TrainingData::verify(); print_statistics_before_exit(); diff --git a/src/hotspot/share/runtime/sharedRuntime.cpp b/src/hotspot/share/runtime/sharedRuntime.cpp index 6294d9c7307..7197ed89fe4 100644 --- a/src/hotspot/share/runtime/sharedRuntime.cpp +++ b/src/hotspot/share/runtime/sharedRuntime.cpp @@ -182,10 +182,8 @@ void SharedRuntime::generate_stubs() { generate_deopt_blob(); -#if INCLUDE_CDS // disallow any further generation of runtime stubs AOTCodeCache::set_shared_stubs_complete(); -#endif // INCLUDE_CDS } void SharedRuntime::init_adapter_library() { diff --git a/src/hotspot/share/runtime/stubRoutines.cpp b/src/hotspot/share/runtime/stubRoutines.cpp index db513a3771e..340874f16d6 100644 --- a/src/hotspot/share/runtime/stubRoutines.cpp +++ b/src/hotspot/share/runtime/stubRoutines.cpp @@ -320,11 +320,8 @@ STUBGEN_BLOBS_DO(DEFINE_BLOB_INIT_FUNCTION) #undef DEFINE_BLOB_INIT_FUNCTION -#if INCLUDE_CDS // non-generated external API init driver function - void stubs_AOTAddressTable_init() { StubRoutines::init_AOTAddressTable(); } -#endif // INCLUDE_CDS /* * we generate the underlying driver function compiler_stubs_init() diff --git a/src/hotspot/share/runtime/stubRoutines.hpp b/src/hotspot/share/runtime/stubRoutines.hpp index fb1b47d2596..6f20b57c135 100644 --- a/src/hotspot/share/runtime/stubRoutines.hpp +++ b/src/hotspot/share/runtime/stubRoutines.hpp @@ -283,10 +283,8 @@ class StubRoutines: AllStatic { static BlobId stub_to_blob(StubId id); #endif -#if INCLUDE_CDS // AOT Initalization -- implementation is arch-specific - static void init_AOTAddressTable(); -#endif // INCLUDE_CDS + static void init_AOTAddressTable() NOT_CDS_RETURN; // Debugging static jint verify_oop_count() { return _verify_oop_count; } diff --git a/src/hotspot/share/runtime/threads.cpp b/src/hotspot/share/runtime/threads.cpp index 73e25346941..4f0eede6a1e 100644 --- a/src/hotspot/share/runtime/threads.cpp +++ b/src/hotspot/share/runtime/threads.cpp @@ -846,13 +846,10 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { JFR_ONLY(Jfr::on_create_vm_3();) #if INCLUDE_MANAGEMENT - bool start_agent = true; -#if INCLUDE_CDS - start_agent = !CDSConfig::is_dumping_aot_cache(); + bool start_agent = !CDSConfig::is_dumping_aot_cache(); if (!start_agent) { log_info(aot)("Not starting management agent during creation of AOT cache."); } -#endif // INCLUDE_CDS if (start_agent) { Management::initialize(THREAD); diff --git a/src/hotspot/share/utilities/vmError.cpp b/src/hotspot/share/utilities/vmError.cpp index 8461f1edf6a..ac958070d70 100644 --- a/src/hotspot/share/utilities/vmError.cpp +++ b/src/hotspot/share/utilities/vmError.cpp @@ -1204,7 +1204,7 @@ void VMError::report(outputStream* st, bool _verbose) { st->cr(); STEP_IF("printing compressed klass pointers mode", _verbose) - CDS_ONLY(AOTMetaspace::print_on(st);) + AOTMetaspace::print_on(st); Metaspace::print_compressed_class_space(st); CompressedKlassPointers::print_mode(st); st->cr(); @@ -1425,7 +1425,7 @@ void VMError::print_vm_info(outputStream* st) { #endif // STEP("printing compressed class ptrs mode") - CDS_ONLY(AOTMetaspace::print_on(st);) + AOTMetaspace::print_on(st); Metaspace::print_compressed_class_space(st); CompressedKlassPointers::print_mode(st); st->cr(); From 7b387055044d56ab57411c324f66feb58f0a5f84 Mon Sep 17 00:00:00 2001 From: Naoto Sato Date: Thu, 19 Nov 2026 17:17:54 +0000 Subject: [PATCH 08/95] 8397209: RuleBasedCollator throws SIOOBE for rules ending with an unmatched quote Reviewed-by: srl, jlu --- .../share/classes/java/text/PatternEntry.java | 12 ++++++++---- test/jdk/java/text/Collator/G7Test.java | 4 ++-- .../text/Collator/RuleBasedCollatorTest.java | 16 +++++++++++----- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/java.base/share/classes/java/text/PatternEntry.java b/src/java.base/share/classes/java/text/PatternEntry.java index 5486f1c008b..e0ee5c871e9 100644 --- a/src/java.base/share/classes/java/text/PatternEntry.java +++ b/src/java.base/share/classes/java/text/PatternEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,8 +38,6 @@ package java.text; -import java.lang.Character; - /** * Utility class for normalizing and merging patterns for collation. * This is to be used with MergeCollation for adding patterns to an @@ -245,8 +243,11 @@ public PatternEntry next() throws ParseException { case ' ': break; // skip whitespace TODO use Character case '/': inChars = false; break; case '\'': + if (++i >= pattern.length()) { + throw new ParseException("Unterminated quote", i - 1); + } inQuote = true; - ch = pattern.charAt(++i); + ch = pattern.charAt(i); if (newChars.length() == 0) newChars.append(ch); else if (inChars) newChars.append(ch); else newExtension.append(ch); @@ -272,6 +273,9 @@ public PatternEntry next() throws ParseException { } i++; } + if (inQuote) { + throw new ParseException("Unterminated quote", i); + } if (newStrength == UNSET) return null; if (newChars.length() == 0) { diff --git a/test/jdk/java/text/Collator/G7Test.java b/test/jdk/java/text/Collator/G7Test.java index fcb201b0719..12e2f11d594 100644 --- a/test/jdk/java/text/Collator/G7Test.java +++ b/test/jdk/java/text/Collator/G7Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -243,7 +243,7 @@ public void TestDemoTest3() { final Collator myCollation = Collator.getInstance(Locale.US); final String defRules = ((RuleBasedCollator)myCollation).getRules(); RuleBasedCollator tblColl = null; - String newRules = defRules + "& Question'-'mark ; '?' & Hash'-'mark ; '#' & Ampersand ; '&"; + String newRules = defRules + "& Question'-'mark ; '?' & Hash'-'mark ; '#' & Ampersand ; '&'"; try { tblColl = new RuleBasedCollator(newRules); diff --git a/test/jdk/java/text/Collator/RuleBasedCollatorTest.java b/test/jdk/java/text/Collator/RuleBasedCollatorTest.java index cd1e8ca69c0..b9de9d385e0 100644 --- a/test/jdk/java/text/Collator/RuleBasedCollatorTest.java +++ b/test/jdk/java/text/Collator/RuleBasedCollatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 4406815 8222969 8266784 + * @bug 4406815 8222969 8266784 8397209 * @summary RuleBasedCollatorTest uses very limited but selected test data * to test basic functionalities provided by RuleBasedCollator. * @run junit/othervm RuleBasedCollatorTest @@ -215,18 +215,24 @@ void testBasicParsingOrder() throws ParseException { assertEquals(0, k2.compareTo(k3)); } - Object[][] ParseData() { + Object[][] ParseExceptionData() { return new Object[][] { {""}, {"a < b"}, {"< a-b < c"}, {"< ,a"}, - {"< a < b & c < d"} + {"< a < b & c < d"}, + {"'"}, + {"\n'"}, + {"< '"}, + {"< a < '"}, + {"< 'a"}, + {"< a < 'b"} }; } @ParameterizedTest - @MethodSource("ParseData") + @MethodSource("ParseExceptionData") void testParseException(String rule) { assertThrows(ParseException.class, () -> new RuleBasedCollator(rule)); } From f54535cfc797d37a21292cb5d43e77c67100b558 Mon Sep 17 00:00:00 2001 From: Alexander Zuev Date: Thu, 19 Nov 2026 17:31:43 +0000 Subject: [PATCH 09/95] 8396622: [macos27] java/awt/Graphics/NativeWin32Clear.java test fails Reviewed-by: prr, jdv, azvegint --- test/jdk/java/awt/Graphics/NativeWin32Clear.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/jdk/java/awt/Graphics/NativeWin32Clear.java b/test/jdk/java/awt/Graphics/NativeWin32Clear.java index 6cef4fa810a..9acf8bfb032 100644 --- a/test/jdk/java/awt/Graphics/NativeWin32Clear.java +++ b/test/jdk/java/awt/Graphics/NativeWin32Clear.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -76,10 +76,10 @@ public void requestCoordinates(Rectangle r) { Insets insets = getInsets(); Point location = getLocationOnScreen(); Dimension size = getSize(); - r.x = location.x + insets.left + 5; - r.y = location.y + insets.top + 5; - r.width = size.width - (insets.left + insets.right + 10); - r.height = size.height - (insets.top + insets.bottom + 10); + r.x = location.x + insets.left + 10; + r.y = location.y + insets.top + 10; + r.width = size.width - (insets.left + insets.right + 20); + r.height = size.height - (insets.top + insets.bottom + 20); } /* From 510deb132b0c5ff6fefdf7bde56d82223e927b69 Mon Sep 17 00:00:00 2001 From: Volodymyr Paprotski Date: Thu, 19 Nov 2026 17:39:13 +0000 Subject: [PATCH 10/95] 8391494: AES/CTR AVX2 intrinsic and refactor existing CTR Reviewed-by: sviswanathan, semery, kvn --- src/hotspot/cpu/x86/assembler_x86.cpp | 31 +- src/hotspot/cpu/x86/assembler_x86.hpp | 3 +- src/hotspot/cpu/x86/stubGenerator_x86_64.hpp | 13 - .../cpu/x86/stubGenerator_x86_64_aes.cpp | 1795 ++++++++--------- src/hotspot/cpu/x86/vm_version_x86.cpp | 16 +- src/hotspot/cpu/x86/vm_version_x86.hpp | 4 +- .../compiler/codegen/aes/TestAESCTR.java | 90 + .../jdk/test/whitebox/CPUInfoTest.java | 2 +- 8 files changed, 928 insertions(+), 1026 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/codegen/aes/TestAESCTR.java diff --git a/src/hotspot/cpu/x86/assembler_x86.cpp b/src/hotspot/cpu/x86/assembler_x86.cpp index 2191eb676a6..f4ca57c6d36 100644 --- a/src/hotspot/cpu/x86/assembler_x86.cpp +++ b/src/hotspot/cpu/x86/assembler_x86.cpp @@ -1520,9 +1520,9 @@ void Assembler::aesdec(XMMRegister dst, XMMRegister src) { } void Assembler::vaesdec(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { - assert(VM_Version::supports_avx512_vaes(), ""); + assert(VM_Version::supports_vaes() && + (vector_len != AVX_512bit || VM_Version::supports_evex()), ""); InstructionAttr attributes(vector_len, /* vex_w */ false, /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); - attributes.set_is_evex_instruction(); int encode = vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F_38, &attributes); emit_int16((unsigned char)0xDE, (0xC0 | encode)); } @@ -1545,9 +1545,9 @@ void Assembler::aesdeclast(XMMRegister dst, XMMRegister src) { } void Assembler::vaesdeclast(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { - assert(VM_Version::supports_avx512_vaes(), ""); + assert(VM_Version::supports_vaes() && + (vector_len != AVX_512bit || VM_Version::supports_evex()), ""); InstructionAttr attributes(vector_len, /* vex_w */ false, /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); - attributes.set_is_evex_instruction(); int encode = vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F_38, &attributes); emit_int16((unsigned char)0xDF, (0xC0 | encode)); } @@ -1569,9 +1569,9 @@ void Assembler::aesenc(XMMRegister dst, XMMRegister src) { } void Assembler::vaesenc(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { - assert(VM_Version::supports_avx512_vaes(), "requires vaes support/enabling"); + assert(VM_Version::supports_vaes() && + (vector_len != AVX_512bit || VM_Version::supports_evex()), ""); InstructionAttr attributes(vector_len, /* vex_w */ false, /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); - attributes.set_is_evex_instruction(); int encode = vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F_38, &attributes); emit_int16((unsigned char)0xDC, (0xC0 | encode)); } @@ -1593,9 +1593,9 @@ void Assembler::aesenclast(XMMRegister dst, XMMRegister src) { } void Assembler::vaesenclast(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { - assert(VM_Version::supports_avx512_vaes(), "requires vaes support/enabling"); + assert(VM_Version::supports_vaes() && + (vector_len != AVX_512bit || VM_Version::supports_evex()), ""); InstructionAttr attributes(vector_len, /* vex_w */ false, /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); - attributes.set_is_evex_instruction(); int encode = vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F_38, &attributes); emit_int16((unsigned char)0xDD, (0xC0 | encode)); } @@ -5257,7 +5257,7 @@ void Assembler::evpcmpeqq(KRegister kdst, XMMRegister nds, Address src, int vect } void Assembler::pcmpgtq(XMMRegister dst, XMMRegister src) { - assert(VM_Version::supports_sse4_1(), ""); + assert(VM_Version::supports_sse4_2(), ""); InstructionAttr attributes(AVX_128bit, /* rex_w */ false, /* legacy_mode */ true, /* no_mask_reg */ true, /* uses_vl */ false); int encode = simd_prefix_and_encode(dst, dst, src, VEX_SIMD_66, VEX_OPCODE_0F_38, &attributes); emit_int16(0x37, (0xC0 | encode)); @@ -6315,6 +6315,13 @@ void Assembler::punpcklqdq(XMMRegister dst, XMMRegister src) { emit_int16(0x6C, (0xC0 | encode)); } +void Assembler::punpckhqdq(XMMRegister dst, XMMRegister src) { + InstructionAttr attributes(AVX_128bit, /* rex_w */ VM_Version::supports_evex(), /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); + attributes.set_rex_vex_w_reverted(); + int encode = simd_prefix_and_encode(dst, dst, src, VEX_SIMD_66, VEX_OPCODE_0F, &attributes); + emit_int16(0x6D, (0xC0 | encode)); +} + void Assembler::evpunpcklqdq(XMMRegister dst, XMMRegister src1, XMMRegister src2, int vector_len) { evpunpcklqdq(dst, k0, src1, src2, false, vector_len); } @@ -10838,7 +10845,8 @@ void Assembler::vpunpckhdq(XMMRegister dst, XMMRegister nds, XMMRegister src, in void Assembler::vpunpckhqdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { assert(UseAVX > 0, "requires some form of AVX"); - InstructionAttr attributes(vector_len, /* vex_w */ false, /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); + InstructionAttr attributes(vector_len, /* vex_w */ VM_Version::supports_evex(), /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); + attributes.set_rex_vex_w_reverted(); int encode = vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F, &attributes); emit_int16(0x6D, (0xC0 | encode)); } @@ -10852,7 +10860,8 @@ void Assembler::vpunpckldq(XMMRegister dst, XMMRegister nds, XMMRegister src, in void Assembler::vpunpcklqdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { assert(UseAVX > 0, "requires some form of AVX"); - InstructionAttr attributes(vector_len, /* vex_w */ false, /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); + InstructionAttr attributes(vector_len, /* vex_w */ VM_Version::supports_evex(), /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); + attributes.set_rex_vex_w_reverted(); int encode = vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F, &attributes); emit_int16(0x6C, (0xC0 | encode)); } diff --git a/src/hotspot/cpu/x86/assembler_x86.hpp b/src/hotspot/cpu/x86/assembler_x86.hpp index 93932e50186..4b6f2a3eaf5 100644 --- a/src/hotspot/cpu/x86/assembler_x86.hpp +++ b/src/hotspot/cpu/x86/assembler_x86.hpp @@ -2105,8 +2105,9 @@ class Assembler : public AbstractAssembler { void vpunpckhdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len); void vpunpckhqdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len); - // Interleave Low Quadwords + // Interleave Low/High Quadwords void punpcklqdq(XMMRegister dst, XMMRegister src); + void punpckhqdq(XMMRegister dst, XMMRegister src); void evpunpcklqdq(XMMRegister dst, XMMRegister src1, XMMRegister src2, int vector_len); void evpunpcklqdq(XMMRegister dst, KRegister mask, XMMRegister src1, XMMRegister src2, bool merge, int vector_len); diff --git a/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp b/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp index 1d7c802d484..c5ab792d212 100644 --- a/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp +++ b/src/hotspot/cpu/x86/stubGenerator_x86_64.hpp @@ -357,15 +357,6 @@ class StubGenerator: public StubCodeGenerator { void aesgcm_avx2(Register in, Register len, Register ct, Register out, Register key, Register state, Register subkeyHtbl, Register counter); - // Vector AES Counter implementation - address generate_counterMode_VectorAESCrypt(); - void aesctr_encrypt(Register src_addr, Register dest_addr, Register key, Register counter, - Register len_reg, Register used, Register used_addr, Register saved_encCounter_start); - - // This is a version of CTR/AES crypt which does 6 blocks in a loop at a time - // to hide instruction latency - address generate_counterMode_AESCrypt_Parallel(); - address generate_cipherBlockChaining_decryptVectorAESCrypt(); address generate_key_shuffle_mask(); @@ -415,10 +406,6 @@ class StubGenerator: public StubCodeGenerator { void load_key(XMMRegister xmmdst, Register key, int offset, XMMRegister xmm_shuf_mask); void load_key(XMMRegister xmmdst, Register key, int offset, Register rscratch); - // Utility routine for increase 128bit counter (iv in CTR mode) - void inc_counter(Register reg, XMMRegister xmmdst, int inc_delta, Label& next_block); - void ev_add128(XMMRegister xmmdst, XMMRegister xmmsrc1, XMMRegister xmmsrc2, - int vector_len, KRegister ktmp, XMMRegister ones); void generate_aes_stubs(); diff --git a/src/hotspot/cpu/x86/stubGenerator_x86_64_aes.cpp b/src/hotspot/cpu/x86/stubGenerator_x86_64_aes.cpp index b95aa5f8818..48e50a5c743 100644 --- a/src/hotspot/cpu/x86/stubGenerator_x86_64_aes.cpp +++ b/src/hotspot/cpu/x86/stubGenerator_x86_64_aes.cpp @@ -62,17 +62,6 @@ static address counter_shuffle_mask_addr() { return (address)COUNTER_SHUFFLE_MASK; } -// This mask is used for incrementing counter value -ATTRIBUTE_ALIGNED(64) static const uint64_t COUNTER_MASK_LINC0[] = { - 0x0000000000000000UL, 0x0000000000000000UL, - 0x0000000000000001UL, 0x0000000000000000UL, - 0x0000000000000002UL, 0x0000000000000000UL, - 0x0000000000000003UL, 0x0000000000000000UL, -}; -static address counter_mask_linc0_addr() { - return (address)COUNTER_MASK_LINC0; -} - ATTRIBUTE_ALIGNED(16) static const uint64_t COUNTER_MASK_LINC1[] = { 0x0000000000000001UL, 0x0000000000000000UL, }; @@ -114,46 +103,6 @@ static address counter_mask_linc4_addr() { return (address)COUNTER_MASK_LINC4; } -ATTRIBUTE_ALIGNED(64) static const uint64_t COUNTER_MASK_LINC8[] = { - 0x0000000000000008UL, 0x0000000000000000UL, - 0x0000000000000008UL, 0x0000000000000000UL, - 0x0000000000000008UL, 0x0000000000000000UL, - 0x0000000000000008UL, 0x0000000000000000UL, -}; -static address counter_mask_linc8_addr() { - return (address)COUNTER_MASK_LINC8; -} - -ATTRIBUTE_ALIGNED(64) static const uint64_t COUNTER_MASK_LINC16[] = { - 0x0000000000000010UL, 0x0000000000000000UL, - 0x0000000000000010UL, 0x0000000000000000UL, - 0x0000000000000010UL, 0x0000000000000000UL, - 0x0000000000000010UL, 0x0000000000000000UL, -}; -static address counter_mask_linc16_addr() { - return (address)COUNTER_MASK_LINC16; -} - -ATTRIBUTE_ALIGNED(64) static const uint64_t COUNTER_MASK_LINC32[] = { - 0x0000000000000020UL, 0x0000000000000000UL, - 0x0000000000000020UL, 0x0000000000000000UL, - 0x0000000000000020UL, 0x0000000000000000UL, - 0x0000000000000020UL, 0x0000000000000000UL, -}; -static address counter_mask_linc32_addr() { - return (address)COUNTER_MASK_LINC32; -} - -ATTRIBUTE_ALIGNED(64) uint64_t COUNTER_MASK_ONES[] = { - 0x0000000000000000UL, 0x0000000000000001UL, - 0x0000000000000000UL, 0x0000000000000001UL, - 0x0000000000000000UL, 0x0000000000000001UL, - 0x0000000000000000UL, 0x0000000000000001UL, -}; -static address counter_mask_ones_addr() { - return (address)COUNTER_MASK_ONES; -} - ATTRIBUTE_ALIGNED(64) static const uint64_t GHASH_POLYNOMIAL_REDUCTION[] = { 0x00000001C2000000UL, 0xC200000000000000UL, 0x00000001C2000000UL, 0xC200000000000000UL, @@ -204,14 +153,803 @@ static address counter_mask_add_1234_addr() { return (address)COUNTER_MASK_ADD_1234; } -// AES intrinsic stubs +ATTRIBUTE_ALIGNED(64) static const uint64_t COUNTER_ADD[] = { + // Sequence 0-1, arranged for vpunpck{l,h}qdq + 0x0000000000000000ULL, 0x0000000000000001ULL, + 0x0000000000000000ULL, 0x0000000000000000ULL, + + // Sequence 0-3, arranged for vpunpck{l,h}qdq + 0x0000000000000000ULL, 0x0000000000000002ULL, + 0x0000000000000001ULL, 0x0000000000000003ULL, + + // Sequence 0-7, arranged for vpunpck{l,h}qdq + 0x0000000000000000ULL, 0x0000000000000004ULL, + 0x0000000000000001ULL, 0x0000000000000005ULL, + 0x0000000000000002ULL, 0x0000000000000006ULL, + 0x0000000000000003ULL, 0x0000000000000007ULL, +}; + +static address counter_adder_addr(int vector_len) { + switch (vector_len) { + case Assembler::AVX_128bit: return (address)COUNTER_ADD; + case Assembler::AVX_256bit: return (address)&COUNTER_ADD[4]; + case Assembler::AVX_512bit: return (address)&COUNTER_ADD[8]; + } + assert(false, "unreachable"); + return nullptr; +} + +class AESAssembler : public MacroAssembler { +public: + AESAssembler(Assembler *as) : MacroAssembler(as->code()){} + + void add128(XMMRegister CtrLow, XMMRegister CtrHigh, XMMRegister Increment, XMMRegister Tmp1, XMMRegister Tmp2, XMMRegister Tmp3, KRegister tmp4, int vector_len) { + assert(UseAVX > 0 || vector_len == Assembler::AVX_128bit, "Invalid"); + + // There is no carry bit output with AVX VPADDQ operations. On AVX512, we can use unsigned compare + // to detect (from the input and result) if a rollover happened. Without unsigned compare, we have to get creative. + // Turns out we can also use VPANDN to detect if carry had happened. + // + // As proof, look at FULL ADDER truth table for the MSB of an ADD operation: + // Out, Carryout = FullAdder(CTR_63rd_bit, increment, Carryin) + // (Note: increment is a small positive number, so the MSB of it, at 64th position will be zero) + // + // CTR incr Cin Out Cout + // 0 0 0 | 0 0 + // 0 0 1 | 1 0 + // 0 1 0 | 1 0 (impossible; increment MSB=1) + // 0 1 1 | 0 1 (impossible; increment MSB=1) + // 1 0 0 | 1 0 + // 1 0 1 | 0 1 + // 1 1 0 | 0 1 (impossible; increment MSB=1) + // 1 1 1 | 1 1 (impossible; increment MSB=1) + // + // Remove impossible increment values and we only care about Carryout: + // CTR Out Cout + // 0 0 | 0 + // 0 1 | 0 + // 1 1 | 0 + // 1 0 | 1 + // Therefore: Cout = ctr AND ~Out (Q.E.D.) + XMMRegister Carry = Tmp1; + XMMRegister Zero = Tmp2; + if (VM_Version::supports_avx512vl()) { + vpternlogq(Carry, 0xFF, Carry, Carry, vector_len); + vpaddq(CtrLow, CtrLow, Increment, vector_len); + evpcmpuq(tmp4, CtrLow, Increment, Assembler::lt, vector_len); + evpsubq(CtrHigh, tmp4, CtrHigh, Carry, true, vector_len); + } else if (UseAVX > 0) { + vpxor(Zero, Zero, Zero, vector_len); + vmovdqu(Carry, CtrLow, vector_len); + vpaddq(CtrLow, CtrLow, Increment, vector_len); + vpandn(Carry, CtrLow, Carry, vector_len); + vpcmpgtq(Carry, Zero, Carry, vector_len); + vpsubq(CtrHigh, CtrHigh, Carry, vector_len); + } else { + pxor(Zero, Zero); + movdqu(Tmp3, CtrLow); + paddq(CtrLow, Increment); + movdqu(Carry, CtrLow); + pandn(Carry, Tmp3); + pcmpgtq(Zero, Carry); + psubq(CtrHigh, Zero); + } + } + + void vaesenc(XMMRegister dst, XMMRegister key, int vector_len) { + assert(VM_Version::supports_vaes() || vector_len == Assembler::AVX_128bit, "Invalid"); + if (VM_Version::supports_vaes()) { + MacroAssembler::vaesenc(dst, dst, key, vector_len); + } else { + aesenc(dst, key); + } + } + + void vaesenclast(XMMRegister dst, XMMRegister key, int vector_len) { + assert(VM_Version::supports_vaes() || vector_len == Assembler::AVX_128bit, "Invalid"); + if (VM_Version::supports_vaes()) { + MacroAssembler::vaesenclast(dst, dst, key, vector_len); + } else { + aesenclast(dst, key); + } + } + + void aesround(XMMRegister dst, XMMRegister key, bool first, bool last, int vector_len) { + if (first) { + vpxor(dst, dst, key, vector_len); + } else if (!last) { + vaesenc(dst, key, vector_len); + } else { + vaesenclast(dst, key, vector_len); + } + } + + using MacroAssembler::vpbroadcastq; + void vpbroadcastq(XMMRegister dst, int val, int vector_len, Register scratch) { + movq(scratch, val); + if (vector_len == Assembler::AVX_512bit) { + evpbroadcastq(dst, scratch, vector_len); + } else if (vector_len == Assembler::AVX_256bit) { + movq(dst, scratch); + MacroAssembler::vpbroadcastq(dst, dst, vector_len); + } else if (vector_len == Assembler::AVX_128bit) { + movq(dst, scratch); + movddup(dst, dst); + } + } + + void vpbroadcastq(XMMRegister dst, Address src, int vector_len) { + if (vector_len == Assembler::AVX_128bit) { + movq(dst, src); + movddup(dst, dst); + } else { + MacroAssembler::vpbroadcastq(dst, src, vector_len); + } + } + + void vbroadcasti128(XMMRegister dst, Address src, int vector_len) { + if (vector_len == Assembler::AVX_512bit) { + evbroadcasti32x4(dst, src, vector_len); + } else if (vector_len == Assembler::AVX_256bit) { + MacroAssembler::vbroadcasti128(dst, src, vector_len); + } else { + movdqu(dst, src); + } + } + + void vbroadcasti128(XMMRegister dst, XMMRegister src, int vector_len) { + if (vector_len == Assembler::AVX_512bit) { + evshufi64x2(dst, src, src, 0b00000000, vector_len); + } else if (vector_len == Assembler::AVX_256bit) { + vinserti128(dst, src, src, 1); + } else if (vector_len == Assembler::AVX_128bit && dst != src){ + movdqu(dst, src); + } + } + + void vpunpcklqdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { + assert(UseAVX > 0 || vector_len == Assembler::AVX_128bit, "Invalid"); + if (UseAVX > 0) { + MacroAssembler::vpunpcklqdq(dst, nds, src, vector_len); + } else { + if (dst != nds) { + assert_different_registers(dst, src); + movdqu(dst, nds); + } + punpcklqdq(dst, src); + } + } + + void vpunpckhqdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { + assert(UseAVX > 0 || vector_len == Assembler::AVX_128bit, "Invalid"); + if (UseAVX > 0) { + MacroAssembler::vpunpckhqdq(dst, nds, src, vector_len); + } else { + if (dst != nds) { + assert_different_registers(dst, src); + movdqu(dst, nds); + } + punpckhqdq(dst, src); + } + } + + void vpshufb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { + assert(UseAVX > 0 || vector_len == Assembler::AVX_128bit, "Invalid"); + if (UseAVX > 0) { + MacroAssembler::vpshufb(dst, nds, src, vector_len); + } else { + if (dst != nds) { + assert_different_registers(dst, src); + movdqu(dst, nds); + } + pshufb(dst, src); + } + } + + void vpxor(XMMRegister dst, XMMRegister nds, Address src, int vector_len, XMMRegister scratch) { + assert(UseAVX > 0 || vector_len == Assembler::AVX_128bit, "Invalid"); + if (UseAVX > 0) { + MacroAssembler::vpxor(dst, nds, src, vector_len); + } else { + if (dst != nds) { + movdqu(dst, src); + pxor(dst, nds); + } else { + assert(scratch != xnoreg, ""); + assert_different_registers(dst, scratch); + movdqu(scratch, src); + pxor(dst, scratch); + } + } + } + + void vpxor(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { + assert(UseAVX > 0 || vector_len == Assembler::AVX_128bit, "Invalid"); + if (UseAVX > 0) { + MacroAssembler::vpxor(dst, nds, src, vector_len); + } else { + if (dst != nds) { + assert_different_registers(dst, src); + movdqu(dst, nds); + } + pxor(dst, src); + } + } +}; + +// Inputs: Windows | Linux +// src = rcx (c_rarg0) | rdi (c_rarg0) +// dst = rdx (c_rarg1) | rsi (c_rarg1) +// key = r8 (c_rarg2) | rdx (c_rarg2) +// ctr = r9 (c_rarg3) | rcx (c_rarg3) +// len = (stack) | r8 (c_rarg4) +// saved ctr = (stack) | r9 (c_rarg5) +// used addr = (stack) | (stack) +// +// Outputs: +// - rax - input processed +// - saved ctr - encryptedCounter value (partially used) +// - used addr - encryptedCounter start +// - ctr - new counter value +// - dst - encrypted payload +// +// Pseudocode: +// if (len <= 0) return len +// while (used < 16 && len-- > 0) { +// out[pos++] = in[pos] ^ encryptedCounter[used++]; +// } +// if (len<=16) { // Single Block +// switch keyLength +// for all keys{load and shuf key; aesround(1 per key)} +// compute&store used&nextCtr +// cleanup +// if (len<16) goto LastBlock +// XOR data +// goto Exit +// } else { +// init first two counters (CtrLow,CtrHigh,Ctr[0],Ctr[1]) +// init first 10 keys, 10x aesround(2 per key) +// switch keyLength +// init remaining keys, aesrounds(2 per key) +// compute&store used&nextCtr +// +// if (len<2*blocksPerReg*16) goto LastSet +// XOR data // 2 full registers +// incr 2 counters +// len -= 2*blocksPerReg*16 +// if (len==0) goto Scrub +// +// full aesrounds(2 per key) // Peel another iteration from LOOP +// if (len<2*blocksPerReg*16) goto LastSet +// XOR data // 2 full registers +// incr 2 counters +// len -= 2*blocksPerReg*16 +// if (len==0) goto Scrub +// +// incr rest of counters +// LOOP: +// full aesrounds(maxParallel per key) +// if (len>= 256 bits +// len -= 32 +// Last2Block: +// if AVX512||AVX256 +// if (len<16) goto Scrub +// XOR data // lower 128 bits +// LastCtr >>= 128 bits +// len -= 16 +// Scrub: +// Zero out all Key and Ctr regs +// Zero out stack slots for spilled keys +// +// LastBlock: +// if (len==0) goto Exit +// store LastCtr +// if (len<8) goto Last4Byte +// XOR data // lower 64 bits +// LastCtr >>= 64 bits +// len -= 8 +// Last4Byte +// if (len<4) goto Last2Byte +// XOR data // lower 32 bits +// LastCtr >>= 32 bits +// len -= 4 +// Last2Byte +// if (len<2) goto LastByte +// XOR data // lower 16 bits +// LastCtr >>= 16 bits +// len -= 2 +// LastByte +// if (len<1) goto Exit +// XOR data // 8 bits +// Exit +// Zero out LastCtr +static address generate_counterModeAES(StubGenerator *stubgen, + int vector_len, AESAssembler *_masm, int maxParallel) { + assert(UseAES, "need AES instruction support"); + assert(maxParallel <= 6, ""); + assert(maxParallel % 2 == 0, "invalid parallel"); + + StubId stub_id = StubId::stubgen_counterMode_AESCrypt_id; + int entry_count = StubInfo::entry_count(stub_id); + assert(entry_count == 1, "sanity check"); + address start = stubgen->load_archive_data(stub_id); + if (start != nullptr) { + return start; + } + __ align(CodeEntryAlignment); + StubCodeMark mark(stubgen, stub_id); + start = __ pc(); + __ enter(); + + const Register src = c_rarg0; // source array address + const Register dst = c_rarg1; // destination array address + const Register key = c_rarg2; // key array address + const Register ctr = c_rarg3; // counter byte array initialized from counter array address + // and updated with the incremented counter in the end +#ifdef _WIN64 + const Register len = rsi; // 5th arg, on stack + const Register savedCtr = rdi;// 6th arg, on stack + const Register usedAddr = r10;// 7th arg, on stack + + __ push_ppx(rsi); + __ push_ppx(rdi); + __ movl(len, Address(rbp, 6 * wordSize)); + __ movptr(savedCtr, Address(rbp, 7 * wordSize)); + __ movptr(usedAddr, Address(rbp, 8 * wordSize)); +#else + const Register len = c_rarg4; + const Register savedCtr = c_rarg5; + const Register usedAddr = r10; // 7th arg, on stack + + __ movptr(usedAddr, Address(rbp, 2 * wordSize)); +#endif + + const Register pos = rax; // also return value + const Register used = r11; + const Register keyLength = r11; // used overload + const Register nextCtrLow = r12; + const Register nextCtrHigh = r13; + const Register tmp = r14; + + Label UsedLoop, UsedLoopDone, LastSet, LastReg, Last2Block, LastBlock; + Label Last4Byte, Last2Byte, LastByte, ExitLabel, SingleBlock, Scrub, NoEarlyRet; + + // Registers, need to allocate: + // AVX_512bit | AVX_256bit&AVX_128bit + // - 5 Temps Regs | Regs + // - (parallel) CTRs Regs | Regs + // - 15 keys Regs | Regs&Stack + + // Constants/parameters + int totalRegs = VM_Version::supports_avx512vlbw() ? 32 : 16; + int keyRegs = totalRegs - 5 - maxParallel; // 5 temps + keyRegs = keyRegs > 15 ? 15 : keyRegs; + int blocksPerReg = vector_len == Assembler::AVX_512bit ? 4 : + vector_len == Assembler::AVX_256bit ? 2 : 1; + + // Each key (that doesn't have a register) takes 16 bytes + int totalStackBytes = 16*(15 - keyRegs); + char comments[64]; + + // XMMRegister allocation + XMMRegister Increment = xmm0; + XMMRegister KeyShuf = xmm0; // overlaps Increment + XMMRegister Tmp = xmm1; + XMMRegister CtrShuf = xmm2; + XMMRegister LastCtr = xmm3; // Last encrypted counter, to be stored to *used + XMMRegister CtrLow = xmm3; + XMMRegister CtrHigh = xmm4; + XMMRegister Ctr[6]; + XMMRegister Keys[15]; + XMMRegister _next = xmm5; + for (int i = 0; isuccessor()) { + Ctr[i] = _next; + } + for (int i = 0; i < keyRegs && _next->is_valid(); i++, _next = _next->successor()) { + Keys[i] = _next; + } + + // if (len <= 0) return len + __ movl(pos, len); + __ cmpl(len, 0); + __ jcc(Assembler::greater, NoEarlyRet); +#ifdef _WIN64 + __ pop_ppx(rdi); + __ pop_ppx(rsi); +#endif + __ leave(); // required for proper stackwalking of RuntimeStub frame + __ ret(0); + + __ BIND(NoEarlyRet); + __ push_ppx(r12); + __ push_ppx(r13); + __ push_ppx(r14); + + if (totalStackBytes > 0) { + // Buy and align stack + __ andq(rsp, -64); + __ subptr(rsp, totalStackBytes); // Enough to store all keys + } + + // use up any counter already created by previous encryption invocation + // it's at most 15 bytes + // while (used < 16 && len-- > 0) {out[pos++] = in[pos] ^ encryptedCounter[used++];} + // No OptoLoopAlignment, case not common enough + __ movl(pos, 0); + __ movl(used, Address(usedAddr, 0)); + __ BIND(UsedLoop); + __ cmpl(used, 16); + __ jcc(Assembler::aboveEqual, UsedLoopDone); + __ movb(tmp, Address(savedCtr, used)); + __ xorb(tmp, Address(src, pos)); + __ movb(Address(dst, pos), tmp); + __ incrementl(pos); + __ incrementl(used); + __ decrementl(len); + __ jcc(Assembler::notZero, UsedLoop); + __ movl(Address(usedAddr, 0), used); + __ jmp(ExitLabel); + __ BIND(UsedLoopDone); + + __ movl(keyLength, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT))); + __ cmpl(len, 16); // Specialize single-block encryption + __ jcc(Assembler::belowEqual, SingleBlock); + + /********************** INIT COUNTERS **********************/ + // initialize enough counters for parallel processing + // (counters always in registers) + BLOCK_COMMENT("Init counters"); + __ vmovdqu(CtrShuf, ExternalAddress(counter_shuffle_mask_addr()), vector_len, tmp /*rscratch*/); //BE->LE + __ vpbroadcastq(CtrLow, Address(ctr, 8), vector_len); + __ vpbroadcastq(CtrHigh, Address(ctr), vector_len); + __ vmovdqa(Increment, ExternalAddress(counter_adder_addr(vector_len)), vector_len, tmp /*rscratch*/); + __ vpshufb(CtrLow, CtrLow, CtrShuf, vector_len); // BE->LE + __ vpshufb(CtrHigh, CtrHigh, CtrShuf, vector_len); // BE->LE + __ pextrq(nextCtrLow, CtrLow, 0x0); + __ pextrq(nextCtrHigh, CtrHigh, 0x0); + // storing nextCtr{Low,High} delayed, get to AES faster + + // First iteration Increment is arranged for the unpack to work + // After first iteration, Increment is a constant step + auto incCtrPair = [&](int i) { + __ add128(CtrLow, CtrHigh, Increment, Tmp, Ctr[i], Ctr[i+1], k1, vector_len); + __ vpunpcklqdq(Ctr[i], CtrLow, CtrHigh, vector_len); + __ vpunpckhqdq(Ctr[i+1], CtrLow, CtrHigh, vector_len); + __ vpshufb(Ctr[i], Ctr[i], CtrShuf, vector_len); + __ vpshufb(Ctr[i+1], Ctr[i+1], CtrShuf, vector_len); + }; + incCtrPair(0); + + /********************** INIT KEYS & FIRST AES ITERATION **********************/ + // convert keys to little-endian (into registers and onto stack) + BLOCK_COMMENT("INIT Keys"); + // (KeyShuf overloaded with Increment) + __ movdqu(KeyShuf, ExternalAddress(key_shuffle_mask_addr()), tmp /*rscratch*/); + auto keysAndRounds = [&](bool init, int from, int to, int keyRounds, int parallel) { + for (int round = from; round < to; round++) { + XMMRegister KeyReg = round < keyRegs ? Keys[round] : Tmp; + if (init) { + __ movdqu(KeyReg, Address(key, round*16)); + __ pshufb(KeyReg, KeyShuf); + + __ vbroadcasti128(KeyReg, KeyReg, vector_len); + if (round >= keyRegs) { + // once ran out of registers, store preshuffled keys to stack + int stackOffset = 16*(round - keyRegs); + __ movdqu(Address(rsp, stackOffset), KeyReg); + } + } else if (round >= keyRegs) { + // once ran out of registers, restore preshuffled keys from stack + int stackOffset = 16*(round - keyRegs); + __ vbroadcasti128(KeyReg, Address(rsp, stackOffset), vector_len); + } + if (KeyReg != Tmp && KeyReg->encoding() > 15 && !VM_Version::supports_vaes()) { + // aesenc can't use higher bank, but we want to still use those registers + __ vmovdqu(Tmp, KeyReg, vector_len); + KeyReg = Tmp; + } + for (int i = 0; i{44, 52, 60} + __ jcc(Assembler::above, NextKeySize); + } + + /********************** LAST KEYS & FIRST AES ITERATION **********************/ + // convert keys to little-endian (into registers and onto stack) + os::snprintf_checked(comments, sizeof(comments), "(%d Rounds) INIT Keys tail", keyRounds); + BLOCK_COMMENT(comments); + int parallel = 2; + // finish rounds for this keysize + keysAndRounds(true, 10, keyRounds, keyRounds, parallel); + + // Increment is now a constant step, 2 Ctrs at a time + __ vpbroadcastq(Increment, 2*blocksPerReg, vector_len, tmp); + + // Before we modify len, compute used and nextCtr + __ movl(tmp, len); + __ incrementl(tmp, 15); + __ shrl(tmp, 4); + __ movl(used, len); + __ andl(used, 0xf); + __ jcc(Assembler::notZero, StoreUsed); + __ movl(used, 16); + __ BIND(StoreUsed); + __ movl(Address(usedAddr, 0), used); + + __ addq(nextCtrLow, tmp); + __ adcq(nextCtrHigh, 0); + __ bswapq(nextCtrLow); + __ bswapq(nextCtrHigh); + __ movq(Address(ctr, 8), nextCtrLow); + __ movq(Address(ctr), nextCtrHigh); + + __ cmpl(len, parallel*blocksPerReg*16); + __ jcc(Assembler::below, LastSet); // Not enough to do a full iteration, break + + BLOCK_COMMENT("XOR Data and Increment Counters for Next iteration"); + xorDataAndIncCtr(parallel); + __ incrementl(pos, parallel*blocksPerReg*16); + __ decrementl(len, parallel*blocksPerReg*16); + __ jcc(Assembler::zero, Scrub); // Exactly on the boundary, exit + + // Another peel of the loop (helps with smaller payloads) + BLOCK_COMMENT("Second peel of the loop"); + keysAndRounds(false, 0, keyRounds, keyRounds, parallel); + __ cmpl(len, parallel*blocksPerReg*16); + __ jcc(Assembler::below, LastSet); // Not enough to do a full iteration, break + xorDataAndIncCtr(parallel); + __ incrementl(pos, parallel*blocksPerReg*16); + __ decrementl(len, parallel*blocksPerReg*16); + __ jcc(Assembler::zero, Scrub); // Exactly on the boundary, exit + + // init remaining Ctrs to switch from parallel = 2 to maxParallel + for (int i = parallel; i < maxParallel; i += 2) { + incCtrPair(i); + } + parallel = maxParallel; + /********************** ENCRYPTION LOOP **********************/ + __ align(OptoLoopAlignment); + __ BIND(EncryptLoop); + + keysAndRounds(false, 0, keyRounds, keyRounds, parallel); + __ cmpl(len, parallel*blocksPerReg*16); + __ jcc(Assembler::below, LastSet); // Not enough to do a full iteration, break + + BLOCK_COMMENT("XOR Data and Increment Counters for Next iteration"); + xorDataAndIncCtr(parallel); + __ incrementl(pos, parallel*blocksPerReg*16); + __ decrementl(len, parallel*blocksPerReg*16); + __ jcc(Assembler::notZero, EncryptLoop); + __ jmp(Scrub); // Exactly on the boundary, exit + + __ bind(NextKeySize); + } + + __ BIND(SingleBlock); // Special-case 16-and-below + __ movdqu(LastCtr, Address(ctr)); + __ movq(nextCtrHigh, Address(ctr)); + __ movq(nextCtrLow, Address(ctr, 8)); + // (KeyShuf overloaded with Increment) + __ movdqu(KeyShuf, ExternalAddress(key_shuffle_mask_addr()), tmp /*rscratch*/); + // storing nextCtr{Low,High} delayed, get to AES faster + + for (int keyRounds = 11; keyRounds <= 15; keyRounds +=2) { // 11, 13, 15 + Label NextKeySize, StoreUsed; + + if (keyRounds != 15) { + __ cmpl(keyLength, 4*keyRounds); // map {11, 13, 15}->{44, 52, 60} + __ jcc(Assembler::above, NextKeySize); + } + + // convert keys to little-endian (into registers and onto stack) + os::snprintf_checked(comments, sizeof(comments), "(%d Rounds) INIT Keys tail", keyRounds); + BLOCK_COMMENT(comments); + XMMRegister KeyReg = Tmp; + for (int round = 0; round < keyRounds; round++) { + __ movdqu(KeyReg, Address(key, round*16)); + __ pshufb(KeyReg, KeyShuf); + __ aesround(LastCtr, KeyReg, round == 0, round == keyRounds - 1, Assembler::AVX_128bit); + } + + __ movl(used, len); + __ andl(used, 0xf); + __ jcc(Assembler::notZero, StoreUsed); + __ movl(used, 16); + __ BIND(StoreUsed); + __ movl(Address(usedAddr, 0), used); + + __ bswapq(nextCtrLow); + __ bswapq(nextCtrHigh); + __ addq(nextCtrLow, 1); + __ adcq(nextCtrHigh, 0); + __ bswapq(nextCtrLow); + __ bswapq(nextCtrHigh); + __ movq(Address(ctr, 8), nextCtrLow); + __ movq(Address(ctr), nextCtrHigh); + + // KeyReg zeroed-out at ExitLabel + + __ cmpl(len, 16); + __ jcc(Assembler::below, LastBlock); + __ vpxor(LastCtr, LastCtr, Address(src, pos, Address::times_1, 0), Assembler::AVX_128bit, Tmp); + __ vmovdqu(Address(dst, pos, Address::times_1, 0), LastCtr, Assembler::AVX_128bit); + __ incrementl(pos, 16); // output + // not decrementing len on purpose + __ jmp(ExitLabel); + __ bind(NextKeySize); + } + + /********************** TAIL ENCRYPTION **********************/ + // Process LastSet of parallel registers + // - End of data somewhere "inside" the register set Ctr[] + // - Move partially used Ctr[i] to LastCtr + // - LastSet ladder is shared by Ctr[2] and Ctr[maxParallel] + // (len check protects parallel=2 from accessing Ctr[2] and Ctr[3]) + __ BIND(LastSet); + for (int i = 0; true; i++) { + __ vmovdqu(LastCtr, Ctr[i], vector_len); + if (i==maxParallel-1) { break; } // last set is always partial + __ cmpl(len, blocksPerReg*16); + __ jcc(Assembler::below, LastReg); + + __ vpxor(Ctr[i], Ctr[i], Address(src, pos, Address::times_1, 0), vector_len, Tmp); + __ vmovdqu(Address(dst, pos, Address::times_1, 0), Ctr[i], vector_len); + __ incrementl(pos, blocksPerReg*16); + __ decrementl(len, blocksPerReg*16); + } + + __ BIND(LastReg); + // Process last 'incomplete' register + if (blocksPerReg == 4) { // Assembler::AVX_512bit + __ cmpl(len, 32); + __ jcc(Assembler::below, Last2Block); + __ vpxor(Tmp, LastCtr, Address(src, pos, Address::times_1, 0), Assembler::AVX_256bit, xnoreg); + __ vmovdqu(Address(dst, pos, Address::times_1, 0), Tmp, Assembler::AVX_256bit); + __ evshufi64x2(LastCtr, LastCtr, LastCtr, 0b00001110, Assembler::AVX_512bit); + __ incrementl(pos, 32); + __ decrementl(len, 32); + } + __ BIND(Last2Block); + if (blocksPerReg >= 2) { // Assembler::AVX_256bit + __ cmpl(len, 16); + __ jcc(Assembler::below, Scrub); + __ vpxor(Tmp, LastCtr, Address(src, pos, Address::times_1, 0), Assembler::AVX_128bit, xnoreg); + __ vmovdqu(Address(dst, pos, Address::times_1, 0), Tmp, Assembler::AVX_128bit); + __ vextractf128(LastCtr, LastCtr, 1); + __ incrementl(pos, 16); + __ decrementl(len, 16); + } + + // Cleanup (here, so SingleBlock can goto LastBlock without this Scrub) + __ BIND(Scrub); + _next = xmm4; // Skip LastCtr and Tmp until ExitLabel + for (int i = 0; i < keyRegs + maxParallel + 1; i++, _next = _next->successor()) { + __ vpxor(_next, _next, _next, Assembler::AVX_128bit); // EVEX clears upper for free + } + for (int slot = 0; slot < totalStackBytes/16; slot++) { + __ movdqu(Address(rsp, 16*slot), xmm4); // xmm4 zeroed already + } + + __ BIND(LastBlock); + __ cmpl(len, 0); + __ jcc(Assembler::equal, ExitLabel); + __ movdqu(Address(savedCtr), LastCtr); + + Register lastCtr = keyLength; + __ pextrq(lastCtr, LastCtr, 0); + __ cmpl(len, 8); + __ jcc(Assembler::below, Last4Byte); + __ xorq(lastCtr, Address(src, pos, Address::times_1, 0)); + __ movq(Address(dst, pos, Address::times_1, 0), lastCtr); + __ pextrq(lastCtr, LastCtr, 1); + __ incrementl(pos, 8); + __ decrementl(len, 8); + + __ BIND(Last4Byte); + __ cmpl(len, 4); + __ jcc(Assembler::below, Last2Byte); + __ movl(tmp, lastCtr); + __ xorl(tmp, Address(src, pos, Address::times_1, 0)); + __ movl(Address(dst, pos, Address::times_1, 0), tmp); + __ shrq(lastCtr, 32); + __ incrementl(pos, 4); + __ decrementl(len, 4); + + __ BIND(Last2Byte); + __ cmpl(len, 2); + __ jcc(Assembler::below, LastByte); + __ movl(tmp, lastCtr); + __ xorw(tmp, Address(src, pos, Address::times_1, 0)); + __ movw(Address(dst, pos, Address::times_1, 0), tmp); + __ shrl(lastCtr, 16); + __ incrementl(pos, 2); + __ decrementl(len, 2); + + __ BIND(LastByte); + __ cmpl(len, 1); + __ jcc(Assembler::below, ExitLabel); + __ xorb(lastCtr, Address(src, pos, Address::times_1, 0)); + __ movb(Address(dst, pos, Address::times_1, 0), lastCtr); + __ incrementl(pos, 1); + + __ BIND(ExitLabel); + __ vpxor(Tmp, Tmp, Tmp, Assembler::AVX_128bit); + __ vpxor(LastCtr, LastCtr, LastCtr, Assembler::AVX_128bit); + __ xorl(lastCtr, lastCtr); + if (vector_len != Assembler::AVX_128bit) { + __ vzeroupper(); + } + + if (totalStackBytes > 0) { + // Restore rsp so pop_ppx can work; value at __ enter() minus push_ppxes +#ifdef _WIN64 + __ lea(rsp, Address(rbp, -5 * wordSize)); +#else + __ lea(rsp, Address(rbp, -3 * wordSize)); +#endif + } + + __ pop_ppx(r14); + __ pop_ppx(r13); + __ pop_ppx(r12); +#ifdef _WIN64 + __ pop_ppx(rdi); + __ pop_ppx(rsi); +#endif + + __ leave(); // required for proper stackwalking of RuntimeStub frame + + __ ret(0); + // record the stub entry and end + stubgen->store_archive_data(stub_id, start, __ pc()); + return start; +} void StubGenerator::generate_aes_stubs() { if (UseAESIntrinsics) { StubRoutines::_aescrypt_encryptBlock = generate_aescrypt_encryptBlock(); StubRoutines::_aescrypt_decryptBlock = generate_aescrypt_decryptBlock(); StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt(); - if (VM_Version::supports_avx512_vaes() && VM_Version::supports_avx512vl() && VM_Version::supports_avx512dq() ) { + if (VM_Version::supports_vaes() && VM_Version::supports_avx512vl() && VM_Version::supports_avx512dq() ) { StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptVectorAESCrypt(); StubRoutines::_electronicCodeBook_encryptAESCrypt = generate_electronicCodeBook_encryptAESCrypt(); StubRoutines::_electronicCodeBook_decryptAESCrypt = generate_electronicCodeBook_decryptAESCrypt(); @@ -227,11 +965,18 @@ void StubGenerator::generate_aes_stubs() { } if (UseAESCTRIntrinsics) { - if (VM_Version::supports_avx512_vaes() && VM_Version::supports_avx512bw() && VM_Version::supports_avx512vl()) { - StubRoutines::_counterMode_AESCrypt = generate_counterMode_VectorAESCrypt(); + int vector_len = Assembler::AVX_128bit; + if (VM_Version::supports_vaes() && VM_Version::supports_avx512bw() && VM_Version::supports_avx512vl()) { + vector_len = Assembler::AVX_512bit; + } else if (VM_Version::supports_vaes() && EnableX86ECoreOpts) { + vector_len = Assembler::AVX_256bit; } else { - StubRoutines::_counterMode_AESCrypt = generate_counterMode_AESCrypt_Parallel(); + assert(VM_Version::supports_aes() && VM_Version::supports_sse4_2(), "AESNI intrinsic unsupported"); } + + int parallel = 4; // experimentally best. Needs to be even, tested 2&4&6 + AESAssembler S(_masm); + StubRoutines::_counterMode_AESCrypt = generate_counterModeAES(this, vector_len, &S, parallel); } } @@ -425,403 +1170,8 @@ address StubGenerator::generate_avx2_galoisCounterMode_AESCrypt() { return start; } -// Vector AES Counter implementation -address StubGenerator::generate_counterMode_VectorAESCrypt() { - StubId stub_id = StubId::stubgen_counterMode_AESCrypt_id; - int entry_count = StubInfo::entry_count(stub_id); - assert(entry_count == 1, "sanity check"); - address start = load_archive_data(stub_id); - if (start != nullptr) { - return start; - } - __ align(CodeEntryAlignment); - StubCodeMark mark(this, stub_id); - start = __ pc(); - - const Register from = c_rarg0; // source array address - const Register to = c_rarg1; // destination array address - const Register key = c_rarg2; // key array address r8 - const Register counter = c_rarg3; // counter byte array initialized from counter array address - // and updated with the incremented counter in the end -#ifndef _WIN64 - const Register len_reg = c_rarg4; - const Register saved_encCounter_start = c_rarg5; - const Register used_addr = r10; - const Address used_mem(rbp, 2 * wordSize); - const Register used = r11; -#else - const Address len_mem(rbp, 6 * wordSize); // length is on stack on Win64 - const Address saved_encCounter_mem(rbp, 7 * wordSize); // saved encrypted counter is on stack on Win64 - const Address used_mem(rbp, 8 * wordSize); // used length is on stack on Win64 - const Register len_reg = r10; // pick the first volatile windows register - const Register saved_encCounter_start = r11; - const Register used_addr = r13; - const Register used = r14; -#endif - __ enter(); - // Save state before entering routine - __ push_ppx(r12); - __ push_ppx(r13); - __ push_ppx(r14); - __ push_ppx(r15); -#ifdef _WIN64 - // on win64, fill len_reg from stack position - __ movl(len_reg, len_mem); - __ movptr(saved_encCounter_start, saved_encCounter_mem); - __ movptr(used_addr, used_mem); - __ movl(used, Address(used_addr, 0)); -#else - __ push_ppx(len_reg); // Save - __ movptr(used_addr, used_mem); - __ movl(used, Address(used_addr, 0)); -#endif - __ push_ppx(rbx); - - aesctr_encrypt(from, to, key, counter, len_reg, used, used_addr, saved_encCounter_start); - - __ vzeroupper(); - // Restore state before leaving routine - __ pop_ppx(rbx); -#ifdef _WIN64 - __ movl(rax, len_mem); // return length -#else - __ pop_ppx(rax); // return length -#endif - __ pop_ppx(r15); - __ pop_ppx(r14); - __ pop_ppx(r13); - __ pop_ppx(r12); - - __ leave(); // required for proper stackwalking of RuntimeStub frame - __ ret(0); - - // record the stub entry and end - store_archive_data(stub_id, start, __ pc()); - - return start; -} - -// This is a version of CTR/AES crypt which does 6 blocks in a loop at a time -// to hide instruction latency -// -// Arguments: -// -// Inputs: -// c_rarg0 - source byte array address -// c_rarg1 - destination byte array address -// c_rarg2 - sessionKe (key) in little endian int array -// c_rarg3 - counter vector byte array address -// Linux -// c_rarg4 - input length -// c_rarg5 - saved encryptedCounter start -// rbp + 6 * wordSize - saved used length -// Windows -// rbp + 6 * wordSize - input length -// rbp + 7 * wordSize - saved encryptedCounter start -// rbp + 8 * wordSize - saved used length -// -// Output: -// rax - input length -// -address StubGenerator::generate_counterMode_AESCrypt_Parallel() { - assert(UseAES, "need AES instructions and misaligned SSE support"); - StubId stub_id = StubId::stubgen_counterMode_AESCrypt_id; - int entry_count = StubInfo::entry_count(stub_id); - assert(entry_count == 1, "sanity check"); - address start = load_archive_data(stub_id); - if (start != nullptr) { - return start; - } - __ align(CodeEntryAlignment); - StubCodeMark mark(this, stub_id); - start = __ pc(); - - const Register from = c_rarg0; // source array address - const Register to = c_rarg1; // destination array address - const Register key = c_rarg2; // key array address - const Register counter = c_rarg3; // counter byte array initialized from counter array address - // and updated with the incremented counter in the end -#ifndef _WIN64 - const Register len_reg = c_rarg4; - const Register saved_encCounter_start = c_rarg5; - const Register used_addr = r10; - const Address used_mem(rbp, 2 * wordSize); - const Register used = r11; -#else - const Address len_mem(rbp, 6 * wordSize); // length is on stack on Win64 - const Address saved_encCounter_mem(rbp, 7 * wordSize); // length is on stack on Win64 - const Address used_mem(rbp, 8 * wordSize); // length is on stack on Win64 - const Register len_reg = r10; // pick the first volatile windows register - const Register saved_encCounter_start = r11; - const Register used_addr = r13; - const Register used = r14; -#endif - const Register pos = rax; - - const int PARALLEL_FACTOR = 6; - const XMMRegister xmm_counter_shuf_mask = xmm0; - const XMMRegister xmm_key_shuf_mask = xmm1; // used temporarily to swap key bytes up front - const XMMRegister xmm_curr_counter = xmm2; - - const XMMRegister xmm_key_tmp0 = xmm3; - const XMMRegister xmm_key_tmp1 = xmm4; - - // registers holding the four results in the parallelized loop - const XMMRegister xmm_result0 = xmm5; - const XMMRegister xmm_result1 = xmm6; - const XMMRegister xmm_result2 = xmm7; - const XMMRegister xmm_result3 = xmm8; - const XMMRegister xmm_result4 = xmm9; - const XMMRegister xmm_result5 = xmm10; - - const XMMRegister xmm_from0 = xmm11; - const XMMRegister xmm_from1 = xmm12; - const XMMRegister xmm_from2 = xmm13; - const XMMRegister xmm_from3 = xmm14; //the last one is xmm14. we have to preserve it on WIN64. - const XMMRegister xmm_from4 = xmm3; //reuse xmm3~4. Because xmm_key_tmp0~1 are useless when loading input text - const XMMRegister xmm_from5 = xmm4; - - //for key_128, key_192, key_256 - const int rounds[3] = {10, 12, 14}; - Label L_exit_preLoop, L_preLoop_start; - Label L_multiBlock_loopTop[3]; - Label L_singleBlockLoopTop[3]; - Label L__incCounter[3][6]; //for 6 blocks - Label L__incCounter_single[3]; //for single block, key128, key192, key256 - Label L_processTail_insr[3], L_processTail_4_insr[3], L_processTail_2_insr[3], L_processTail_1_insr[3], L_processTail_exit_insr[3]; - Label L_processTail_4_extr[3], L_processTail_2_extr[3], L_processTail_1_extr[3], L_processTail_exit_extr[3]; - - Label L_exit; - - __ enter(); // required for proper stackwalking of RuntimeStub frame - -#ifdef _WIN64 - // allocate spill slots for r13, r14 - enum { - saved_r13_offset, - saved_r14_offset - }; - __ subptr(rsp, 2 * wordSize); - __ movptr(Address(rsp, saved_r13_offset * wordSize), r13); - __ movptr(Address(rsp, saved_r14_offset * wordSize), r14); - - // on win64, fill len_reg from stack position - __ movl(len_reg, len_mem); - __ movptr(saved_encCounter_start, saved_encCounter_mem); - __ movptr(used_addr, used_mem); - __ movl(used, Address(used_addr, 0)); -#else - __ push_ppx(len_reg); // Save - __ movptr(used_addr, used_mem); - __ movl(used, Address(used_addr, 0)); -#endif - - __ push_ppx(rbx); // Save RBX - __ movdqu(xmm_curr_counter, Address(counter, 0x00)); // initialize counter with initial counter - __ movdqu(xmm_counter_shuf_mask, ExternalAddress(counter_shuffle_mask_addr()), pos /*rscratch*/); - __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled - __ movptr(pos, 0); - - // Use the partially used encrpyted counter from last invocation - __ BIND(L_preLoop_start); - __ cmpptr(used, 16); - __ jcc(Assembler::aboveEqual, L_exit_preLoop); - __ cmpptr(len_reg, 0); - __ jcc(Assembler::lessEqual, L_exit_preLoop); - __ movb(rbx, Address(saved_encCounter_start, used)); - __ xorb(rbx, Address(from, pos)); - __ movb(Address(to, pos), rbx); - __ addptr(pos, 1); - __ addptr(used, 1); - __ subptr(len_reg, 1); - - __ jmp(L_preLoop_start); - - __ BIND(L_exit_preLoop); - __ movl(Address(used_addr, 0), used); - - // key length could be only {11, 13, 15} * 4 = {44, 52, 60} - __ movdqu(xmm_key_shuf_mask, ExternalAddress(key_shuffle_mask_addr()), rbx /*rscratch*/); - __ movl(rbx, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT))); - __ cmpl(rbx, 52); - __ jcc(Assembler::equal, L_multiBlock_loopTop[1]); - __ cmpl(rbx, 60); - __ jcc(Assembler::equal, L_multiBlock_loopTop[2]); - -#define CTR_DoSix(opc, src_reg) \ - __ opc(xmm_result0, src_reg); \ - __ opc(xmm_result1, src_reg); \ - __ opc(xmm_result2, src_reg); \ - __ opc(xmm_result3, src_reg); \ - __ opc(xmm_result4, src_reg); \ - __ opc(xmm_result5, src_reg); - - // k == 0 : generate code for key_128 - // k == 1 : generate code for key_192 - // k == 2 : generate code for key_256 - for (int k = 0; k < 3; ++k) { - //multi blocks starts here - __ align(OptoLoopAlignment); - __ BIND(L_multiBlock_loopTop[k]); - __ cmpptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // see if at least PARALLEL_FACTOR blocks left - __ jcc(Assembler::less, L_singleBlockLoopTop[k]); - load_key(xmm_key_tmp0, key, 0x00, xmm_key_shuf_mask); - - //load, then increase counters - CTR_DoSix(movdqa, xmm_curr_counter); - inc_counter(rbx, xmm_result1, 0x01, L__incCounter[k][0]); - inc_counter(rbx, xmm_result2, 0x02, L__incCounter[k][1]); - inc_counter(rbx, xmm_result3, 0x03, L__incCounter[k][2]); - inc_counter(rbx, xmm_result4, 0x04, L__incCounter[k][3]); - inc_counter(rbx, xmm_result5, 0x05, L__incCounter[k][4]); - inc_counter(rbx, xmm_curr_counter, 0x06, L__incCounter[k][5]); - CTR_DoSix(pshufb, xmm_counter_shuf_mask); // after increased, shuffled counters back for PXOR - CTR_DoSix(pxor, xmm_key_tmp0); //PXOR with Round 0 key - - //load two ROUND_KEYs at a time - for (int i = 1; i < rounds[k]; ) { - load_key(xmm_key_tmp1, key, (0x10 * i), xmm_key_shuf_mask); - load_key(xmm_key_tmp0, key, (0x10 * (i+1)), xmm_key_shuf_mask); - CTR_DoSix(aesenc, xmm_key_tmp1); - i++; - if (i != rounds[k]) { - CTR_DoSix(aesenc, xmm_key_tmp0); - } else { - CTR_DoSix(aesenclast, xmm_key_tmp0); - } - i++; - } - - // get next PARALLEL_FACTOR blocks into xmm_result registers - __ movdqu(xmm_from0, Address(from, pos, Address::times_1, 0 * AESBlockSize)); - __ movdqu(xmm_from1, Address(from, pos, Address::times_1, 1 * AESBlockSize)); - __ movdqu(xmm_from2, Address(from, pos, Address::times_1, 2 * AESBlockSize)); - __ movdqu(xmm_from3, Address(from, pos, Address::times_1, 3 * AESBlockSize)); - __ movdqu(xmm_from4, Address(from, pos, Address::times_1, 4 * AESBlockSize)); - __ movdqu(xmm_from5, Address(from, pos, Address::times_1, 5 * AESBlockSize)); - - __ pxor(xmm_result0, xmm_from0); - __ pxor(xmm_result1, xmm_from1); - __ pxor(xmm_result2, xmm_from2); - __ pxor(xmm_result3, xmm_from3); - __ pxor(xmm_result4, xmm_from4); - __ pxor(xmm_result5, xmm_from5); - - // store 6 results into the next 64 bytes of output - __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0); - __ movdqu(Address(to, pos, Address::times_1, 1 * AESBlockSize), xmm_result1); - __ movdqu(Address(to, pos, Address::times_1, 2 * AESBlockSize), xmm_result2); - __ movdqu(Address(to, pos, Address::times_1, 3 * AESBlockSize), xmm_result3); - __ movdqu(Address(to, pos, Address::times_1, 4 * AESBlockSize), xmm_result4); - __ movdqu(Address(to, pos, Address::times_1, 5 * AESBlockSize), xmm_result5); - - __ addptr(pos, PARALLEL_FACTOR * AESBlockSize); // increase the length of crypt text - __ subptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // decrease the remaining length - __ jmp(L_multiBlock_loopTop[k]); - - // singleBlock starts here - __ align(OptoLoopAlignment); - __ BIND(L_singleBlockLoopTop[k]); - __ cmpptr(len_reg, 0); - __ jcc(Assembler::lessEqual, L_exit); - load_key(xmm_key_tmp0, key, 0x00, xmm_key_shuf_mask); - __ movdqa(xmm_result0, xmm_curr_counter); - inc_counter(rbx, xmm_curr_counter, 0x01, L__incCounter_single[k]); - __ pshufb(xmm_result0, xmm_counter_shuf_mask); - __ pxor(xmm_result0, xmm_key_tmp0); - for (int i = 1; i < rounds[k]; i++) { - load_key(xmm_key_tmp0, key, (0x10 * i), xmm_key_shuf_mask); - __ aesenc(xmm_result0, xmm_key_tmp0); - } - load_key(xmm_key_tmp0, key, (rounds[k] * 0x10), xmm_key_shuf_mask); - __ aesenclast(xmm_result0, xmm_key_tmp0); - __ cmpptr(len_reg, AESBlockSize); - __ jcc(Assembler::less, L_processTail_insr[k]); - __ movdqu(xmm_from0, Address(from, pos, Address::times_1, 0 * AESBlockSize)); - __ pxor(xmm_result0, xmm_from0); - __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0); - __ addptr(pos, AESBlockSize); - __ subptr(len_reg, AESBlockSize); - __ jmp(L_singleBlockLoopTop[k]); - __ BIND(L_processTail_insr[k]); // Process the tail part of the input array - __ addptr(pos, len_reg); // 1. Insert bytes from src array into xmm_from0 register - __ testptr(len_reg, 8); - __ jcc(Assembler::zero, L_processTail_4_insr[k]); - __ subptr(pos,8); - __ pinsrq(xmm_from0, Address(from, pos), 0); - __ BIND(L_processTail_4_insr[k]); - __ testptr(len_reg, 4); - __ jcc(Assembler::zero, L_processTail_2_insr[k]); - __ subptr(pos,4); - __ pslldq(xmm_from0, 4); - __ pinsrd(xmm_from0, Address(from, pos), 0); - __ BIND(L_processTail_2_insr[k]); - __ testptr(len_reg, 2); - __ jcc(Assembler::zero, L_processTail_1_insr[k]); - __ subptr(pos, 2); - __ pslldq(xmm_from0, 2); - __ pinsrw(xmm_from0, Address(from, pos), 0); - __ BIND(L_processTail_1_insr[k]); - __ testptr(len_reg, 1); - __ jcc(Assembler::zero, L_processTail_exit_insr[k]); - __ subptr(pos, 1); - __ pslldq(xmm_from0, 1); - __ pinsrb(xmm_from0, Address(from, pos), 0); - __ BIND(L_processTail_exit_insr[k]); - - __ movdqu(Address(saved_encCounter_start, 0), xmm_result0); // 2. Perform pxor of the encrypted counter and plaintext Bytes. - __ pxor(xmm_result0, xmm_from0); // Also the encrypted counter is saved for next invocation. - - __ testptr(len_reg, 8); - __ jcc(Assembler::zero, L_processTail_4_extr[k]); // 3. Extract bytes from xmm_result0 into the dest. array - __ pextrq(Address(to, pos), xmm_result0, 0); - __ psrldq(xmm_result0, 8); - __ addptr(pos, 8); - __ BIND(L_processTail_4_extr[k]); - __ testptr(len_reg, 4); - __ jcc(Assembler::zero, L_processTail_2_extr[k]); - __ pextrd(Address(to, pos), xmm_result0, 0); - __ psrldq(xmm_result0, 4); - __ addptr(pos, 4); - __ BIND(L_processTail_2_extr[k]); - __ testptr(len_reg, 2); - __ jcc(Assembler::zero, L_processTail_1_extr[k]); - __ pextrw(Address(to, pos), xmm_result0, 0); - __ psrldq(xmm_result0, 2); - __ addptr(pos, 2); - __ BIND(L_processTail_1_extr[k]); - __ testptr(len_reg, 1); - __ jcc(Assembler::zero, L_processTail_exit_extr[k]); - __ pextrb(Address(to, pos), xmm_result0, 0); - - __ BIND(L_processTail_exit_extr[k]); - __ movl(Address(used_addr, 0), len_reg); - __ jmp(L_exit); - } - - __ BIND(L_exit); - __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled back. - __ movdqu(Address(counter, 0), xmm_curr_counter); //save counter back - __ pop_ppx(rbx); // pop the saved RBX. -#ifdef _WIN64 - __ movl(rax, len_mem); - __ movptr(r13, Address(rsp, saved_r13_offset * wordSize)); - __ movptr(r14, Address(rsp, saved_r14_offset * wordSize)); - __ addptr(rsp, 2 * wordSize); -#else - __ pop_ppx(rax); // return 'len' -#endif - __ leave(); // required for proper stackwalking of RuntimeStub frame - __ ret(0); - - // record the stub entry and end - store_archive_data(stub_id, start, __ pc()); - - return start; -} - address StubGenerator::generate_cipherBlockChaining_decryptVectorAESCrypt() { - assert(VM_Version::supports_avx512_vaes(), "need AES instructions and misaligned SSE support"); + assert(VM_Version::supports_vaes(), "need AES instructions and misaligned SSE support"); StubId stub_id = StubId::stubgen_cipherBlockChaining_decryptAESCrypt_id; int entry_count = StubInfo::entry_count(stub_id); assert(entry_count == 1, "sanity check"); @@ -2002,19 +2352,6 @@ address StubGenerator::generate_electronicCodeBook_decryptAESCrypt() { return start; } -// Utility routine for increase 128bit counter (iv in CTR mode) -void StubGenerator::inc_counter(Register reg, XMMRegister xmmdst, int inc_delta, Label& next_block) { - __ pextrq(reg, xmmdst, 0x0); - __ addq(reg, inc_delta); - __ pinsrq(xmmdst, reg, 0x0); - __ jcc(Assembler::carryClear, next_block); // jump if no carry - __ pextrq(reg, xmmdst, 0x01); // Carry - __ addq(reg, 0x01); - __ pinsrq(xmmdst, reg, 0x01); //Carry end - __ BIND(next_block); // next instruction -} - - void StubGenerator::roundEnc(XMMRegister key, int rnum) { for (int xmm_reg_no = 0; xmm_reg_no <=rnum; xmm_reg_no++) { __ vaesenc(as_XMMRegister(xmm_reg_no), as_XMMRegister(xmm_reg_no), key, Assembler::AVX_512bit); @@ -2103,18 +2440,6 @@ void StubGenerator::ev_load_key(XMMRegister xmmdst, Register key, int offset, Re __ evshufi64x2(xmmdst, xmmdst, xmmdst, 0x0, Assembler::AVX_512bit); } -// Add 128-bit integers in xmmsrc1 to xmmsrc2, then place the result in xmmdst. -// Clobber ktmp and rscratch. -// Used by aesctr_encrypt. -void StubGenerator::ev_add128(XMMRegister xmmdst, XMMRegister xmmsrc1, XMMRegister xmmsrc2, - int vector_len, KRegister ktmp, XMMRegister ones) { - __ vpaddq(xmmdst, xmmsrc1, xmmsrc2, vector_len); - __ evpcmpuq(ktmp, xmmdst, xmmsrc2, __ lt, vector_len); // set mask[0/1] bit if addq to dst[0/1] wraps - __ kshiftlbl(ktmp, ktmp, 1); // mask[1] <- mask[0], mask[0] <- 0, etc - - __ evpaddq(xmmdst, ktmp, xmmdst, ones, /*merge*/true, vector_len); // dst[1]++ if mask[1] set -} - // AES-ECB Encrypt Operation void StubGenerator::aesecb_encrypt(Register src_addr, Register dest_addr, Register key, Register len) { const Register pos = rax; @@ -2536,514 +2861,6 @@ void StubGenerator::aesecb_decrypt(Register src_addr, Register dest_addr, Regist __ pop_ppx(r13); } - -// AES Counter Mode using VAES instructions -void StubGenerator::aesctr_encrypt(Register src_addr, Register dest_addr, Register key, Register counter, - Register len_reg, Register used, Register used_addr, Register saved_encCounter_start) { - - const Register rounds = rax; - const Register pos = r12; - const Register tail = r15; - - Label PRELOOP_START, EXIT_PRELOOP, REMAINDER, REMAINDER_16, LOOP, END, EXIT, END_LOOP, - AES192, AES256, AES192_REMAINDER16, REMAINDER16_END_LOOP, AES256_REMAINDER16, - REMAINDER_8, REMAINDER_4, AES192_REMAINDER8, REMAINDER_LOOP, AES256_REMINDER, - AES192_REMAINDER, END_REMAINDER_LOOP, AES256_REMAINDER8, REMAINDER8_END_LOOP, - AES192_REMAINDER4, AES256_REMAINDER4, AES256_REMAINDER, END_REMAINDER4, EXTRACT_TAILBYTES, - EXTRACT_TAIL_4BYTES, EXTRACT_TAIL_2BYTES, EXTRACT_TAIL_1BYTE, STORE_CTR; - - __ cmpl(len_reg, 0); - __ jcc(Assembler::belowEqual, EXIT); - - __ movl(pos, 0); - // if the number of used encrypted counter bytes < 16, - // XOR PT with saved encrypted counter to obtain CT - __ bind(PRELOOP_START); - __ cmpl(used, 16); - __ jcc(Assembler::aboveEqual, EXIT_PRELOOP); - __ movb(rbx, Address(saved_encCounter_start, used)); - __ xorb(rbx, Address(src_addr, pos)); - __ movb(Address(dest_addr, pos), rbx); - __ addptr(pos, 1); - __ addptr(used, 1); - __ decrement(len_reg); - __ jcc(Assembler::notEqual, PRELOOP_START); - - __ bind(EXIT_PRELOOP); - __ movl(Address(used_addr, 0), used); - - __ cmpl(len_reg, 0); - __ jcc(Assembler::equal, EXIT); - - // Calculate number of rounds i.e. 10, 12, 14, based on key length(128, 192, 256). - __ movl(rounds, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT))); - - __ vpxor(xmm0, xmm0, xmm0, Assembler::AVX_128bit); - // Move initial counter value in xmm0 - __ movdqu(xmm0, Address(counter, 0)); - // broadcast counter value to zmm8 - __ evshufi64x2(xmm8, xmm0, xmm0, 0, Assembler::AVX_512bit); - - // load lbswap mask - __ evmovdquq(xmm16, ExternalAddress(counter_shuffle_mask_addr()), Assembler::AVX_512bit, r15 /*rscratch*/); - - //shuffle counter using lbswap_mask - __ vpshufb(xmm8, xmm8, xmm16, Assembler::AVX_512bit); - - // pre-increment and propagate counter values to zmm9-zmm15 registers. - // Linc0 increments the zmm8 by 1 (initial value being 0), Linc4 increments the counters zmm9-zmm15 by 4 - // The counter is incremented after each block i.e. 16 bytes is processed; - // each zmm register has 4 counter values as its MSB - // the counters are incremented in parallel - - const XMMRegister ones = xmm17; - // Vector value to propagate carries - __ evmovdquq(ones, ExternalAddress(counter_mask_ones_addr()), Assembler::AVX_512bit, r15); - - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc0_addr()), Assembler::AVX_512bit, r15 /*rscratch*/); - ev_add128(xmm8, xmm8, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc4_addr()), Assembler::AVX_512bit, r15 /*rscratch*/); - ev_add128(xmm9, xmm8, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - ev_add128(xmm10, xmm9, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - ev_add128(xmm11, xmm10, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - ev_add128(xmm12, xmm11, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - ev_add128(xmm13, xmm12, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - ev_add128(xmm14, xmm13, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - ev_add128(xmm15, xmm14, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - - // load linc32 mask in zmm register.linc32 increments counter by 32 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc32_addr()), Assembler::AVX_512bit, r15 /*rscratch*/); - - // xmm31 contains the key shuffle mask. - __ movdqu(xmm31, ExternalAddress(key_shuffle_mask_addr()), r15 /*rscratch*/); - // Load key function loads 128 bit key and shuffles it. Then we broadcast the shuffled key to convert it into a 512 bit value. - // For broadcasting the values to ZMM, vshufi64 is used instead of evbroadcasti64x2 as the source in this case is ZMM register - // that holds shuffled key value. - ev_load_key(xmm20, key, 0, xmm31); - ev_load_key(xmm21, key, 1 * 16, xmm31); - ev_load_key(xmm22, key, 2 * 16, xmm31); - ev_load_key(xmm23, key, 3 * 16, xmm31); - ev_load_key(xmm24, key, 4 * 16, xmm31); - ev_load_key(xmm25, key, 5 * 16, xmm31); - ev_load_key(xmm26, key, 6 * 16, xmm31); - ev_load_key(xmm27, key, 7 * 16, xmm31); - ev_load_key(xmm28, key, 8 * 16, xmm31); - ev_load_key(xmm29, key, 9 * 16, xmm31); - ev_load_key(xmm30, key, 10 * 16, xmm31); - - // Process 32 blocks or 512 bytes of data - __ bind(LOOP); - __ cmpl(len_reg, 512); - __ jcc(Assembler::less, REMAINDER); - __ subq(len_reg, 512); - //Shuffle counter and Exor it with roundkey1. Result is stored in zmm0-7 - __ vpshufb(xmm0, xmm8, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm0, xmm0, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm1, xmm9, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm1, xmm1, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm2, xmm10, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm2, xmm2, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm3, xmm11, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm3, xmm3, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm4, xmm12, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm4, xmm4, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm5, xmm13, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm5, xmm5, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm6, xmm14, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm6, xmm6, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm7, xmm15, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm7, xmm7, xmm20, Assembler::AVX_512bit); - // Perform AES encode operations and put results in zmm0-zmm7. - // This is followed by incrementing counter values in zmm8-zmm15. - // Since we will be processing 32 blocks at a time, the counter is incremented by 32. - roundEnc(xmm21, 7); - ev_add128(xmm8, xmm8, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm22, 7); - ev_add128(xmm9, xmm9, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm23, 7); - ev_add128(xmm10, xmm10, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm24, 7); - ev_add128(xmm11, xmm11, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm25, 7); - ev_add128(xmm12, xmm12, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm26, 7); - ev_add128(xmm13, xmm13, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm27, 7); - ev_add128(xmm14, xmm14, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm28, 7); - ev_add128(xmm15, xmm15, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - roundEnc(xmm29, 7); - - __ cmpl(rounds, 52); - __ jcc(Assembler::aboveEqual, AES192); - lastroundEnc(xmm30, 7); - __ jmp(END_LOOP); - - __ bind(AES192); - roundEnc(xmm30, 7); - ev_load_key(xmm18, key, 11 * 16, xmm31); - roundEnc(xmm18, 7); - __ cmpl(rounds, 60); - __ jcc(Assembler::aboveEqual, AES256); - ev_load_key(xmm18, key, 12 * 16, xmm31); - lastroundEnc(xmm18, 7); - __ jmp(END_LOOP); - - __ bind(AES256); - ev_load_key(xmm18, key, 12 * 16, xmm31); - roundEnc(xmm18, 7); - ev_load_key(xmm18, key, 13 * 16, xmm31); - roundEnc(xmm18, 7); - ev_load_key(xmm18, key, 14 * 16, xmm31); - lastroundEnc(xmm18, 7); - - // After AES encode rounds, the encrypted block cipher lies in zmm0-zmm7 - // xor encrypted block cipher and input plaintext and store resultant ciphertext - __ bind(END_LOOP); - __ evpxorq(xmm0, xmm0, Address(src_addr, pos, Address::times_1, 0 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 0), xmm0, Assembler::AVX_512bit); - __ evpxorq(xmm1, xmm1, Address(src_addr, pos, Address::times_1, 1 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 64), xmm1, Assembler::AVX_512bit); - __ evpxorq(xmm2, xmm2, Address(src_addr, pos, Address::times_1, 2 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 2 * 64), xmm2, Assembler::AVX_512bit); - __ evpxorq(xmm3, xmm3, Address(src_addr, pos, Address::times_1, 3 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 3 * 64), xmm3, Assembler::AVX_512bit); - __ evpxorq(xmm4, xmm4, Address(src_addr, pos, Address::times_1, 4 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 4 * 64), xmm4, Assembler::AVX_512bit); - __ evpxorq(xmm5, xmm5, Address(src_addr, pos, Address::times_1, 5 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 5 * 64), xmm5, Assembler::AVX_512bit); - __ evpxorq(xmm6, xmm6, Address(src_addr, pos, Address::times_1, 6 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 6 * 64), xmm6, Assembler::AVX_512bit); - __ evpxorq(xmm7, xmm7, Address(src_addr, pos, Address::times_1, 7 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 7 * 64), xmm7, Assembler::AVX_512bit); - __ addq(pos, 512); - __ jmp(LOOP); - - // Encode 256, 128, 64 or 16 bytes at a time if length is less than 512 bytes - __ bind(REMAINDER); - __ cmpl(len_reg, 0); - __ jcc(Assembler::equal, END); - __ cmpl(len_reg, 256); - __ jcc(Assembler::aboveEqual, REMAINDER_16); - __ cmpl(len_reg, 128); - __ jcc(Assembler::aboveEqual, REMAINDER_8); - __ cmpl(len_reg, 64); - __ jcc(Assembler::aboveEqual, REMAINDER_4); - // At this point, we will process 16 bytes of data at a time. - // So load xmm19 with counter increment value as 1 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc1_addr()), Assembler::AVX_128bit, r15 /*rscratch*/); - __ jmp(REMAINDER_LOOP); - - // Each ZMM register can be used to encode 64 bytes of data, so we have 4 ZMM registers to encode 256 bytes of data - __ bind(REMAINDER_16); - __ subq(len_reg, 256); - // As we process 16 blocks at a time, load mask for incrementing the counter value by 16 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc16_addr()), Assembler::AVX_512bit, r15 /*rscratch*/); - // shuffle counter and XOR counter with roundkey1 - __ vpshufb(xmm0, xmm8, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm0, xmm0, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm1, xmm9, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm1, xmm1, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm2, xmm10, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm2, xmm2, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm3, xmm11, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm3, xmm3, xmm20, Assembler::AVX_512bit); - // Increment counter values by 16 - ev_add128(xmm8, xmm8, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - ev_add128(xmm9, xmm9, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - // AES encode rounds - roundEnc(xmm21, 3); - roundEnc(xmm22, 3); - roundEnc(xmm23, 3); - roundEnc(xmm24, 3); - roundEnc(xmm25, 3); - roundEnc(xmm26, 3); - roundEnc(xmm27, 3); - roundEnc(xmm28, 3); - roundEnc(xmm29, 3); - - __ cmpl(rounds, 52); - __ jcc(Assembler::aboveEqual, AES192_REMAINDER16); - lastroundEnc(xmm30, 3); - __ jmp(REMAINDER16_END_LOOP); - - __ bind(AES192_REMAINDER16); - roundEnc(xmm30, 3); - ev_load_key(xmm18, key, 11 * 16, xmm31); - roundEnc(xmm18, 3); - ev_load_key(xmm5, key, 12 * 16, xmm31); - - __ cmpl(rounds, 60); - __ jcc(Assembler::aboveEqual, AES256_REMAINDER16); - lastroundEnc(xmm5, 3); - __ jmp(REMAINDER16_END_LOOP); - __ bind(AES256_REMAINDER16); - roundEnc(xmm5, 3); - ev_load_key(xmm6, key, 13 * 16, xmm31); - roundEnc(xmm6, 3); - ev_load_key(xmm7, key, 14 * 16, xmm31); - lastroundEnc(xmm7, 3); - - // After AES encode rounds, the encrypted block cipher lies in zmm0-zmm3 - // xor 256 bytes of PT with the encrypted counters to produce CT. - __ bind(REMAINDER16_END_LOOP); - __ evpxorq(xmm0, xmm0, Address(src_addr, pos, Address::times_1, 0), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 0), xmm0, Assembler::AVX_512bit); - __ evpxorq(xmm1, xmm1, Address(src_addr, pos, Address::times_1, 1 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 1 * 64), xmm1, Assembler::AVX_512bit); - __ evpxorq(xmm2, xmm2, Address(src_addr, pos, Address::times_1, 2 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 2 * 64), xmm2, Assembler::AVX_512bit); - __ evpxorq(xmm3, xmm3, Address(src_addr, pos, Address::times_1, 3 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 3 * 64), xmm3, Assembler::AVX_512bit); - __ addq(pos, 256); - - __ cmpl(len_reg, 128); - __ jcc(Assembler::aboveEqual, REMAINDER_8); - - __ cmpl(len_reg, 64); - __ jcc(Assembler::aboveEqual, REMAINDER_4); - //load mask for incrementing the counter value by 1 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc1_addr()), Assembler::AVX_128bit, r15 /*rscratch*/); - __ jmp(REMAINDER_LOOP); - - // Each ZMM register can be used to encode 64 bytes of data, so we have 2 ZMM registers to encode 128 bytes of data - __ bind(REMAINDER_8); - __ subq(len_reg, 128); - // As we process 8 blocks at a time, load mask for incrementing the counter value by 8 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc8_addr()), Assembler::AVX_512bit, r15 /*rscratch*/); - // shuffle counters and xor with roundkey1 - __ vpshufb(xmm0, xmm8, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm0, xmm0, xmm20, Assembler::AVX_512bit); - __ vpshufb(xmm1, xmm9, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm1, xmm1, xmm20, Assembler::AVX_512bit); - // increment counter by 8 - ev_add128(xmm8, xmm8, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - // AES encode - roundEnc(xmm21, 1); - roundEnc(xmm22, 1); - roundEnc(xmm23, 1); - roundEnc(xmm24, 1); - roundEnc(xmm25, 1); - roundEnc(xmm26, 1); - roundEnc(xmm27, 1); - roundEnc(xmm28, 1); - roundEnc(xmm29, 1); - - __ cmpl(rounds, 52); - __ jcc(Assembler::aboveEqual, AES192_REMAINDER8); - lastroundEnc(xmm30, 1); - __ jmp(REMAINDER8_END_LOOP); - - __ bind(AES192_REMAINDER8); - roundEnc(xmm30, 1); - ev_load_key(xmm18, key, 11 * 16, xmm31); - roundEnc(xmm18, 1); - ev_load_key(xmm5, key, 12 * 16, xmm31); - __ cmpl(rounds, 60); - __ jcc(Assembler::aboveEqual, AES256_REMAINDER8); - lastroundEnc(xmm5, 1); - __ jmp(REMAINDER8_END_LOOP); - - __ bind(AES256_REMAINDER8); - roundEnc(xmm5, 1); - ev_load_key(xmm6, key, 13 * 16, xmm31); - roundEnc(xmm6, 1); - ev_load_key(xmm7, key, 14 * 16, xmm31); - lastroundEnc(xmm7, 1); - - __ bind(REMAINDER8_END_LOOP); - // After AES encode rounds, the encrypted block cipher lies in zmm0-zmm1 - // XOR PT with the encrypted counter and store as CT - __ evpxorq(xmm0, xmm0, Address(src_addr, pos, Address::times_1, 0 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 0 * 64), xmm0, Assembler::AVX_512bit); - __ evpxorq(xmm1, xmm1, Address(src_addr, pos, Address::times_1, 1 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 1 * 64), xmm1, Assembler::AVX_512bit); - __ addq(pos, 128); - - __ cmpl(len_reg, 64); - __ jcc(Assembler::aboveEqual, REMAINDER_4); - // load mask for incrementing the counter value by 1 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc1_addr()), Assembler::AVX_128bit, r15 /*rscratch*/); - __ jmp(REMAINDER_LOOP); - - // Each ZMM register can be used to encode 64 bytes of data, so we have 1 ZMM register used in this block of code - __ bind(REMAINDER_4); - __ subq(len_reg, 64); - // As we process 4 blocks at a time, load mask for incrementing the counter value by 4 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc4_addr()), Assembler::AVX_512bit, r15 /*rscratch*/); - // XOR counter with first roundkey - __ vpshufb(xmm0, xmm8, xmm16, Assembler::AVX_512bit); - __ evpxorq(xmm0, xmm0, xmm20, Assembler::AVX_512bit); - - // Increment counter - ev_add128(xmm8, xmm8, xmm19, Assembler::AVX_512bit, /*ktmp*/k1, ones); - __ vaesenc(xmm0, xmm0, xmm21, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm22, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm23, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm24, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm25, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm26, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm27, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm28, Assembler::AVX_512bit); - __ vaesenc(xmm0, xmm0, xmm29, Assembler::AVX_512bit); - __ cmpl(rounds, 52); - __ jcc(Assembler::aboveEqual, AES192_REMAINDER4); - __ vaesenclast(xmm0, xmm0, xmm30, Assembler::AVX_512bit); - __ jmp(END_REMAINDER4); - - __ bind(AES192_REMAINDER4); - __ vaesenc(xmm0, xmm0, xmm30, Assembler::AVX_512bit); - ev_load_key(xmm18, key, 11 * 16, xmm31); - __ vaesenc(xmm0, xmm0, xmm18, Assembler::AVX_512bit); - ev_load_key(xmm5, key, 12 * 16, xmm31); - - __ cmpl(rounds, 60); - __ jcc(Assembler::aboveEqual, AES256_REMAINDER4); - __ vaesenclast(xmm0, xmm0, xmm5, Assembler::AVX_512bit); - __ jmp(END_REMAINDER4); - - __ bind(AES256_REMAINDER4); - __ vaesenc(xmm0, xmm0, xmm5, Assembler::AVX_512bit); - ev_load_key(xmm6, key, 13 * 16, xmm31); - __ vaesenc(xmm0, xmm0, xmm6, Assembler::AVX_512bit); - ev_load_key(xmm7, key, 14 * 16, xmm31); - __ vaesenclast(xmm0, xmm0, xmm7, Assembler::AVX_512bit); - // After AES encode rounds, the encrypted block cipher lies in zmm0. - // XOR encrypted block cipher with PT and store 64 bytes of ciphertext - __ bind(END_REMAINDER4); - __ evpxorq(xmm0, xmm0, Address(src_addr, pos, Address::times_1, 0 * 64), Assembler::AVX_512bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 0), xmm0, Assembler::AVX_512bit); - __ addq(pos, 64); - // load mask for incrementing the counter value by 1 - __ evmovdquq(xmm19, ExternalAddress(counter_mask_linc1_addr()), Assembler::AVX_128bit, r15 /*rscratch*/); - - // For a single block, the AES rounds start here. - __ bind(REMAINDER_LOOP); - __ cmpl(len_reg, 0); - __ jcc(Assembler::belowEqual, END); - // XOR counter with first roundkey - __ vpshufb(xmm0, xmm8, xmm16, Assembler::AVX_128bit); - __ evpxorq(xmm0, xmm0, xmm20, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm21, Assembler::AVX_128bit); - // Increment counter by 1 - ev_add128(xmm8, xmm8, xmm19, Assembler::AVX_128bit, /*ktmp*/k1, ones); - __ vaesenc(xmm0, xmm0, xmm22, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm23, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm24, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm25, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm26, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm27, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm28, Assembler::AVX_128bit); - __ vaesenc(xmm0, xmm0, xmm29, Assembler::AVX_128bit); - - __ cmpl(rounds, 52); - __ jcc(Assembler::aboveEqual, AES192_REMAINDER); - __ vaesenclast(xmm0, xmm0, xmm30, Assembler::AVX_128bit); - __ jmp(END_REMAINDER_LOOP); - - __ bind(AES192_REMAINDER); - __ vaesenc(xmm0, xmm0, xmm30, Assembler::AVX_128bit); - ev_load_key(xmm18, key, 11 * 16, xmm31); - __ vaesenc(xmm0, xmm0, xmm18, Assembler::AVX_128bit); - ev_load_key(xmm5, key, 12 * 16, xmm31); - __ cmpl(rounds, 60); - __ jcc(Assembler::aboveEqual, AES256_REMAINDER); - __ vaesenclast(xmm0, xmm0, xmm5, Assembler::AVX_128bit); - __ jmp(END_REMAINDER_LOOP); - - __ bind(AES256_REMAINDER); - __ vaesenc(xmm0, xmm0, xmm5, Assembler::AVX_128bit); - ev_load_key(xmm6, key, 13 * 16, xmm31); - __ vaesenc(xmm0, xmm0, xmm6, Assembler::AVX_128bit); - ev_load_key(xmm7, key, 14 * 16, xmm31); - __ vaesenclast(xmm0, xmm0, xmm7, Assembler::AVX_128bit); - - __ bind(END_REMAINDER_LOOP); - // If the length register is less than the blockSize i.e. 16 - // then we store only those bytes of the CT to the destination - // corresponding to the length register value - // extracting the exact number of bytes is handled by EXTRACT_TAILBYTES - __ cmpl(len_reg, 16); - __ jcc(Assembler::less, EXTRACT_TAILBYTES); - __ subl(len_reg, 16); - // After AES encode rounds, the encrypted block cipher lies in xmm0. - // If the length register is equal to 16 bytes, store CT in dest after XOR operation. - __ evpxorq(xmm0, xmm0, Address(src_addr, pos, Address::times_1, 0), Assembler::AVX_128bit); - __ evmovdquq(Address(dest_addr, pos, Address::times_1, 0), xmm0, Assembler::AVX_128bit); - __ addl(pos, 16); - - __ jmp(REMAINDER_LOOP); - - __ bind(EXTRACT_TAILBYTES); - // Save encrypted counter value in xmm0 for next invocation, before XOR operation - __ movdqu(Address(saved_encCounter_start, 0), xmm0); - // XOR encryted block cipher in xmm0 with PT to produce CT - // extract up to 15 bytes of CT from xmm0 as specified by length register - __ testptr(len_reg, 8); - __ jcc(Assembler::zero, EXTRACT_TAIL_4BYTES); - __ pextrq(tail, xmm0, 0); - __ xorq(tail, Address(src_addr, pos, Address::times_1, 0)); - __ movq(Address(dest_addr, pos), tail); - __ psrldq(xmm0, 8); - __ addl(pos, 8); - __ bind(EXTRACT_TAIL_4BYTES); - __ testptr(len_reg, 4); - __ jcc(Assembler::zero, EXTRACT_TAIL_2BYTES); - __ pextrd(tail, xmm0, 0); - __ xorl(tail, Address(src_addr, pos, Address::times_1, 0)); - __ movl(Address(dest_addr, pos), tail); - __ psrldq(xmm0, 4); - __ addq(pos, 4); - __ bind(EXTRACT_TAIL_2BYTES); - __ testptr(len_reg, 2); - __ jcc(Assembler::zero, EXTRACT_TAIL_1BYTE); - __ pextrw(tail, xmm0, 0); - __ xorw(tail, Address(src_addr, pos, Address::times_1, 0)); - __ movw(Address(dest_addr, pos), tail); - __ psrldq(xmm0, 2); - __ addl(pos, 2); - __ bind(EXTRACT_TAIL_1BYTE); - __ testptr(len_reg, 1); - __ jcc(Assembler::zero, END); - __ pextrb(tail, xmm0, 0); - __ xorb(tail, Address(src_addr, pos, Address::times_1, 0)); - __ movb(Address(dest_addr, pos), tail); - __ addl(pos, 1); - - __ bind(END); - // If there are no tail bytes, store counter value and exit - __ cmpl(len_reg, 0); - __ jcc(Assembler::equal, STORE_CTR); - __ movl(Address(used_addr, 0), len_reg); - - __ bind(STORE_CTR); - //shuffle updated counter and store it - __ vpshufb(xmm8, xmm8, xmm16, Assembler::AVX_128bit); - __ movdqu(Address(counter, 0), xmm8); - // Zero out counter and key registers - __ evpxorq(xmm8, xmm8, xmm8, Assembler::AVX_512bit); - __ evpxorq(xmm20, xmm20, xmm20, Assembler::AVX_512bit); - __ evpxorq(xmm21, xmm21, xmm21, Assembler::AVX_512bit); - __ evpxorq(xmm22, xmm22, xmm22, Assembler::AVX_512bit); - __ evpxorq(xmm23, xmm23, xmm23, Assembler::AVX_512bit); - __ evpxorq(xmm24, xmm24, xmm24, Assembler::AVX_512bit); - __ evpxorq(xmm25, xmm25, xmm25, Assembler::AVX_512bit); - __ evpxorq(xmm26, xmm26, xmm26, Assembler::AVX_512bit); - __ evpxorq(xmm27, xmm27, xmm27, Assembler::AVX_512bit); - __ evpxorq(xmm28, xmm28, xmm28, Assembler::AVX_512bit); - __ evpxorq(xmm29, xmm29, xmm29, Assembler::AVX_512bit); - __ evpxorq(xmm30, xmm30, xmm30, Assembler::AVX_512bit); - __ cmpl(rounds, 44); - __ jcc(Assembler::belowEqual, EXIT); - __ evpxorq(xmm18, xmm18, xmm18, Assembler::AVX_512bit); - __ evpxorq(xmm5, xmm5, xmm5, Assembler::AVX_512bit); - __ cmpl(rounds, 52); - __ jcc(Assembler::belowEqual, EXIT); - __ evpxorq(xmm6, xmm6, xmm6, Assembler::AVX_512bit); - __ evpxorq(xmm7, xmm7, xmm7, Assembler::AVX_512bit); - __ bind(EXIT); -} - void StubGenerator::gfmul_avx512(XMMRegister GH, XMMRegister HK) { const XMMRegister TMP1 = xmm0; const XMMRegister TMP2 = xmm1; @@ -4404,16 +4221,14 @@ void StubGenerator::init_AOTAddressTable_aes(GrowableArray
& external_ad #define ADD(addr) external_addresses.append((address)(addr)) ADD(key_shuffle_mask_addr()); ADD(counter_shuffle_mask_addr()); - ADD(counter_mask_linc0_addr()); ADD(counter_mask_linc1_addr()); ADD(counter_mask_linc1f_addr()); ADD(counter_mask_linc2_addr()); ADD(counter_mask_linc2f_addr()); ADD(counter_mask_linc4_addr()); - ADD(counter_mask_linc8_addr()); - ADD(counter_mask_linc16_addr()); - ADD(counter_mask_linc32_addr()); - ADD(counter_mask_ones_addr()); + ADD(counter_adder_addr(Assembler::AVX_128bit)); + ADD(counter_adder_addr(Assembler::AVX_256bit)); + ADD(counter_adder_addr(Assembler::AVX_512bit)); ADD(ghash_polynomial_reduction_addr()); ADD(ghash_polynomial_two_one_addr()); ADD(counter_mask_addbe_4444_addr()); diff --git a/src/hotspot/cpu/x86/vm_version_x86.cpp b/src/hotspot/cpu/x86/vm_version_x86.cpp index 5f2f2bfa136..02173bb5649 100644 --- a/src/hotspot/cpu/x86/vm_version_x86.cpp +++ b/src/hotspot/cpu/x86/vm_version_x86.cpp @@ -1046,7 +1046,6 @@ void VM_Version::get_processor_features() { clear_feature(CPU_AVX512VL); clear_feature(CPU_AVX512_VPOPCNTDQ); clear_feature(CPU_AVX512_VPCLMULQDQ); - clear_feature(CPU_AVX512_VAES); clear_feature(CPU_AVX512_VNNI); clear_feature(CPU_AVX512_VBMI); clear_feature(CPU_AVX512_VBMI2); @@ -1062,6 +1061,7 @@ void VM_Version::get_processor_features() { if (UseAVX < 2) { clear_feature(CPU_AVX2); clear_feature(CPU_AVX_IFMA); + clear_feature(CPU_VAES); } if (UseAVX < 1) { @@ -1084,7 +1084,7 @@ void VM_Version::get_processor_features() { clear_feature(CPU_APX_F); clear_feature(CPU_AVX512DQ); clear_feature(CPU_AVX512_VNNI); - clear_feature(CPU_AVX512_VAES); + clear_feature(CPU_VAES); clear_feature(CPU_AVX512_VPOPCNTDQ); clear_feature(CPU_AVX512_VPCLMULQDQ); clear_feature(CPU_AVX512_VBMI); @@ -1224,15 +1224,15 @@ void VM_Version::get_processor_features() { FLAG_SET_DEFAULT(UseAESCTRIntrinsics, false); } } else { - if (supports_sse4_1()) { + if (supports_sse4_2()) { if (FLAG_IS_DEFAULT(UseAESCTRIntrinsics)) { FLAG_SET_DEFAULT(UseAESCTRIntrinsics, true); } } else if (UseAESCTRIntrinsics) { // The AES-CTR intrinsic stubs require AES instruction support (of course) - // but also require sse4.1 mode or higher for instructions it use. + // but also require sse4.2 mode or higher for instructions it use. if (!FLAG_IS_DEFAULT(UseAESCTRIntrinsics)) { - warning("X86 AES-CTR intrinsics require SSE4.1 instructions or higher. Intrinsics will be disabled."); + warning("X86 AES-CTR intrinsics require SSE4.2 instructions or higher. Intrinsics will be disabled."); } FLAG_SET_DEFAULT(UseAESCTRIntrinsics, false); } @@ -3012,6 +3012,8 @@ VM_Version::VM_Features VM_Version::CpuidInfo::feature_flags() const { } if (sef_cpuid7_ecx.bits.gfni != 0) vm_features.set_feature(CPU_GFNI); + if (sef_cpuid7_ecx.bits.vaes != 0) + vm_features.set_feature(CPU_VAES); if (sef_cpuid7_ebx.bits.avx512f != 0 && xem_xcr0_eax.bits.opmask != 0 && xem_xcr0_eax.bits.zmm512 != 0 && @@ -3035,8 +3037,6 @@ VM_Version::VM_Features VM_Version::CpuidInfo::feature_flags() const { vm_features.set_feature(CPU_AVX512_VPOPCNTDQ); if (sef_cpuid7_ecx.bits.avx512_vpclmulqdq != 0) vm_features.set_feature(CPU_AVX512_VPCLMULQDQ); - if (sef_cpuid7_ecx.bits.vaes != 0) - vm_features.set_feature(CPU_AVX512_VAES); if (sef_cpuid7_ecx.bits.avx512_vnni != 0) vm_features.set_feature(CPU_AVX512_VNNI); if (sef_cpuid7_ecx.bits.avx512_bitalg != 0) @@ -3063,7 +3063,7 @@ VM_Version::VM_Features VM_Version::CpuidInfo::feature_flags() const { vm_features.set_feature(CPU_AVX512VL); vm_features.set_feature(CPU_AVX512_VPOPCNTDQ); vm_features.set_feature(CPU_AVX512_VPCLMULQDQ); - vm_features.set_feature(CPU_AVX512_VAES); + vm_features.set_feature(CPU_VAES); vm_features.set_feature(CPU_AVX512_VNNI); vm_features.set_feature(CPU_AVX512_BITALG); vm_features.set_feature(CPU_AVX512_VBMI); diff --git a/src/hotspot/cpu/x86/vm_version_x86.hpp b/src/hotspot/cpu/x86/vm_version_x86.hpp index 2d24cd39f9a..067433048ee 100644 --- a/src/hotspot/cpu/x86/vm_version_x86.hpp +++ b/src/hotspot/cpu/x86/vm_version_x86.hpp @@ -414,7 +414,7 @@ class VM_Version : public Abstract_VM_Version { decl(VZEROUPPER, vzeroupper ) /* Vzeroupper instruction */ \ decl(AVX512_VPOPCNTDQ, avx512_vpopcntdq ) /* Vector popcount */ \ decl(AVX512_VPCLMULQDQ, avx512_vpclmulqdq ) /* Vector carryless multiplication */ \ - decl(AVX512_VAES, avx512_vaes ) /* Vector AES instruction */ \ + decl(VAES, vaes ) /* Vector AES instruction */ \ decl(AVX512_VNNI, avx512_vnni ) /* Vector Neural Network Instructions */ \ decl(FLUSHOPT, clflushopt ) /* flusopth instruction */ \ decl(CLWB, clwb ) /* clwb instruction */ \ @@ -932,7 +932,7 @@ class VM_Version : public Abstract_VM_Version { static bool supports_vzeroupper() { return _features.supports_feature(CPU_VZEROUPPER); } static bool supports_avx512_vpopcntdq() { return _features.supports_feature(CPU_AVX512_VPOPCNTDQ); } static bool supports_avx512_vpclmulqdq() { return _features.supports_feature(CPU_AVX512_VPCLMULQDQ); } - static bool supports_avx512_vaes() { return _features.supports_feature(CPU_AVX512_VAES); } + static bool supports_vaes() { return _features.supports_feature(CPU_VAES); } static bool supports_gfni() { return _features.supports_feature(CPU_GFNI); } static bool supports_avx512_vnni() { return _features.supports_feature(CPU_AVX512_VNNI); } static bool supports_avx512_bitalg() { return _features.supports_feature(CPU_AVX512_BITALG); } diff --git a/test/hotspot/jtreg/compiler/codegen/aes/TestAESCTR.java b/test/hotspot/jtreg/compiler/codegen/aes/TestAESCTR.java new file mode 100644 index 00000000000..8bc96fb2e7e --- /dev/null +++ b/test/hotspot/jtreg/compiler/codegen/aes/TestAESCTR.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2026, Intel Corporation. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8391494 + * @key stress randomness + * @summary test AES/CTR intrinsics + * @library /test/lib / + * @modules java.base/jdk.internal.misc + * java.management + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm/timeout=600 -Xbatch -DcheckOutput=true -Dmode=CTR + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. + * compiler.codegen.aes.TestAESCTR + */ +/** + * @test + * @bug 8391494 + * @key stress randomness + * @requires os.simpleArch == "x64" + * @summary test AES/CTR intrinsics + * @library /test/lib / + * @modules java.base/jdk.internal.misc + * java.management + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm/timeout=600 -Xbatch -DcheckOutput=true -Dmode=CTR + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. + * -XX:UseAVX=2 -XX:+EnableX86ECoreOpts compiler.codegen.aes.TestAESCTR + * @run main/othervm/timeout=600 -Xbatch -DcheckOutput=true -Dmode=CTR + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. + * -XX:UseAVX=1 compiler.codegen.aes.TestAESCTR + */ + +package compiler.codegen.aes; + +import jdk.test.whitebox.WhiteBox; + +public class TestAESCTR { + public static void main(String[] args) { + String[] keys = {"128", "192", "256"}; + int[] msgSizes = { + 1, 15, 16, 17, 63, 64, 65, 128, 129, 256, 639, 768, 801, 512*200+1 + }; + for (int msgSize:msgSizes) { + for (String key:keys) { + System.setProperty("keySize", key); + System.setProperty("msgSize", ""+msgSize); + + // deopt so reference output is from Java AES implementation + WhiteBox.getWhiteBox().deoptimizeAll(); + TestAESMain.main(args); + + if (msgSize == 1) { + continue; + } + + // test the usedCtr path, force update() + doFinal() + System.setProperty("lastChunkSize", "7"); + System.setProperty("encInputOffset", "1"); + WhiteBox.getWhiteBox().deoptimizeAll(); + TestAESMain.main(args); + System.clearProperty("lastChunkSize"); + System.clearProperty("encInputOffset"); + } + } + } +} diff --git a/test/lib-test/jdk/test/whitebox/CPUInfoTest.java b/test/lib-test/jdk/test/whitebox/CPUInfoTest.java index 283807d039e..bd620ae82a3 100644 --- a/test/lib-test/jdk/test/whitebox/CPUInfoTest.java +++ b/test/lib-test/jdk/test/whitebox/CPUInfoTest.java @@ -60,7 +60,7 @@ public class CPUInfoTest { "bmi2", "rtm", "adx", "avx512f", "avx512dq", "avx512pf", "avx512er", "avx512cd", "avx512bw", "avx512vl", "sha", "fma", - "vzeroupper", "avx512_vpopcntdq", "avx512_vpclmulqdq", "avx512_vaes", + "vzeroupper", "avx512_vpopcntdq", "avx512_vpclmulqdq", "vaes", "avx512_vnni", "clflush", "clflushopt", "clwb", "avx512_vbmi2", "avx512_vbmi", "rdtscp", "rdpid", "hv", "fsrm", "avx512_bitalg", "gfni", From 9e079370a03bd6c6b98daf74fcf4c878715e4976 Mon Sep 17 00:00:00 2001 From: Alexander Zuev Date: Thu, 19 Nov 2026 19:39:14 +0000 Subject: [PATCH 11/95] 8396626: [macos27] java/awt/dnd/MissingEventsOnModalDialog/MissingEventsOnModalDialogTest.java test fails Reviewed-by: prr, azvegint --- .../MissingEventsOnModalDialogTest.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/test/jdk/java/awt/dnd/MissingEventsOnModalDialog/MissingEventsOnModalDialogTest.java b/test/jdk/java/awt/dnd/MissingEventsOnModalDialog/MissingEventsOnModalDialogTest.java index b99e9d2b7f4..3291db57363 100644 --- a/test/jdk/java/awt/dnd/MissingEventsOnModalDialog/MissingEventsOnModalDialogTest.java +++ b/test/jdk/java/awt/dnd/MissingEventsOnModalDialog/MissingEventsOnModalDialogTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,6 +22,7 @@ */ import java.awt.Dialog; +import java.awt.EventQueue; import java.awt.Frame; import java.awt.Point; import java.awt.Robot; @@ -46,6 +47,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /* @@ -60,7 +62,8 @@ public class MissingEventsOnModalDialogTest { private static final String RUN_PROCESS = "RUN_PROCESS"; private static final String RUN_TEST = "RUN_TEST"; private static boolean exception = false; - private static volatile boolean passed = false; + private static final CountDownLatch CLICKED = new CountDownLatch(1); + private static final int CLICK_TIMEOUT_SECONDS = 5; public static void main(String[] args) throws Exception { String command = args.length < 1 ? RUN_TEST : args[0]; @@ -100,20 +103,18 @@ private static void runTest() throws Exception { robot.mouseMove(point.x, point.y); robot.waitForIdle(); - mouseDragAndDrop(robot, point, getCenterPoint(targetFrame)); - - long time = System.currentTimeMillis() + 2000; + try { + mouseDragAndDrop(robot, point, getCenterPoint(targetFrame)); - while (!passed) { - if (time < System.currentTimeMillis()) { - sourceFrame.dispose(); - targetFrame.dispose(); + if (!CLICKED.await(CLICK_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { throw new RuntimeException("Mouse clicked event is lost!"); } - Thread.sleep(10); + } finally { + EventQueue.invokeAndWait(() -> { + sourceFrame.dispose(); + targetFrame.dispose(); + }); } - sourceFrame.dispose(); - targetFrame.dispose(); } private static Frame createFrame(String title, int x, int y) { @@ -220,8 +221,8 @@ private static void showModalDialog(Frame targetFrame) { @Override public void mouseClicked(MouseEvent e) { - passed = true; dialog.dispose(); + CLICKED.countDown(); } }); @@ -255,8 +256,6 @@ private static void clickOnDialog(Dialog dialog) { robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); } catch (Exception e) { throw new RuntimeException(e); - } finally { - dialog.dispose(); } } From 5150c501659c65fc9adfc122d9506a82d8f051ae Mon Sep 17 00:00:00 2001 From: Alexander Zuev Date: Thu, 19 Nov 2026 19:39:47 +0000 Subject: [PATCH 12/95] 8396627: [macos27] java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java test fails Reviewed-by: prr, azvegint --- .../InterJVMGetDropSuccessTest.java | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/test/jdk/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java b/test/jdk/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java index 9548bd4fe2f..c8cf4c383ec 100644 --- a/test/jdk/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java +++ b/test/jdk/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,6 +55,7 @@ import java.awt.event.MouseEvent; import java.io.File; import java.io.InputStream; +import java.util.concurrent.TimeUnit; public class InterJVMGetDropSuccessTest { @@ -160,6 +161,7 @@ final class Util implements AWTEventListener { public static final int CODE_FAILURE = 0x1; public static final int FRAME_ACTIVATION_TIMEOUT = 1000; + public static final int DROP_COMPLETION_TIMEOUT = 5000; static final Object SYNC_LOCK = new Object(); @@ -207,10 +209,25 @@ public boolean getDropSuccess() { return dropSuccess; } + public void awaitDropFinished() throws InterruptedException { + synchronized (Util.SYNC_LOCK) { + long deadline = System.nanoTime() + + TimeUnit.MILLISECONDS.toNanos(Util.DROP_COMPLETION_TIMEOUT); + while (!finished) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + throw new RuntimeException("Drop not finished within " + + Util.DROP_COMPLETION_TIMEOUT + " ms"); + } + TimeUnit.NANOSECONDS.timedWait(Util.SYNC_LOCK, remaining); + } + } + } + public void dragDropEnd(DragSourceDropEvent dsde) { - finished = true; - dropSuccess = dsde.getDropSuccess(); synchronized (Util.SYNC_LOCK) { + finished = true; + dropSuccess = dsde.getDropSuccess(); Util.SYNC_LOCK.notifyAll(); } } @@ -271,7 +288,7 @@ public void run(String[] args) { synchronized (Util.SYNC_LOCK) { robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - Util.SYNC_LOCK.wait(Util.FRAME_ACTIVATION_TIMEOUT); + dragSourceListener.awaitDropFinished(); } EventQueue.invokeAndWait(() -> { @@ -296,7 +313,7 @@ public void run(String[] args) { synchronized (Util.SYNC_LOCK) { robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - Util.SYNC_LOCK.wait(Util.FRAME_ACTIVATION_TIMEOUT); + dragSourceListener.awaitDropFinished(); } EventQueue.invokeAndWait(() -> { From b85242a7ffd075ed6e34e71561eb3012eec1b460 Mon Sep 17 00:00:00 2001 From: Alexander Zuev Date: Thu, 19 Nov 2026 19:41:57 +0000 Subject: [PATCH 13/95] 8396625: [macos27] FrameMouseEventAbsoluteCoordsTest.java test fails Reviewed-by: azvegint, prr --- .../FrameMouseEventAbsoluteCoordsTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/jdk/java/awt/event/MouseEvent/FrameMouseEventAbsoluteCoordsTest/FrameMouseEventAbsoluteCoordsTest.java b/test/jdk/java/awt/event/MouseEvent/FrameMouseEventAbsoluteCoordsTest/FrameMouseEventAbsoluteCoordsTest.java index 5113b81be2a..d7565cb099d 100644 --- a/test/jdk/java/awt/event/MouseEvent/FrameMouseEventAbsoluteCoordsTest/FrameMouseEventAbsoluteCoordsTest.java +++ b/test/jdk/java/awt/event/MouseEvent/FrameMouseEventAbsoluteCoordsTest/FrameMouseEventAbsoluteCoordsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -76,7 +76,7 @@ public void start () button.getHeight()/2); robot.mouseMove(mousePositionAbsolute.x, mousePositionAbsolute.y ); - // robot.delay(1000); + robot.delay(1000); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); }catch(AWTException e) { From 4b31987f25ddcc693802dc7da40a31b7561d2546 Mon Sep 17 00:00:00 2001 From: David Holmes Date: Thu, 19 Nov 2026 20:42:07 +0000 Subject: [PATCH 14/95] 8397421: JNI_CreateJavaVM should not retry after VM initialization has started Reviewed-by: jsjolen, kvn, iklam, shade --- src/hotspot/share/prims/jni.cpp | 7 ++++++- src/hotspot/share/runtime/threads.cpp | 23 +++++++++++++++++------ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/hotspot/share/prims/jni.cpp b/src/hotspot/share/prims/jni.cpp index 6d271e17cca..4555257abd3 100644 --- a/src/hotspot/share/prims/jni.cpp +++ b/src/hotspot/share/prims/jni.cpp @@ -3690,7 +3690,8 @@ static jint JNI_CreateJavaVM_inner(JavaVM **vm, void **penv, void *args) { } /** - * Certain errors during initialization are recoverable and do not + * Historical note: + * Certain errors during initialization were recoverable and did not * prevent this method from being called again at a later time * (perhaps with different arguments). However, at a certain * point during initialization if an error occurs we cannot allow @@ -3698,6 +3699,10 @@ static jint JNI_CreateJavaVM_inner(JavaVM **vm, void **penv, void *args) { * situations, the 'canTryAgain' flag is set to false, which atomically * sets safe_to_recreate_vm to 1, such that any new call to * JNI_CreateJavaVM will immediately fail using the above logic. + * + * In practice the ability to recover and reinitialize has not existed + * for a very long time. See Threads::create_vm for the still supported + * case. */ bool can_try_again = true; diff --git a/src/hotspot/share/runtime/threads.cpp b/src/hotspot/share/runtime/threads.cpp index 4f0eede6a1e..98b7b566ea5 100644 --- a/src/hotspot/share/runtime/threads.cpp +++ b/src/hotspot/share/runtime/threads.cpp @@ -456,12 +456,26 @@ class ReadReleaseFileTask : public PeriodicTask { jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { extern void JDK_Version_init(); - // Preinitialize version info. - VM_Version::early_initialize(); - // Check version if (!is_supported_jni_version(args->version)) return JNI_EVERSION; + // The ability to successfully re-initialize a partially initialized VM + // has significantly degraded over the years. Fastdebug VMs will trigger + // assertions almost immediately. In a product release the implications + // of re-initalizing already initialized subsystems is unclear - we know + // that if Arguments::init_system_properties() is called again it causes + // the classpath setting to be lost, rendering the VM almost unusable. + // Other logic likely leads to memory leaks and invalid state that may + // not be detected until much later in the execution of an application. + // Consequently, other than the trivial case above of asking for an + // unsupported JNI version, we do not allow the caller to try again upon + // error. Note that the ability to try again is not even documented in + // the JNI specification. + *canTryAgain = false; + + // Preinitialize version info. + VM_Version::early_initialize(); + // Deferred "static" initialization NonJavaThread::init(); @@ -590,7 +604,6 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { vm_shutdown_during_initialization( "Failed necessary internal allocation. Out of swap space"); main_thread->smr_delete(); - *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again return JNI_ENOMEM; } @@ -608,7 +621,6 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { jint status = init_globals(); if (status != JNI_OK) { main_thread->smr_delete(); - *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again return status; } @@ -629,7 +641,6 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { if (!main_thread->has_pending_exception()) { main_thread->smr_delete(); } - *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again return status; } From c65508c5c97021a18ee6d67b604e7e93d3b0b996 Mon Sep 17 00:00:00 2001 From: ByeongGyu Jeon Date: Thu, 19 Nov 2026 21:24:59 +0000 Subject: [PATCH 15/95] 8394909: Grammatical errors in javac man page Reviewed-by: jlahoda --- src/jdk.compiler/share/man/javac.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/jdk.compiler/share/man/javac.md b/src/jdk.compiler/share/man/javac.md index bcfde3695c6..4b763e313a5 100644 --- a/src/jdk.compiler/share/man/javac.md +++ b/src/jdk.compiler/share/man/javac.md @@ -1297,11 +1297,11 @@ Three different kinds of hierarchy are supported: a _package hierarchy_, a _module hierarchy_, and a _module source hierarchy_. While `javac` is fairly relaxed about the organization of source code, -beyond the expectation that source will be organized in one or package +beyond the expectation that source will be organized in one or more package hierarchies, and can generally accommodate organizations prescribed by development environments and build tools, Java tools in general, and `javac` and the Java launcher in particular, are more stringent -regarding the organization of compiled class files, and will be +regarding the organization of compiled class files, which must be organized in package hierarchies or module hierarchies, as appropriate. The location of these hierarchies are specified to `javac` with command-line From b09eeeb697cd71b9108e9def9d565541ab9b1f50 Mon Sep 17 00:00:00 2001 From: William Kemper Date: Thu, 19 Nov 2026 23:51:14 +0000 Subject: [PATCH 16/95] 8397081: Shenandoah: TestHumongousAllocFailureRecovery.java sometimes fails to establish test conditions Reviewed-by: shade, ruili, kdnilsen --- .../generational/TestHumongousAllocFailureRecovery.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java b/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java index b625c19f412..6a4d1ae15f9 100644 --- a/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java +++ b/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java @@ -30,7 +30,8 @@ * @library /test/lib * @run main/othervm * -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC - * -XX:ShenandoahGCMode=generational -Xmx128m -Xms128m + * -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=passive + * -Xmx128m -Xms128m * -XX:ShenandoahRegionSize=1m -XX:+AlwaysPreTouch * -XX:ConcGCThreads=1 -XX:ParallelGCThreads=1 * TestHumongousAllocFailureRecovery From bad12bd11b24d28b60cb0d77b0e6ae767112458e Mon Sep 17 00:00:00 2001 From: William Kemper Date: Thu, 19 Nov 2026 23:52:06 +0000 Subject: [PATCH 17/95] 8396415: Shenandoah: TestGenerationalReferenceProcessing.java races with unsolicited GC that may promote referents Reviewed-by: shade, ruili, kdnilsen --- test/hotspot/jtreg/ProblemList.txt | 2 -- .../generational/TestGenerationalReferenceProcessing.java | 8 ++++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index 31976c9dc61..703b7e87a0c 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -87,8 +87,6 @@ gc/stress/jfr/TestStressAllocationGCEventsWithShenandoah.java#generational 83869 gc/stress/jfr/TestStressAllocationGCEventsWithShenandoah.java#default 8386964 generic-all gc/stress/jfr/TestStressBigAllocationGCEventsWithShenandoah.java#generational 8386964 generic-all gc/stress/jfr/TestStressBigAllocationGCEventsWithShenandoah.java#default 8386964 generic-all -gc/shenandoah/generational/TestGenerationalReferenceProcessing.java#young 8396415 generic-all -gc/shenandoah/generational/TestGenerationalReferenceProcessing.java#young-no-compressed-oops 8396415 generic-all ############################################################################# diff --git a/test/hotspot/jtreg/gc/shenandoah/generational/TestGenerationalReferenceProcessing.java b/test/hotspot/jtreg/gc/shenandoah/generational/TestGenerationalReferenceProcessing.java index d459110093a..b7450877e78 100644 --- a/test/hotspot/jtreg/gc/shenandoah/generational/TestGenerationalReferenceProcessing.java +++ b/test/hotspot/jtreg/gc/shenandoah/generational/TestGenerationalReferenceProcessing.java @@ -34,7 +34,7 @@ * -XX:+IgnoreUnrecognizedVMOptions * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UnlockExperimentalVMOptions - * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational + * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=passive * -XX:ShenandoahGenerationalMinTenuringAge=1 -XX:ShenandoahGenerationalMaxTenuringAge=1 * -Xmx128M -Xms128M -ea * gc.shenandoah.generational.TestGenerationalReferenceProcessing young @@ -52,7 +52,7 @@ * -XX:+IgnoreUnrecognizedVMOptions * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UnlockExperimentalVMOptions - * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational + * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=passive * -XX:ShenandoahGenerationalMinTenuringAge=1 -XX:ShenandoahGenerationalMaxTenuringAge=1 * -Xmx128M -Xms128M -ea * gc.shenandoah.generational.TestGenerationalReferenceProcessing old @@ -70,7 +70,7 @@ * -XX:+IgnoreUnrecognizedVMOptions * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UnlockExperimentalVMOptions -XX:-UseCompressedOops - * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational + * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=passive * -XX:ShenandoahGenerationalMinTenuringAge=1 -XX:ShenandoahGenerationalMaxTenuringAge=1 * -Xmx128M -Xms128M -ea * gc.shenandoah.generational.TestGenerationalReferenceProcessing young @@ -88,7 +88,7 @@ * -XX:+IgnoreUnrecognizedVMOptions * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UnlockExperimentalVMOptions -XX:-UseCompressedOops - * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational + * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=passive * -XX:ShenandoahGenerationalMinTenuringAge=1 -XX:ShenandoahGenerationalMaxTenuringAge=1 * -Xmx128M -Xms128M -ea * gc.shenandoah.generational.TestGenerationalReferenceProcessing old From 3cf8493003e4f7284a4b430b40cef8a35b933f65 Mon Sep 17 00:00:00 2001 From: Mikael Vidstedt Date: Fri, 20 Nov 2026 00:30:03 +0000 Subject: [PATCH 18/95] 8397851: Add missing AC_MSG_CHECKING to freetype configuration message Reviewed-by: prr, erikj --- make/autoconf/lib-freetype.m4 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/make/autoconf/lib-freetype.m4 b/make/autoconf/lib-freetype.m4 index 8d524c8c8b9..f08841312ea 100644 --- a/make/autoconf/lib-freetype.m4 +++ b/make/autoconf/lib-freetype.m4 @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -237,7 +237,8 @@ AC_DEFUN_ONCE([LIB_SETUP_FREETYPE], fi fi - AC_MSG_RESULT([Using freetype: $FREETYPE_TO_USE]) + AC_MSG_CHECKING([for which freetype to use]) + AC_MSG_RESULT([$FREETYPE_TO_USE]) AC_SUBST(FREETYPE_TO_USE) AC_SUBST(FREETYPE_CFLAGS) From 010b574b56c74fc4537c29e9d6ea3839560eed98 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 20 Nov 2026 01:11:23 +0000 Subject: [PATCH 19/95] 8397741: Unconditionally use relocation for Medadata loads Reviewed-by: adinn, heidinga --- src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp | 6 +----- src/hotspot/cpu/x86/macroAssembler_x86.cpp | 6 +----- src/hotspot/share/c1/c1_LIRGenerator.cpp | 9 ++------- 3 files changed, 4 insertions(+), 17 deletions(-) diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp index 96ba171d966..b85f4aa4eeb 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp @@ -7126,11 +7126,7 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i if (vk != nullptr) { // Called from C1, where the return type is statically known. - if (AOTCodeCache::is_on_for_dump()) { - mov_metadata(klass, vk->constant_encoding()); - } else { - movptr(klass, (intptr_t)vk->get_ValueKlass()); - } + mov_metadata(klass, vk->get_ValueKlass()); // get_ValueKlass asserts that vk is ValueKlass jint lh = vk->layout_helper(); assert(lh != Klass::_lh_neutral_value, "value class in return type must have been resolved"); if (UseTLAB && !Klass::layout_helper_needs_slow_path(lh)) { diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.cpp b/src/hotspot/cpu/x86/macroAssembler_x86.cpp index abd55737e18..2755a705870 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp @@ -6024,11 +6024,7 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i mov(rscratch1, rax); // save rax for slow_case since *_allocate may corrupt it when allocation failed if (vk != nullptr) { // Called from C1, where the return type is statically known. - if (AOTCodeCache::is_on_for_dump()) { - mov_metadata(rbx, vk->constant_encoding()); - } else { - movptr(rbx, (intptr_t)vk->get_ValueKlass()); - } + mov_metadata(rbx, vk->get_ValueKlass()); // get_ValueKlass asserts that vk is ValueKlass jint lh = vk->layout_helper(); assert(lh != Klass::_lh_neutral_value, "value class in return type must have been resolved"); if (UseTLAB && !Klass::layout_helper_needs_slow_path(lh)) { diff --git a/src/hotspot/share/c1/c1_LIRGenerator.cpp b/src/hotspot/share/c1/c1_LIRGenerator.cpp index e200e05f8d3..f22acc6e3bd 100644 --- a/src/hotspot/share/c1/c1_LIRGenerator.cpp +++ b/src/hotspot/share/c1/c1_LIRGenerator.cpp @@ -3878,13 +3878,8 @@ void LIRGenerator::increment_event_counter_impl(CodeEmitInfo* info, bailout("method counters allocation failed"); return; } - if (AOTCodeCache::is_dumping_code()) { - counter_holder = new_register(T_METADATA); - __ metadata2reg(counters_adr->constant_encoding(), counter_holder); - } else { - counter_holder = new_pointer_register(); - __ move(LIR_OprFact::intptrConst(counters_adr->constant_encoding()), counter_holder); - } + counter_holder = new_register(T_METADATA); + __ metadata2reg(counters_adr->constant_encoding(), counter_holder); offset = in_bytes(backedge ? MethodCounters::backedge_counter_offset() : MethodCounters::invocation_counter_offset()); } else if (level == CompLevel_full_profile) { From 9f61381e1ea9b495c085b05ada0093e950772f15 Mon Sep 17 00:00:00 2001 From: Markus KARG Date: Fri, 20 Nov 2026 01:51:46 +0000 Subject: [PATCH 20/95] 8389573: InputStreamReader.readAllAsString() should override the generic Reader default implementation to avoid unnecessary buffer copies Reviewed-by: jpai --- .../classes/java/io/InputStreamReader.java | 13 +- .../classes/sun/nio/cs/StreamDecoder.java | 38 +++- test/jdk/java/io/Reader/ReadAll.java | 185 +++++++++++++++++- 3 files changed, 227 insertions(+), 9 deletions(-) diff --git a/src/java.base/share/classes/java/io/InputStreamReader.java b/src/java.base/share/classes/java/io/InputStreamReader.java index 092ee8f3423..aff9a30dd96 100644 --- a/src/java.base/share/classes/java/io/InputStreamReader.java +++ b/src/java.base/share/classes/java/io/InputStreamReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -183,6 +183,17 @@ public int read(char[] cbuf, int off, int len) throws IOException { return sd.read(cbuf, off, len); } + @Override + public String readAllAsString() throws IOException { + // optimized implementation for InputStreamReader to + // try and avoid unnecessary buffer copies in super.readAllAsString() + if (this.getClass() == InputStreamReader.class) { + String s = sd.tryReadAllAsString(); + return (s != null) ? s : super.readAllAsString(); + } + return super.readAllAsString(); + } + /** * Tells whether this stream is ready to be read. An InputStreamReader is * ready if its input buffer is not empty, or if bytes are available to be diff --git a/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java b/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java index 124e41b77c9..6afa9c3aa7d 100644 --- a/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java +++ b/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,6 +49,7 @@ public class StreamDecoder extends Reader { private static final int MIN_BYTE_BUFFER_SIZE = 32; private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192; + private boolean readCalled; private volatile boolean closed; private void ensureOpen() throws IOException { @@ -122,6 +123,8 @@ public int read() throws IOException { @SuppressWarnings("fallthrough") private int read0() throws IOException { synchronized (lock) { + readCalled = true; + // Return the leftover char, if there is one if (haveLeftoverChar) { haveLeftoverChar = false; @@ -149,6 +152,7 @@ private int read0() throws IOException { public int read(char[] cbuf, int offset, int length) throws IOException { synchronized (lock) { + readCalled = true; int off = offset; int len = length; @@ -232,19 +236,28 @@ public void fillZeroToPosition() throws IOException { private final InputStream in; private final ReadableByteChannel ch; + // true if decoder was created from cs, false if decoder was provided externally + private final boolean decoderFromCharset; + StreamDecoder(InputStream in, Object lock, Charset cs) { - this(in, lock, + this(in, lock, cs, cs.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE)); + .onUnmappableCharacter(CodingErrorAction.REPLACE), + true); } StreamDecoder(InputStream in, Object lock, CharsetDecoder dec) { + this(in, lock, dec.charset(), dec, false); + } + + private StreamDecoder(InputStream in, Object lock, Charset cs, CharsetDecoder dec, boolean decoderFromCharset) { super(lock); - this.cs = dec.charset(); + this.cs = cs; this.decoder = dec; this.in = in; this.ch = null; + this.decoderFromCharset = decoderFromCharset; this.bb = ByteBuffer.allocate(DEFAULT_BYTE_BUFFER_SIZE); bb.flip(); // So that bb is initially empty } @@ -254,6 +267,7 @@ public void fillZeroToPosition() throws IOException { this.ch = ch; this.decoder = dec; this.cs = dec.charset(); + this.decoderFromCharset = false; this.bb = ByteBuffer.allocate(mbc < 0 ? DEFAULT_BYTE_BUFFER_SIZE : (mbc < MIN_BYTE_BUFFER_SIZE @@ -295,8 +309,7 @@ private int readBytes() throws IOException { return rem; } - int implRead(char[] cbuf, int off, int end) throws IOException { - + private int implRead(char[] cbuf, int off, int end) throws IOException { // In order to handle surrogate pairs, this method requires that // the invoker attempt to read at least two characters. Saving the // extra character, if any, at a higher level is easier than trying @@ -374,4 +387,17 @@ void implClose() throws IOException { in.close(); } } + + public String tryReadAllAsString() throws IOException { + if (in == null || !decoderFromCharset) { + return null; + } + synchronized (lock) { + ensureOpen(); + if (!readCalled) { + return new String(in.readAllBytes(), cs); + } + } + return null; + } } diff --git a/test/jdk/java/io/Reader/ReadAll.java b/test/jdk/java/io/Reader/ReadAll.java index fbe1d5a6431..687945a3c84 100644 --- a/test/jdk/java/io/Reader/ReadAll.java +++ b/test/jdk/java/io/Reader/ReadAll.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,18 +23,23 @@ /* @test * @bug 8354724 - * @summary Test Reader readAllLines and readAllAstring methods + * @summary Test Reader readAllLines and readAllAsString methods * @library .. /test/lib * @build jdk.test.lib.Platform jdk.test.lib.RandomFactory * @run junit ReadAll * @key randomness */ +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.Reader; +import java.io.SequenceInputStream; import java.io.StringReader; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -48,6 +53,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ReadAll { private static final String PHRASE = @@ -190,5 +196,180 @@ public void readAllAsString() throws IOException { string = r.readAllAsString(); } assertEquals(stringExpected.substring(n), string); + + // InputStreamReader implementation: Called directly after construction + try (InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(stringExpected.getBytes()))) { + string = isr.readAllAsString(); + } + assertEquals(stringExpected, string); + + // InputStreamReader implementation: Called on empty stream + try (InputStreamReader isr = new InputStreamReader(InputStream.nullInputStream())) { + string = isr.readAllAsString(); + } + assertEquals("", string); + + // InputStreamReader implementation: Stream ends mid-character (here: last byte of three-byte UTF-8 character missing) + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0xE2, (byte) 0x82 }), StandardCharsets.UTF_8)) { + string = isr.readAllAsString(); + } + assertEquals("\uFFFD", string); + + // InputStreamReader implementation: Complete character + incomplete sequence + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0xE2 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + string = isr.readAllAsString(); + } + assertEquals("\uFFFD", string); + + // InputStreamReader implementation: Two Complete characters + incomplete sequence + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0x42, (byte) 0xE2 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + string = isr.readAllAsString(); + } + assertEquals("B\uFFFD", string); + + // InputStreamReader implementation: Three Complete characters + incomplete sequence + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0x42, (byte) 0x43, (byte) 0xE2 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + assertEquals('B', isr.read()); + string = isr.readAllAsString(); + } + assertEquals("C\uFFFD", string); + + // InputStreamReader implementation: Four Complete characters + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0x42, (byte) 0x43, (byte) 0x44 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + assertEquals('B', isr.read()); + string = isr.readAllAsString(); + } + assertEquals("CD", string); + + // InputStreamReader implementation: 8K+ Complete characters + int plen = PHRASE.length(); + String p8192 = PHRASE.repeat((8192 + plen - 1) / plen); + try (InputStreamReader isr = new InputStreamReader(new SequenceInputStream( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0x42, (byte) 0x43, (byte) 0x44 }), + new ByteArrayInputStream(p8192.getBytes(StandardCharsets.UTF_8))), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + assertEquals('B', isr.read()); + string = isr.readAllAsString(); + } + assertEquals("CD" + p8192, string); + + // InputStreamReader implementation: read() after readAllAsString() + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(stringExpected.getBytes()))) { + assertEquals(stringExpected, isr.readAllAsString()); + assertEquals(-1, isr.read()); // must not throw but return -1 + } + + // InputStreamReader implementation: readAllAsString() after readAllAsString() + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(stringExpected.getBytes()))) { + assertEquals(stringExpected, isr.readAllAsString()); + assertEquals("", isr.readAllAsString()); + } + + // InputStreamReader implementation: Decoder belongs to the Charset instance, empty stream but decoder has bytes + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + assertEquals("", isr.readAllAsString()); + } + + // InputStreamReader implementation: Decoder belongs to the Charset instance, with leftover char + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0x42 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + assertEquals("B", isr.readAllAsString()); + } + + // InputStreamReader implementation: Decoder belongs to the Charset instance, readAllAsString() called twice + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + assertEquals("", isr.readAllAsString()); + assertEquals("", isr.readAllAsString()); + } + + // InputStreamReader implementation: Decoder belongs to the Charset instance, with leftover then readAllAsString() again + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0x42 }), + StandardCharsets.UTF_8)) { + assertEquals('A', isr.read()); + assertEquals("B", isr.readAllAsString()); + assertEquals("", isr.readAllAsString()); + } + + // InputStreamReader implementation: Explicitly provided decoder, on empty input stream + try (InputStreamReader isr = new InputStreamReader( + InputStream.nullInputStream(), + StandardCharsets.UTF_8.newDecoder())) { + assertEquals("", isr.readAllAsString()); + } + + // InputStreamReader implementation: Explicitly provided decoder, empty stream but decoder has bytes + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41 }), + StandardCharsets.UTF_8.newDecoder())) { + assertEquals('A', isr.read()); + assertEquals("", isr.readAllAsString()); + assertEquals(-1, isr.read()); + } + + // InputStreamReader implementation: Explicitly provided decoder, without leftover, then readAllAsString() twice + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41 }), + StandardCharsets.UTF_8.newDecoder())) { + assertEquals('A', isr.read()); + assertEquals("", isr.readAllAsString()); + assertEquals("", isr.readAllAsString()); + assertEquals(-1, isr.read()); + } + + // InputStreamReader implementation: Explicitly provided decoder, with leftover then readAllAsString() again + try (InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream(new byte[] { (byte) 0x41, (byte) 0x42 }), + StandardCharsets.UTF_8.newDecoder())) { + assertEquals('A', isr.read()); + assertEquals("B", isr.readAllAsString()); + assertEquals("", isr.readAllAsString()); + assertEquals(-1, isr.read()); + } + + // Proofs that internal optimization in InputStreamReader is skipped with subclasses + try (InputStreamReaderSubclass isrs = new InputStreamReaderSubclass( + new ByteArrayInputStream(stringExpected.getBytes(StandardCharsets.UTF_8)))) { + assertEquals(stringExpected, isrs.readAllAsString()); + assertTrue(isrs.readCalled); + } + } + + private static class InputStreamReaderSubclass extends InputStreamReader { + boolean readCalled; + + InputStreamReaderSubclass(InputStream in) { + super(in, StandardCharsets.UTF_8); + } + + @Override + public int read(char[] cbuf, int off, int len) throws IOException { + readCalled = true; + return super.read(cbuf, off, len); + } } } From 69e56809606c182b85b8491ea97a455ecda6bff1 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Fri, 20 Nov 2026 03:38:13 +0000 Subject: [PATCH 21/95] 8393346: Reject invalid values for XML properties with a fixed set of string values Reviewed-by: jlu --- .../jdk/xml/internal/XMLSecurityManager.java | 49 +++++++---- src/java.xml/share/classes/module-info.java | 2 + .../unittest/common/ImplPropertyTest.java | 81 ++++++++++++++----- 3 files changed, 97 insertions(+), 35 deletions(-) diff --git a/src/java.xml/share/classes/jdk/xml/internal/XMLSecurityManager.java b/src/java.xml/share/classes/jdk/xml/internal/XMLSecurityManager.java index 336b101f8ac..bc49e89c171 100644 --- a/src/java.xml/share/classes/jdk/xml/internal/XMLSecurityManager.java +++ b/src/java.xml/share/classes/jdk/xml/internal/XMLSecurityManager.java @@ -30,6 +30,7 @@ import java.net.URI; import java.util.Collections; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; @@ -84,8 +85,7 @@ public final class XMLSecurityManager implements Cloneable { CR_MAP = Collections.unmodifiableMap(map); } - // Valid values for Resource Access, and mappings between the string and - // integer values + // Canonical string representations of the Resource Access integer values static final Map RA_MAP; // Source Level JDK 8 static { @@ -102,13 +102,17 @@ public final class XMLSecurityManager implements Cloneable { private static final IntegerMapper INTMAPPER = new IntegerMapper(); // DTD value mapper - private static final StringMapper DTDMAPPER = new StringMapper(DTD_MAP); + private static final StringMapper DTDMAPPER = new StringMapper(JdkConstants.DTD_PROPNAME, DTD_MAP); // Catalog Resolve value mapper - private static final StringMapper CRMAPPER = new StringMapper(CR_MAP); + private static final StringMapper CRMAPPER = new StringMapper(JdkConstants.JDKCATALOG_RESOLVE, CR_MAP); - // Resource Access value mapper - private static final StringMapper RAMAPPER = new StringMapper(RA_MAP); + /** + * Resource Access value mapper + * AccessRule parses and validates the rules. This mapper provides string representations + * of the broad access cases: allow all and deny all. + */ + private static final StringMapper RAMAPPER = new StringMapper(JdkConstants.RESOURCE_ACCESS, RA_MAP); /** * Limits managed by the security manager @@ -483,7 +487,9 @@ public void setLimit(Limit limit, State state, Object value) { if (state.compareTo(states[index]) >= 0) { String ruleValue = (String)value; AccessRule rule = new AccessRule(ruleValue); - int intValue = limit.mapper().toInt(ruleValue); + // AccessRule holds the actual rules. The integer value is used + // only for bookkeeping; access decisions use AccessRule.allows. + int intValue = ruleValue.trim().isEmpty() ? JdkConstants.DENY : JdkConstants.ALLOW; accessRule = rule; values[index] = intValue; states[index] = state; @@ -851,7 +857,7 @@ private boolean getPropertyConfig(Limit limit, String sysPropertyName) { } private boolean isPropertyValuePresent(Limit limit, String value) { - return value != null && (!value.isEmpty() || limit == Limit.RESOURCE_ACCESS); + return value != null && (!value.isEmpty() || limit.mapper() instanceof StringMapper); } /** @@ -892,10 +898,18 @@ public static XMLSecurityManager convert(Object value, XMLSecurityManager securi * keys and values within the map. */ public static class StringMapper extends ValueMapper { + private final String propertyName; private final Map map; private final Map reverseMap; - public StringMapper(Map map) { + /** + * Creates a mapper for the named property. + * + * @param propertyName the name of the property + * @param map the value mappings, or null for numeric conversion + */ + public StringMapper(String propertyName, Map map) { + this.propertyName = propertyName; this.map = map; if (map != null) { reverseMap = map.entrySet().stream() @@ -907,18 +921,25 @@ public StringMapper(Map map) { /** * Finds the mapping int value with the specified property value. This - * method will try to convert the provided value to an integer if no - * mapping is found. + * method trims surrounding whitespace before looking up the value, + * or converts the value to an integer if no map is supplied. * @param value the property value - * @return the mapping int value if found, null otherwise + * @return the mapped or converted integer + * @throws IllegalArgumentException if the value is not in the provided map + * @throws NumberFormatException if numeric conversion is required and + * the value cannot be parsed as a number */ @Override public int toInt(Object value) { Objects.requireNonNull(value); Integer iVal; if (map != null) { - iVal = map.get(((String)value).toLowerCase()); - iVal = (iVal == null) ? 0 : iVal; + String stringValue = ((String)value).trim(); + iVal = map.get(stringValue.toLowerCase(Locale.ROOT)); + if (iVal == null) { + throw new IllegalArgumentException("Invalid setting '" + value + + "' for property '" + propertyName + "'."); + } } else { try { iVal = (int)Double.parseDouble((String)value); diff --git a/src/java.xml/share/classes/module-info.java b/src/java.xml/share/classes/module-info.java index fb2f2fe602d..9bf70fe64fb 100644 --- a/src/java.xml/share/classes/module-info.java +++ b/src/java.xml/share/classes/module-info.java @@ -1012,6 +1012,7 @@ * String * * {@code allow, ignore, and deny}. Values are case-insensitive. + * If an invalid value is supplied, {@code IllegalArgumentException} is thrown. * * allow * No @@ -1046,6 +1047,7 @@ * String * * {@code continue, ignore, and strict}. Values are case-insensitive. + * If an invalid value is supplied, {@code IllegalArgumentException} is thrown. * * continue * No diff --git a/test/jaxp/javax/xml/jaxp/unittest/common/ImplPropertyTest.java b/test/jaxp/javax/xml/jaxp/unittest/common/ImplPropertyTest.java index a6bd2c817a6..d1a73b3298b 100644 --- a/test/jaxp/javax/xml/jaxp/unittest/common/ImplPropertyTest.java +++ b/test/jaxp/javax/xml/jaxp/unittest/common/ImplPropertyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,8 @@ import java.util.EnumSet; import java.util.Set; +import java.util.stream.Stream; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; @@ -33,36 +35,40 @@ import javax.xml.validation.SchemaFactory; import javax.xml.xpath.XPathFactory; import jdk.xml.internal.JdkProperty.ImplPropMap; +import jdk.xml.internal.JdkProperty.State; +import jdk.xml.internal.XMLSecurityManager; import jdk.xml.internal.XMLSecurityManager.BooleanMapper; import jdk.xml.internal.XMLSecurityManager.IntegerMapper; import jdk.xml.internal.XMLSecurityManager.Limit; import jdk.xml.internal.XMLSecurityManager.StringMapper; import jdk.xml.internal.XMLSecurityManager.ValueMapper; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.XMLReader; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /* * @test - * @bug 8265248 + * @bug 8265248 8393346 * @modules java.xml/com.sun.org.apache.xerces.internal.utils * @modules java.xml/jdk.xml.internal - * @run testng common.ImplPropertyTest + * @run junit/othervm common.ImplPropertyTest * @summary Verifies Implementation-specific Features and Properties as specified * in the java.xml module summary. */ public class ImplPropertyTest { - private final DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance(); private final XMLInputFactory xif = XMLInputFactory.newDefaultFactory(); private final SchemaFactory sf = SchemaFactory.newDefaultInstance(); - - private final XPathFactory xf = XPathFactory.newDefaultInstance(); // as in the Processors table in java.xml module summary @@ -78,6 +84,22 @@ private enum Processor { XPATH }; + // for testing invalid string values + private static Stream invalidStringProperties() { + return Stream.of( + Arguments.of(Limit.DTD, ""), + Arguments.of(Limit.DTD, "invalid"), + Arguments.of(Limit.DTD, " "), + Arguments.of(Limit.DTD, "0"), + Arguments.of(Limit.DTD, "strict"), + Arguments.of(Limit.JDKCATALOG_RESOLVE, ""), + Arguments.of(Limit.JDKCATALOG_RESOLVE, "invalid"), + Arguments.of(Limit.JDKCATALOG_RESOLVE, " "), + Arguments.of(Limit.JDKCATALOG_RESOLVE, "0"), + Arguments.of(Limit.JDKCATALOG_RESOLVE, "allow") + ); + } + /** * Verifies both the new and legacy property names. This test runs two cases: * a. sets legacy property first; @@ -113,6 +135,23 @@ public void testLimits() throws Exception { } } + // Verifies that invalid values are rejected with IllegalArgumentException. + @ParameterizedTest + @MethodSource("invalidStringProperties") + public void testInvalidStringProperty(Limit limit, String value) { + XMLSecurityManager manager = new XMLSecurityManager(); + assertThrows(IllegalArgumentException.class, + () -> manager.setLimit(limit.apiProperty(), State.APIPROPERTY, value)); + + for (Processor processor : EnumSet.of(Processor.DOM, Processor.SAX, + Processor.XMLREADER, Processor.StAX, Processor.VALIDATION, + Processor.TRANSFORM)) { + assertThrows(IllegalArgumentException.class, + () -> testProperties(processor, limit.apiProperty(), value, + null, null, false)); + } + } + // Supported processor for isStandalone: DOMLS @Test public void testIsStandalone() throws Exception { @@ -292,10 +331,10 @@ private void testProperties(Processor processor, String name1, Object value1, } // name1 is set, expected return value: value1 (set with the old name) - Assert.assertEquals(ret1, value1); + assertEquals(value1, ret1); if (differ) { // if both are set, expected value: value2 (set with the new name) - Assert.assertEquals(ret2, value2); + assertEquals(value2, ret2); } } @@ -306,54 +345,54 @@ private void testFeatures(Processor processor, String name1, boolean value1, switch (processor) { case DOM: dbf.setFeature(name1, value1); - Assert.assertEquals(dbf.getFeature(name1), value1); + assertEquals(value1, dbf.getFeature(name1)); if (differ) { dbf.setFeature(name2, value2); dbf.setFeature(name1, value1); - Assert.assertEquals(dbf.getFeature(name2), value2); + assertEquals(value2, dbf.getFeature(name2)); } return; case SAX: SAXParserFactory spf = SAXParserFactory.newDefaultInstance(); spf.setFeature(name1, value1); - Assert.assertEquals(spf.getFeature(name1), value1); + assertEquals(value1, spf.getFeature(name1)); if (differ) { spf.setFeature(name2, value2); spf.setFeature(name1, value1); - Assert.assertEquals(spf.getFeature(name2), value2); + assertEquals(value2, spf.getFeature(name2)); } return; case VALIDATION: sf.setFeature(name1, value1); - Assert.assertEquals(sf.getFeature(name1), value1); + assertEquals(value1, sf.getFeature(name1)); if (differ) { sf.setFeature(name2, value2); sf.setFeature(name1, value1); - Assert.assertEquals(sf.getFeature(name2), value2); + assertEquals(value2, sf.getFeature(name2)); } return; case TRANSFORM: TransformerFactory tf = TransformerFactory.newDefaultInstance(); tf.setFeature(name1, value1); - Assert.assertEquals(tf.getFeature(name1), value1); + assertEquals(value1, tf.getFeature(name1)); if (differ) { tf.setFeature(name2, value2); tf.setFeature(name1, value1); - Assert.assertEquals(tf.getFeature(name2), value2); + assertEquals(value2, tf.getFeature(name2)); } return; case XPATH: xf.setFeature(name1, value1); - Assert.assertEquals(xf.getFeature(name1), value1); + assertEquals(value1, xf.getFeature(name1)); if (differ) { xf.setFeature(name2, value2); xf.setFeature(name1, value1); - Assert.assertEquals(xf.getFeature(name2), value2); + assertEquals(value2, xf.getFeature(name2)); } return; } - Assert.fail("Failed setting features for : " + processor); + fail("Failed setting features for : " + processor); } From ef2fb394c25497ffc956880fe7fe8aa49ac2b8a0 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Fri, 20 Nov 2026 04:58:46 +0000 Subject: [PATCH 22/95] 8393035: [macOS] Calling java.awt.Graphics2D::getFontMetrics for the first time concurrently causes a data race Reviewed-by: psadhukhan, kizune --- .../modules/java.desktop/lib/AwtLibraries.gmk | 13 +- .../macosx/native/libawt_lwawt/awt/AWTView.m | 4 +- .../native/libawt_lwawt/awt/AWTWindow.m | 2 +- .../libawt_lwawt/awt/ApplicationDelegate.m | 5 +- .../native/libawt_lwawt/awt/CDragSource.m | 6 +- .../native/libawt_lwawt/awt/CDropTarget.m | 5 +- .../libawt_lwawt/awt/CDropTargetContextPeer.m | 5 +- .../native/libawt_lwawt/awt/CPrinterJob.m | 12 +- .../native/libawt_lwawt/awt/CTextPipe.m | 4 +- .../libawt_lwawt/awt/ImageSurfaceData.m | 9 +- .../awt/JavaAccessibilityUtilities.m | 4 +- .../awt/JavaComponentAccessibility.m | 18 +-- .../libawt_lwawt/awt/JavaTextAccessibility.m | 11 +- .../native/libawt_lwawt/awt/PrinterView.m | 8 +- .../awt/a11y/ColumnAccessibility.m | 10 +- .../awt/a11y/ComboBoxAccessibility.m | 10 +- .../awt/a11y/CommonComponentAccessibility.m | 17 +-- .../awt/a11y/CommonTextAccessibility.m | 11 +- .../libawt_lwawt/awt/a11y/MenuAccessibility.m | 4 +- .../awt/a11y/NavigableTextAccessibility.m | 9 +- .../awt/a11y/OutlineAccessibility.m | 6 +- .../awt/a11y/OutlineRowAccessibility.m | 4 +- .../awt/a11y/TabGroupAccessibility.m | 6 +- .../awt/a11y/TableAccessibility.m | 10 +- .../awt/a11y/TableRowAccessibility.m | 4 +- .../macosx/native/libosxapp/JNIUtilities.h | 132 ++++++++++-------- .../macosx/native/libosxui/ScreenMenu.m | 5 +- .../FontMetrics/MultiThreadFontMetrics.java | 109 +++++++++++++++ 28 files changed, 283 insertions(+), 160 deletions(-) create mode 100644 test/jdk/java/awt/FontMetrics/MultiThreadFontMetrics.java diff --git a/make/modules/java.desktop/lib/AwtLibraries.gmk b/make/modules/java.desktop/lib/AwtLibraries.gmk index dbc45bb92bd..776abb94677 100644 --- a/make/modules/java.desktop/lib/AwtLibraries.gmk +++ b/make/modules/java.desktop/lib/AwtLibraries.gmk @@ -356,9 +356,18 @@ ifeq ($(call isTargetOs, macosx), true) OPTIMIZATION := LOW, \ EXTRA_HEADER_DIRS := $(LIBAWT_LWAWT_EXTRA_HEADER_DIRS), \ DISABLED_WARNINGS_clang := deprecated-declarations extra-tokens \ - incompatible-pointer-types incomplete-implementation \ + incomplete-implementation \ objc-method-access sign-compare undef unused-function \ unused-variable, \ + DISABLED_WARNINGS_clang_AWTFont.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_CommonComponentAccessibility.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_JavaComponentAccessibility.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_TableRowAccessibility.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_EncoderManager.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_MTLContext.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_MTLGlyphCache.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_MTLPaints.m := incompatible-pointer-types, \ + DISABLED_WARNINGS_clang_MTLSurfaceData.m := incompatible-pointer-types, \ DISABLED_WARNINGS_clang_AWTWindow.m := bitwise-op-parentheses, \ DISABLED_WARNINGS_clang_CFileDialog.m := semicolon-before-method-body, \ DISABLED_WARNINGS_clang_CGGlyphImages.m := pointer-arith, \ @@ -368,7 +377,7 @@ ifeq ($(call isTargetOs, macosx), true) DISABLED_WARNINGS_clang_MTLBlitLoops.m := pointer-arith, \ DISABLED_WARNINGS_clang_MTLPipelineStatesStorage.m := \ semicolon-before-method-body, \ - DISABLED_WARNINGS_clang_MTLRenderer.m := gnu-folding-constant, \ + DISABLED_WARNINGS_clang_MTLRenderer.m := gnu-folding-constant incompatible-pointer-types, \ DISABLED_WARNINGS_clang_MTLVertexCache.m := pointer-arith, \ DISABLED_WARNINGS_clang_OGLBufImgOps.c := format-nonliteral, \ DISABLED_WARNINGS_clang_OGLPaints.c := format-nonliteral, \ diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m index d6dde548c0a..e8e32627cc3 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -905,7 +905,7 @@ - (void)draggingEnded:(id )sender /******************************** BEGIN NSTextInputClient Protocol ********************************/ -static jclass jc_CInputMethod = NULL; +DECLARE_CLASS_ONLY(jc_CInputMethod); #define GET_CIM_CLASS() \ GET_CLASS(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod"); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m index 36fb5dcb666..89d2cc803d7 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m @@ -42,7 +42,7 @@ #define IS(BITS, KEY) \ ((BITS & MASK(KEY)) != 0) -static jclass jc_CPlatformWindow = NULL; +DECLARE_CLASS_ONLY(jc_CPlatformWindow); #define GET_CPLATFORM_WINDOW_CLASS() \ GET_CLASS(jc_CPlatformWindow, "sun/lwawt/macosx/CPlatformWindow"); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m index d84fe9afa4a..cbe267913d4 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -293,7 +293,8 @@ - (void)dealloc { #pragma mark Callbacks from AppKit -static jclass sjc_AppEventHandler = NULL; +DECLARE_CLASS_ONLY(sjc_AppEventHandler); + #define GET_APPEVENTHANDLER_CLASS() \ GET_CLASS(sjc_AppEventHandler, "com/apple/eawt/_AppEventHandler"); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/CDragSource.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/CDragSource.m index ddb8630fb67..ee28fef21ab 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/CDragSource.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/CDragSource.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,8 +69,8 @@ + (void)javaDraggingEnd } @end -static jclass DataTransfererClass = NULL; -static jclass CDragSourceContextPeerClass = NULL; +DECLARE_CLASS_ONLY(DataTransfererClass); +DECLARE_CLASS_ONLY(CDragSourceContextPeerClass); #define GET_DT_CLASS() \ GET_CLASS(DataTransfererClass, "sun/awt/datatransfer/DataTransferer"); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTarget.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTarget.m index 2777dc1e261..2eb167449f2 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTarget.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTarget.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,7 +57,8 @@ static CDropTarget* sCurrentDropTarget; -extern jclass jc_CDropTargetContextPeer; +DECLARE_CLASS_ONLY(jc_CDropTargetContextPeer); + #define GET_DTCP_CLASS() \ GET_CLASS(jc_CDropTargetContextPeer, "sun/lwawt/macosx/CDropTargetContextPeer"); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTargetContextPeer.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTargetContextPeer.m index b29e7283ef4..eb7536e0853 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTargetContextPeer.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/CDropTargetContextPeer.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,8 @@ #import "ThreadUtilities.h" #import "JNIUtilities.h" -jclass jc_CDropTargetContextPeer = NULL; +DECLARE_CLASS_ONLY(jc_CDropTargetContextPeer); + #define GET_DTCP_CLASS() \ GET_CLASS(jc_CDropTargetContextPeer, "sun/lwawt/macosx/CDropTargetContextPeer"); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/CPrinterJob.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/CPrinterJob.m index 555a2746f43..d26bc6c41ab 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/CPrinterJob.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/CPrinterJob.m @@ -41,12 +41,12 @@ #define TWO_SIDED_LONG_EDGE 1 #define TWO_SIDED_SHORT_EDGE 2 -static jclass sjc_Paper = NULL; -static jclass sjc_PageFormat = NULL; -static jclass sjc_CPrinterJob = NULL; -static jclass sjc_CPrinterDialog = NULL; -static jmethodID sjm_getNSPrintInfo = NULL; -static jmethodID sjm_printerJob = NULL; +DECLARE_CLASS_ONLY(sjc_Paper) +DECLARE_CLASS_ONLY(sjc_PageFormat) +DECLARE_CLASS_ONLY(sjc_CPrinterJob) +DECLARE_CLASS_ONLY(sjc_CPrinterDialog) +DECLARE_METHOD_ONLY(sjm_getNSPrintInfo) +DECLARE_FIELD_ONLY(sjm_printerJob) #define GET_PAPER_CLASS() GET_CLASS(sjc_Paper, "java/awt/print/Paper"); #define GET_PAGEFORMAT_CLASS() GET_CLASS(sjc_PageFormat, "java/awt/print/PageFormat"); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/CTextPipe.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/CTextPipe.m index f1c12585728..c353bd2f1e8 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/CTextPipe.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/CTextPipe.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -321,7 +321,7 @@ render using the right font (see bug 7183516) when attribString is not -----------------------------------*/ -static jclass jc_StandardGlyphVector = NULL; +DECLARE_CLASS_ONLY(jc_StandardGlyphVector); #define GET_SGV_CLASS() GET_CLASS(jc_StandardGlyphVector, "sun/font/StandardGlyphVector"); // Checks the GlyphVector Java object for any transforms that were applied to individual characters. If none are present, diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/ImageSurfaceData.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/ImageSurfaceData.m index ec2bbf48b8c..3216f3877c3 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/ImageSurfaceData.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/ImageSurfaceData.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,7 @@ static jfieldID mapSizeID; static jfieldID allGrayID; -static jclass jc_OSXOffScreenSurfaceData = NULL; +DECLARE_CLASS_ONLY(jc_OSXOffScreenSurfaceData); #define GET_OSXOSD_CLASS() \ GET_CLASS(jc_OSXOffScreenSurfaceData, "sun/java2d/OSXOffScreenSurfaceData"); @@ -1620,8 +1620,9 @@ JNIEXPORT void JNICALL Java_sun_java2d_OSXOffScreenSurfaceData_initIDs(JNIEnv *e //fprintf(stderr, "gColorspaceRGB=%p, gColorspaceGray=%p\n", gColorspaceRGB, gColorspaceGray); } -static jclass jc_BufferedImage = NULL; -static jfieldID jm_SurfaceData = NULL; +DECLARE_CLASS_ONLY(jc_BufferedImage); + +DECLARE_FIELD_ONLY(jm_SurfaceData); JNIEXPORT jobject JNICALL Java_sun_java2d_OSXOffScreenSurfaceData_getSurfaceData (JNIEnv *env, jclass bisd, jobject bufImg) diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m index c35122cb331..c735b4a535b 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m @@ -43,11 +43,11 @@ void initializeRoles(); // Unique -static jclass sjc_AccessibleState = NULL; +DECLARE_CLASS_ONLY(sjc_AccessibleState); #define GET_ACCESSIBLESTATE_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_AccessibleState, "javax/accessibility/AccessibleState", ret); -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); NSSize getAxComponentSize(JNIEnv *env, jobject axComponent, jobject component) { diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m index da83387a58d..9565ce19002 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,33 +51,34 @@ // If the value is >=0, it's an index // GET* macros defined in JavaAccessibilityUtilities.h, so they can be shared. -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); -static jmethodID sjm_getAccessibleName = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleName); #define GET_ACCESSIBLENAME_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleName, sjc_CAccessibility, "getAccessibleName", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;", ret); -static jmethodID jm_getChildrenAndRoles = NULL; +DECLARE_METHOD_ONLY(jm_getChildrenAndRoles); + #define GET_CHILDRENANDROLES_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(jm_getChildrenAndRoles, sjc_CAccessibility, "getChildrenAndRoles",\ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;IZ)[Ljava/lang/Object;", ret); -static jmethodID sjm_getAccessibleComponent = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleComponent); #define GET_ACCESSIBLECOMPONENT_STATIC_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleComponent, sjc_CAccessibility, "getAccessibleComponent", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljavax/accessibility/AccessibleComponent;", ret); -static jmethodID sjm_getAccessibleIndexInParent = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleIndexInParent); #define GET_ACCESSIBLEINDEXINPARENT_STATIC_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleIndexInParent, sjc_CAccessibility, "getAccessibleIndexInParent", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)I", ret); -static jclass sjc_CAccessible = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessible); #define GET_CACCESSIBLE_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_CAccessible, "sun/lwawt/macosx/CAccessible", ret); @@ -1062,7 +1063,7 @@ - (NSString *)accessibilityRoleDescriptionAttribute "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;", nil); - jobject axRole = (*env)->CallStaticObjectMethod(env, jm_getAccessibleRoleDisplayString, fAccessible, fComponent); + jobject axRole = (*env)->CallStaticObjectMethod(env, sjc_CAccessibility, jm_getAccessibleRoleDisplayString, fAccessible, fComponent); CHECK_EXCEPTION(); if (axRole != NULL) { value = JavaStringToNSString(env, axRole); @@ -1252,6 +1253,7 @@ - (id)accessibilityValueAttribute GET_ACCESSIBLENAME_METHOD_RETURN(nil); jobject itemValue = (*env)->CallStaticObjectMethod( env, + sjc_CAccessibility, sjm_getAccessibleName, selectedMenuItem->fAccessible, selectedMenuItem->fComponent ); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaTextAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaTextAccessibility.m index 424d44d94cb..0fc5a232a44 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaTextAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaTextAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,25 +29,26 @@ #import "ThreadUtilities.h" #import "JNIUtilities.h" -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); + #define GET_CACCESSIBLITY_CLASS() \ GET_CLASS(sjc_CAccessibility, "sun/lwawt/macosx/CAccessibility"); #define GET_CACCESSIBLITY_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_CAccessibility, "sun/lwawt/macosx/CAccessibility", ret); -static jmethodID sjm_getAccessibleText = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleText); #define GET_ACCESSIBLETEXT_METHOD_RETURN(ret) \ GET_CACCESSIBLITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleText, sjc_CAccessibility, "getAccessibleText", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljavax/accessibility/AccessibleText;", ret); -static jclass sjc_CAccessibleText = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibleText); #define GET_CACCESSIBLETEXT_CLASS() \ GET_CLASS(sjc_CAccessibleText, "sun/lwawt/macosx/CAccessibleText"); #define GET_CACCESSIBLETEXT_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_CAccessibleText, "sun/lwawt/macosx/CAccessibleText", ret); -static jmethodID sjm_getAccessibleEditableText = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleEditableText); #define GET_ACCESSIBLEEDITABLETEXT_METHOD_RETURN(ret) \ GET_CACCESSIBLETEXT_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleEditableText, sjc_CAccessibleText, "getAccessibleEditableText", \ diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/PrinterView.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/PrinterView.m index f219e8082b4..aaae7a031cd 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/PrinterView.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/PrinterView.m @@ -32,11 +32,11 @@ #import "GeomUtilities.h" #import "JNIUtilities.h" -static jclass sjc_CPrinterJob = NULL; -static jclass sjc_PAbortEx = NULL; +DECLARE_CLASS_ONLY(sjc_CPrinterJob); +DECLARE_CLASS_ONLY(sjc_PAbortEx); #define GET_CPRINTERJOB_CLASS() (sjc_CPrinterJob, "sun/lwawt/macosx/CPrinterJob"); #define GET_CPRINTERJOB_CLASS_RETURN(ret) GET_CLASS_RETURN(sjc_CPrinterJob, "sun/lwawt/macosx/CPrinterJob", ret); -#define GET_PRINERABORTEXCEPTION_CLASS(ret) GET_CLASS_RETURN(sjc_PAbortEx, "java/awt/print/PrinterAbortException", ret); +#define GET_PRINTERABORTEXCEPTION_CLASS(ret) GET_CLASS_RETURN(sjc_PAbortEx, "java/awt/print/PrinterAbortException", ret); @implementation PrinterView @@ -279,7 +279,7 @@ - (BOOL)cancelCheck:(JNIEnv*)env BOOL b = (*env)->CallBooleanMethod(env, fPrinterJob, jm_cancelCheck); // AWT_THREADING Safe (known object) if (b) { - GET_PRINERABORTEXCEPTION_CLASS(b); + GET_PRINTERABORTEXCEPTION_CLASS(b); (*env)->ThrowNew(env, sjc_PAbortEx, "Printer Job cancelled"); } else { CHECK_EXCEPTION(); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m index fb41511275b..e93f7a22e50 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -34,14 +34,6 @@ #import "JNIUtilities.h" #import "sun_lwawt_macosx_CAccessibility.h" -static jclass sjc_CAccessibility = NULL; - -static jmethodID jm_getChildrenAndRoles = NULL; -#define GET_CHILDRENANDROLES_METHOD_RETURN(ret) \ - GET_CACCESSIBILITY_CLASS_RETURN(ret); \ - GET_STATIC_METHOD_RETURN(jm_getChildrenAndRoles, sjc_CAccessibility, "getChildrenAndRoles",\ - "(Ljavax/accessibility/Accessible;Ljava/awt/Component;IZ)[Ljava/lang/Object;", ret); - @implementation ColumnAccessibility // NSAccessibilityElement protocol methods diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComboBoxAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComboBoxAccessibility.m index 52f171e9ded..7e4ae7a8d97 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComboBoxAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComboBoxAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2022, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,13 +29,7 @@ #import "ThreadUtilities.h" #import "JNIUtilities.h" -static jclass sjc_CAccessibility = NULL; - -static jmethodID sjm_getAccessibleName = NULL; -#define GET_ACCESSIBLENAME_METHOD_RETURN(ret) \ - GET_CACCESSIBILITY_CLASS_RETURN(ret); \ - GET_STATIC_METHOD_RETURN(sjm_getAccessibleName, sjc_CAccessibility, "getAccessibleName", \ - "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;", ret); +DECLARE_CLASS_ONLY(sjc_CAccessibility); @implementation ComboBoxAccessibility diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m index b9f9f0fa403..b242cc86c34 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m @@ -37,39 +37,39 @@ // GET* macros defined in JavaAccessibilityUtilities.h, so they can be shared. -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); -static jmethodID sjm_getAccessibleName = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleName); #define GET_ACCESSIBLENAME_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleName, sjc_CAccessibility, "getAccessibleName", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;", ret); -static jmethodID jm_getChildrenAndRoles = NULL; +DECLARE_METHOD_ONLY(jm_getChildrenAndRoles); #define GET_CHILDRENANDROLES_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(jm_getChildrenAndRoles, sjc_CAccessibility, "getChildrenAndRoles",\ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;IZ)[Ljava/lang/Object;", ret); -static jmethodID jm_getChildrenAndRolesRecursive = NULL; +DECLARE_METHOD_ONLY(jm_getChildrenAndRolesRecursive); #define GET_CHILDRENANDROLESRECURSIVE_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(jm_getChildrenAndRolesRecursive, sjc_CAccessibility, "getChildrenAndRolesRecursive",\ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;IZI)[Ljava/lang/Object;", ret); -static jmethodID sjm_getAccessibleComponent = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleComponent); #define GET_ACCESSIBLECOMPONENT_STATIC_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleComponent, sjc_CAccessibility, "getAccessibleComponent", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljavax/accessibility/AccessibleComponent;", ret); -static jmethodID sjm_getAccessibleIndexInParent = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleIndexInParent); #define GET_ACCESSIBLEINDEXINPARENT_STATIC_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleIndexInParent, sjc_CAccessibility, "getAccessibleIndexInParent", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)I", ret); -static jclass sjc_CAccessible = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessible); #define GET_CACCESSIBLE_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_CAccessible, "sun/lwawt/macosx/CAccessible", ret); @@ -878,7 +878,7 @@ - (NSString *)accessibilityRoleDescription DECLARE_STATIC_METHOD_RETURN(jm_getAccessibleRoleDisplayString, sjc_CAccessibility, "getAccessibleRoleDisplayString", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;", nil); - jobject axRole = (*env)->CallStaticObjectMethod(env, jm_getAccessibleRoleDisplayString, fAccessible, fComponent); + jobject axRole = (*env)->CallStaticObjectMethod(env, sjc_CAccessibility, jm_getAccessibleRoleDisplayString, fAccessible, fComponent); CHECK_EXCEPTION(); if (axRole != NULL) { value = JavaStringToNSString(env, axRole); @@ -1072,6 +1072,7 @@ - (id)accessibilityValue GET_ACCESSIBLENAME_METHOD_RETURN(nil); jobject itemValue = (*env)->CallStaticObjectMethod( env, + sjc_CAccessibility, sjm_getAccessibleName, selectedMenuItem->fAccessible, selectedMenuItem->fComponent ); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonTextAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonTextAccessibility.m index 3e12f2985e0..fc2e8d43a48 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonTextAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonTextAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,20 +30,21 @@ #define DEFAULT_RANGE NSMakeRange(0, 0) #define DEFAULT_RECT NSMakeRect(0, 0, 0, 0) -static jclass sjc_CAccessibility = NULL; -static jmethodID sjm_getAccessibleText = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); + +DECLARE_METHOD_ONLY(sjm_getAccessibleText); #define GET_ACCESSIBLETEXT_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleText, sjc_CAccessibility, "getAccessibleText", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljavax/accessibility/AccessibleText;", ret); -static jclass sjc_CAccessibleText = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibleText); #define GET_CACCESSIBLETEXT_CLASS() \ GET_CLASS(sjc_CAccessibleText, "sun/lwawt/macosx/CAccessibleText"); #define GET_CACCESSIBLETEXT_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_CAccessibleText, "sun/lwawt/macosx/CAccessibleText", ret); -static jmethodID sjm_getAccessibleEditableText = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleEditableText); #define GET_ACCESSIBLEEDITABLETEXT_METHOD_RETURN(ret) \ GET_CACCESSIBLETEXT_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleEditableText, sjc_CAccessibleText, "getAccessibleEditableText", \ diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m index 14b7ee8c6b5..4858ede5be8 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ #import "ThreadUtilities.h" #import "sun_lwawt_macosx_CAccessibility.h" -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); /* * Implementing a protocol that represents menus both as submenu and as a diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/NavigableTextAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/NavigableTextAccessibility.m index 8e241e65b96..1ceefc6af99 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/NavigableTextAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/NavigableTextAccessibility.m @@ -29,25 +29,26 @@ #import "ThreadUtilities.h" #import "JNIUtilities.h" -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); + #define GET_CACCESSIBLITY_CLASS() \ GET_CLASS(sjc_CAccessibility, "sun/lwawt/macosx/CAccessibility"); #define GET_CACCESSIBLITY_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_CAccessibility, "sun/lwawt/macosx/CAccessibility", ret); -static jmethodID sjm_getAccessibleText = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleText); #define GET_ACCESSIBLETEXT_METHOD_RETURN(ret) \ GET_CACCESSIBLITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleText, sjc_CAccessibility, "getAccessibleText", \ "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljavax/accessibility/AccessibleText;", ret); -static jclass sjc_CAccessibleText = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibleText); #define GET_CACCESSIBLETEXT_CLASS() \ GET_CLASS(sjc_CAccessibleText, "sun/lwawt/macosx/CAccessibleText"); #define GET_CACCESSIBLETEXT_CLASS_RETURN(ret) \ GET_CLASS_RETURN(sjc_CAccessibleText, "sun/lwawt/macosx/CAccessibleText", ret); -static jmethodID sjm_getAccessibleEditableText = NULL; +DECLARE_METHOD_ONLY(sjm_getAccessibleEditableText); #define GET_ACCESSIBLEEDITABLETEXT_METHOD_RETURN(ret) \ GET_CACCESSIBLETEXT_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_getAccessibleEditableText, sjc_CAccessibleText, "getAccessibleEditableText", \ diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineAccessibility.m index 08240614bf7..218ff332801 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, 2024, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,9 +29,9 @@ #import "ThreadUtilities.h" #import "JNIUtilities.h" -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); -static jmethodID sjm_isTreeRootVisible = NULL; +DECLARE_METHOD_ONLY(sjm_isTreeRootVisible); #define GET_ISTREEROOTVISIBLE_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(sjm_isTreeRootVisible, sjc_CAccessibility, "isTreeRootVisible", \ diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m index e1392785904..a0b3965fecb 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -32,7 +32,7 @@ #import "OutlineAccessibility.h" #import "sun_lwawt_macosx_CAccessibility.h" -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); @implementation OutlineRowAccessibility diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TabGroupAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TabGroupAccessibility.m index 06375fc2934..0aa02db971b 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TabGroupAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TabGroupAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -31,9 +31,9 @@ #import "JNIUtilities.h" #import "sun_lwawt_macosx_CAccessibility.h" -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); -static jmethodID jm_getChildrenAndRoles = NULL; +DECLARE_METHOD_ONLY(jm_getChildrenAndRoles); #define GET_CHILDRENANDROLES_METHOD_RETURN(ret) \ GET_CACCESSIBILITY_CLASS_RETURN(ret); \ GET_STATIC_METHOD_RETURN(jm_getChildrenAndRoles, sjc_CAccessibility, "getChildrenAndRoles",\ diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m index 36af3dd5f10..02f6184adb7 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, 2022, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -37,13 +37,7 @@ #import "sun_lwawt_macosx_CAccessibility.h" #import "sun_lwawt_macosx_CAccessible.h" -static jclass sjc_CAccessibility = NULL; - -static jmethodID sjm_getAccessibleName = NULL; -#define GET_ACCESSIBLENAME_METHOD_RETURN(ret) \ - GET_CACCESSIBILITY_CLASS_RETURN(ret); \ - GET_STATIC_METHOD_RETURN(sjm_getAccessibleName, sjc_CAccessibility, "getAccessibleName", \ - "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;", ret); +DECLARE_CLASS_ONLY(sjc_CAccessibility); @implementation TableAccessibility diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m index 7c9f9bcb744..9e48a97b8b7 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -33,7 +33,7 @@ #import "JNIUtilities.h" #import "sun_lwawt_macosx_CAccessibility.h" -static jclass sjc_CAccessibility = NULL; +DECLARE_CLASS_ONLY(sjc_CAccessibility); @implementation TableRowAccessibility diff --git a/src/java.desktop/macosx/native/libosxapp/JNIUtilities.h b/src/java.desktop/macosx/native/libosxapp/JNIUtilities.h index 51fba2770d0..74f374b7441 100644 --- a/src/java.desktop/macosx/native/libosxapp/JNIUtilities.h +++ b/src/java.desktop/macosx/native/libosxapp/JNIUtilities.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,111 +51,125 @@ /******** GET CLASS SUPPORT *********/ -#define GET_CLASS(dst_var, cls) \ - if (dst_var == NULL) { \ +#define GET_CLASS_ONLY(dst_var, cls) \ + dispatch_once(&dst_var##_once, ^{ \ dst_var = (*env)->FindClass(env, cls); \ if (dst_var != NULL) dst_var = (*env)->NewGlobalRef(env, dst_var); \ - } \ - LOG_NULL(dst_var, cls); \ - CHECK_NULL(dst_var); + }); \ + LOG_NULL(dst_var, cls); -#define DECLARE_CLASS(dst_var, cls) \ - static jclass dst_var = NULL; \ - GET_CLASS(dst_var, cls); +#define GET_CLASS(dst_var, cls) \ + GET_CLASS_ONLY(dst_var, cls); \ + CHECK_NULL(dst_var); #define GET_CLASS_RETURN(dst_var, cls, ret) \ - if (dst_var == NULL) { \ - dst_var = (*env)->FindClass(env, cls); \ - if (dst_var != NULL) dst_var = (*env)->NewGlobalRef(env, dst_var); \ - } \ - LOG_NULL(dst_var, cls); \ + GET_CLASS_ONLY(dst_var, cls); \ CHECK_NULL_RETURN(dst_var, ret); -#define DECLARE_CLASS_RETURN(dst_var, cls, ret) \ +#define DECLARE_CLASS_ONLY(dst_var) \ static jclass dst_var = NULL; \ + static dispatch_once_t dst_var##_once; + +#define DECLARE_CLASS(dst_var, cls) \ + DECLARE_CLASS_ONLY(dst_var) \ + GET_CLASS(dst_var, cls); + +#define DECLARE_CLASS_RETURN(dst_var, cls, ret) \ + DECLARE_CLASS_ONLY(dst_var) \ GET_CLASS_RETURN(dst_var, cls, ret); /******** GET METHOD SUPPORT *********/ -#define GET_METHOD(dst_var, cls, name, signature) \ - if (dst_var == NULL) { \ +#define GET_METHOD_ONLY(dst_var, cls, name, signature) \ + dispatch_once(&dst_var##_once, ^{ \ dst_var = (*env)->GetMethodID(env, cls, name, signature); \ - } \ - LOG_NULL(dst_var, name); \ - CHECK_NULL(dst_var); + }); \ + LOG_NULL(dst_var, name); -#define DECLARE_METHOD(dst_var, cls, name, signature) \ - static jmethodID dst_var = NULL; \ - GET_METHOD(dst_var, cls, name, signature); +#define GET_METHOD(dst_var, cls, name, signature) \ + GET_METHOD_ONLY(dst_var, cls, name, signature); \ + CHECK_NULL(dst_var); #define GET_METHOD_RETURN(dst_var, cls, name, signature, ret) \ - if (dst_var == NULL) { \ - dst_var = (*env)->GetMethodID(env, cls, name, signature); \ - } \ - LOG_NULL(dst_var, name); \ + GET_METHOD_ONLY(dst_var, cls, name, signature); \ CHECK_NULL_RETURN(dst_var, ret); +#define DECLARE_METHOD_ONLY(dst_var) \ + static jmethodID dst_var = NULL; \ + static dispatch_once_t dst_var##_once; + +#define DECLARE_METHOD(dst_var, cls, name, signature) \ + DECLARE_METHOD_ONLY(dst_var); \ + GET_METHOD(dst_var, cls, name, signature); + #define DECLARE_METHOD_RETURN(dst_var, cls, name, signature, ret) \ - static jmethodID dst_var = NULL; \ + DECLARE_METHOD_ONLY(dst_var); \ GET_METHOD_RETURN(dst_var, cls, name, signature, ret); -#define GET_STATIC_METHOD(dst_var, cls, name, signature) \ - if (dst_var == NULL) { \ +#define GET_STATIC_METHOD_ONLY(dst_var, cls, name, signature) \ + dispatch_once(&dst_var##_once, ^{ \ dst_var = (*env)->GetStaticMethodID(env, cls, name, signature); \ - } \ - LOG_NULL(dst_var, name); \ - CHECK_NULL(dst_var); + }); \ + LOG_NULL(dst_var, name); -#define DECLARE_STATIC_METHOD(dst_var, cls, name, signature) \ - static jmethodID dst_var = NULL; \ - GET_STATIC_METHOD(dst_var, cls, name, signature); +#define GET_STATIC_METHOD(dst_var, cls, name, signature) \ + GET_STATIC_METHOD_ONLY(dst_var, cls, name, signature); \ + CHECK_NULL(dst_var); #define GET_STATIC_METHOD_RETURN(dst_var, cls, name, signature, ret) \ - if (dst_var == NULL) { \ - dst_var = (*env)->GetStaticMethodID(env, cls, name, signature); \ - } \ - LOG_NULL(dst_var, name); \ + GET_STATIC_METHOD_ONLY(dst_var, cls, name, signature); \ CHECK_NULL_RETURN(dst_var, ret); +#define DECLARE_STATIC_METHOD(dst_var, cls, name, signature) \ + DECLARE_METHOD_ONLY(dst_var); \ + GET_STATIC_METHOD(dst_var, cls, name, signature); + #define DECLARE_STATIC_METHOD_RETURN(dst_var, cls, name, signature, ret) \ - static jmethodID dst_var = NULL; \ + DECLARE_METHOD_ONLY(dst_var); \ GET_STATIC_METHOD_RETURN(dst_var, cls, name, signature, ret); /******** GET FIELD SUPPORT *********/ -#define GET_FIELD(dst_var, cls, name, signature) \ - if (dst_var == NULL) { \ +#define GET_FIELD_ONLY(dst_var, cls, name, signature) \ + dispatch_once(&dst_var##_once, ^{ \ dst_var = (*env)->GetFieldID(env, cls, name, signature); \ - } \ - LOG_NULL(dst_var, name); \ - CHECK_NULL(dst_var); + }); \ + LOG_NULL(dst_var, name); -#define DECLARE_FIELD(dst_var, cls, name, signature) \ - static jfieldID dst_var = NULL; \ - GET_FIELD(dst_var, cls, name, signature); +#define GET_FIELD(dst_var, cls, name, signature) \ + GET_FIELD_ONLY(dst_var, cls, name, signature); \ + CHECK_NULL(dst_var); #define GET_FIELD_RETURN(dst_var, cls, name, signature, ret) \ - if (dst_var == NULL) { \ - dst_var = (*env)->GetFieldID(env, cls, name, signature); \ - } \ - LOG_NULL(dst_var, name); \ + GET_FIELD_ONLY(dst_var, cls, name, signature); \ CHECK_NULL_RETURN(dst_var, ret); +#define DECLARE_FIELD_ONLY(dst_var) \ + static jfieldID dst_var = NULL; \ + static dispatch_once_t dst_var##_once; + +#define DECLARE_FIELD(dst_var, cls, name, signature) \ + DECLARE_FIELD_ONLY(dst_var); \ + GET_FIELD(dst_var, cls, name, signature); + #define DECLARE_FIELD_RETURN(dst_var, cls, name, signature, ret) \ - static jfieldID dst_var = NULL; \ + DECLARE_FIELD_ONLY(dst_var); \ GET_FIELD_RETURN(dst_var, cls, name, signature, ret); -#define GET_STATIC_FIELD_RETURN(dst_var, cls, name, signature, ret) \ - if (dst_var == NULL) { \ +#define GET_STATIC_FIELD_ONLY(dst_var, cls, name, signature) \ + dispatch_once(&dst_var##_once, ^{ \ dst_var = (*env)->GetStaticFieldID(env, cls, name, signature); \ - } \ - LOG_NULL(dst_var, name); \ + }); \ + LOG_NULL(dst_var, name); + +#define GET_STATIC_FIELD_RETURN(dst_var, cls, name, signature, ret) \ + GET_STATIC_FIELD_ONLY(dst_var, cls, name, signature) \ CHECK_NULL_RETURN(dst_var, ret); #define DECLARE_STATIC_FIELD_RETURN(dst_var, cls, name, signature, ret) \ - static jfieldID dst_var = NULL; \ + DECLARE_FIELD_ONLY(dst_var); \ GET_STATIC_FIELD_RETURN(dst_var, cls, name, signature, ret); /********* EXCEPTION_HANDLING *********/ diff --git a/src/java.desktop/macosx/native/libosxui/ScreenMenu.m b/src/java.desktop/macosx/native/libosxui/ScreenMenu.m index c28d87b4ed6..e055789c4f0 100644 --- a/src/java.desktop/macosx/native/libosxui/ScreenMenu.m +++ b/src/java.desktop/macosx/native/libosxui/ScreenMenu.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,8 @@ #import "CMenuBar.h" #import "JNIUtilities.h" -static jclass sjc_ScreenMenu = NULL; +DECLARE_CLASS_ONLY(sjc_ScreenMenu); + #define GET_SCREENMENU_CLASS() \ GET_CLASS(sjc_ScreenMenu, "com/apple/laf/ScreenMenu"); diff --git a/test/jdk/java/awt/FontMetrics/MultiThreadFontMetrics.java b/test/jdk/java/awt/FontMetrics/MultiThreadFontMetrics.java new file mode 100644 index 00000000000..5e51680a74f --- /dev/null +++ b/test/jdk/java/awt/FontMetrics/MultiThreadFontMetrics.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; + +/* + * @test + * @bug 8393035 + * @summary test that MT initialization of font metrics does not crash + * @run main/othervm MultiThreadFontMetrics run + */ +public final class MultiThreadFontMetrics extends Thread { + + static BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); + + public static void main(String[] args) throws Exception { + if (args.length == 0) { + runMetricsTest(); + return; + } + for (int i = 0; i < 20; i++) { + System.out.println(i); + runChild(); + } + } + + static void runChild() { + String cpDir = System.getProperty("java.class.path"); + String jHome = System.getProperty("java.home"); + String jCmd = jHome + File.separator + "bin" + File.separator + "java"; + int exitValue = doExec(jCmd, "-Xcheck:jni", "-cp", cpDir, "MultiThreadFontMetrics"); + if (exitValue != 0) { + throw new RuntimeException("Test Failed"); + } + } + + static int doExec(String... cmds) { + Process p = null; + ProcessBuilder pb = new ProcessBuilder(cmds); + BufferedReader rdr = null; + try { + pb.redirectErrorStream(true); + p = pb.start(); + rdr = new BufferedReader(new InputStreamReader(p.getInputStream())); + String in; + while ((in = rdr.readLine()) != null) { + System.out.println(in); + } + p.waitFor(); + p.destroy(); + } catch (Exception ex) { + ex.printStackTrace(); + } + return p.exitValue(); + } + + static void runMetricsTest() throws Exception { + + System.setProperty("java.awt.headless", "true"); + + int numThreads = 16; + + MultiThreadFontMetrics[] threads = new MultiThreadFontMetrics[numThreads]; + + for (int i = 0; i < numThreads; i++) { + final int threadNumber = i; + threads[i] = new MultiThreadFontMetrics(); + + } + for (Thread t : threads) { + t.start(); + } + for (Thread t : threads) { + t.join(); + } + } + + public void run() { + Graphics2D graphics = image.createGraphics(); + graphics.getFontMetrics(); + graphics.dispose(); + } +} From 057dfd43d5b0283c7af3f15347aa38802ecb5df6 Mon Sep 17 00:00:00 2001 From: Albert Mingkun Yang Date: Fri, 20 Nov 2026 07:50:19 +0000 Subject: [PATCH 23/95] 8397772: AArch64: Remove redundant zero-fill predicates from ClearArray matching rules Reviewed-by: aph, adinn --- src/hotspot/cpu/aarch64/aarch64.ad | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/hotspot/cpu/aarch64/aarch64.ad b/src/hotspot/cpu/aarch64/aarch64.ad index 3845b30e2ad..a784305320a 100644 --- a/src/hotspot/cpu/aarch64/aarch64.ad +++ b/src/hotspot/cpu/aarch64/aarch64.ad @@ -14219,8 +14219,7 @@ instruct clearArray_reg_reg(iRegL_R11 cnt, iRegP_R10 base, iRegL val, Universe d instruct clearArray_imm_reg(immL cnt, iRegP_R10 base, iRegL_R11 temp, immL0 zero, Universe dummy, rFlagsReg cr) %{ predicate((uint64_t)n->in(2)->in(1)->get_long() - < (uint64_t)(BlockZeroingLowLimit >> LogBytesPerWord) - && !((ClearArrayNode*)n)->requires_word_fill()); + < (uint64_t)(BlockZeroingLowLimit >> LogBytesPerWord)); match(Set dummy (ClearArray (Binary cnt base) zero)); effect(TEMP temp, USE_KILL base, KILL cr); From 19f7b9fff237fd77aeea2975c29fe31040dfd0f8 Mon Sep 17 00:00:00 2001 From: Albert Mingkun Yang Date: Fri, 20 Nov 2026 07:53:22 +0000 Subject: [PATCH 24/95] 8397773: RISC-V: Remove redundant zero-fill predicates from ClearArray matching rules Reviewed-by: fyang, gcao --- src/hotspot/cpu/riscv/riscv.ad | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/hotspot/cpu/riscv/riscv.ad b/src/hotspot/cpu/riscv/riscv.ad index e0bc84775c6..b2678333992 100644 --- a/src/hotspot/cpu/riscv/riscv.ad +++ b/src/hotspot/cpu/riscv/riscv.ad @@ -12014,8 +12014,7 @@ instruct clearArray_imm_reg(immL cnt, iRegP_R28 base, immL_0 zero, Universe dumm %{ predicate(!UseRVV && (uint64_t)n->in(2)->in(1)->get_long() - < (uint64_t)(BlockZeroingLowLimit >> LogBytesPerWord) - && !((ClearArrayNode*)n)->requires_word_fill()); + < (uint64_t)(BlockZeroingLowLimit >> LogBytesPerWord)); match(Set dummy (ClearArray (Binary cnt base) zero)); effect(USE_KILL base, KILL cr); From 203378f623b4d683eaf44d4ad2fd0d91a42fc556 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Fri, 20 Nov 2026 08:47:25 +0000 Subject: [PATCH 25/95] 8397507: ProcessPath.c replace ALLOC und REALLOC macros Reviewed-by: prr, lucy --- .../native/libawt/java2d/loops/ProcessPath.c | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c b/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c index 6ddb1ee6b7a..3792d47bd33 100644 --- a/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c +++ b/src/java.desktop/share/native/libawt/java2d/loops/ProcessPath.c @@ -1726,17 +1726,6 @@ jboolean ProcessPath(ProcessHandler* hnd, return JNI_TRUE; } -/* TODO Add checking of the result of the malloc/realloc functions to handle - * out of memory error and don't leak earlier allocated data - */ - - -#define ALLOC(ptr, type, n) \ - ptr = (type *)malloc((n)*sizeof(type)) -#define REALLOC(ptr, type, n) \ - ptr = (type *)realloc(ptr, (n)*sizeof(type)) - - struct _Edge; typedef struct _Point { @@ -1986,12 +1975,18 @@ void FillPolygon(ProcessHandler* hnd, if (n <=1) return; - ALLOC(yHash, Point*, hashSize); + yHash = (Point**) malloc(hashSize * sizeof(Point*)); + if (yHash == NULL) return; + for (k = 0; k < hashSize; k++) { yHash[k] = NULL; } - ALLOC(active, Edge, n); + active = (Edge*) malloc(n * sizeof(Edge)); + if (active == NULL) { + free(yHash); + return; + } /* Creating double linked list (prev, next links) describing path order and * hash table with points which fall between scanlines. nextByY link is From 81eec8e3c730038eebee9f171aad18b484f3e711 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Fri, 20 Nov 2026 08:51:03 +0000 Subject: [PATCH 26/95] 8390009: FieldAccess and FieldModification events should be suppressed during strict initialization Reviewed-by: sspitsyn, cjplummer --- .../classes/build/tools/jdwpgen/AltNode.java | 17 +- src/hotspot/share/prims/jvmti.xml | 30 + src/hotspot/share/prims/jvmtiExport.cpp | 46 + src/java.se/share/data/jdwp/jdwp.spec | 31 + .../sun/jdi/event/AccessWatchpointEvent.java | 20 +- .../event/ModificationWatchpointEvent.java | 18 +- .../jdi/request/AccessWatchpointRequest.java | 14 +- .../ModificationWatchpointRequest.java | 13 +- .../WatchedField/WatchStrictInitFields.java | 910 ++++++++++++++++++ .../WatchedField/libWatchStrictInitFields.cpp | 199 ++++ .../FieldAccessModify/FieldAccessModify.java | 19 - .../jdi/valhalla/FieldWatchpointsTest.java | 6 +- 12 files changed, 1288 insertions(+), 35 deletions(-) create mode 100644 test/hotspot/jtreg/serviceability/jvmti/WatchedField/WatchStrictInitFields.java create mode 100644 test/hotspot/jtreg/serviceability/jvmti/WatchedField/libWatchStrictInitFields.cpp diff --git a/make/jdk/src/classes/build/tools/jdwpgen/AltNode.java b/make/jdk/src/classes/build/tools/jdwpgen/AltNode.java index 6999dc2caa5..ab04a67ba1c 100644 --- a/make/jdk/src/classes/build/tools/jdwpgen/AltNode.java +++ b/make/jdk/src/classes/build/tools/jdwpgen/AltNode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,11 +46,20 @@ void constrain(Context ctx) { } void document(PrintWriter writer) { - writer.println(""); + Node node = parent; + while (node != null && !(node instanceof CommandNode)) { + node = node.parent; + } + if (node == null) { + error("Alt must be enclosed in a Command"); + } + + // ID, e.g. JDWP_Event_Composite_eventKind_FieldModification + String id = node.context.whereC + "_" + select.typeNode.name() + "_" + name(); + writer.println(""); writer.println("" + indentElement(structIndent, - "Case " + nameNode.name - + " - if " + ((SelectNode)parent).typeNode.name + "" + + "Case " + name() + " - if " + select.typeNode.name() + "" + " is " + nameNode.value() + ":")); writer.println("" + comment() + " "); writer.println(""); diff --git a/src/hotspot/share/prims/jvmti.xml b/src/hotspot/share/prims/jvmti.xml index 8a5a1fc27a1..3a7b839db93 100644 --- a/src/hotspot/share/prims/jvmti.xml +++ b/src/hotspot/share/prims/jvmti.xml @@ -6629,6 +6629,36 @@ class C2 extends C1 implements I2 { + When preview features are enabled, the following restrictions apply to + and + events: +
    +
  • + An event for a watched instance field is not generated if the current + Java frame of the event thread is a constructor whose declaring class + or any of its superclasses has + + strictly-initializedPREVIEW instance fields and + slot 0 of the local variable array contains a reference to the object + containing the watched field. + For this purpose, the VM identifies the object being constructed by the + reference in slot 0 of the current constructor frame's local variable array. +
  • +
  • + An event for a watched static field is not generated when the class + declaring the field is being initialized by the event thread and the + class declares + + strictly-initializedPREVIEW static fields. +
  • +
+

+ API Note: + The instance fields of + + value classesPREVIEW are strictly-initialized. + Consequently, events for watched instance fields of a value class are + not generated for accesses or modifications directly in its constructors. diff --git a/src/hotspot/share/prims/jvmtiExport.cpp b/src/hotspot/share/prims/jvmtiExport.cpp index 28b7796ce32..009f1098c45 100644 --- a/src/hotspot/share/prims/jvmtiExport.cpp +++ b/src/hotspot/share/prims/jvmtiExport.cpp @@ -2279,6 +2279,46 @@ void JvmtiExport::post_field_access_by_jni(JavaThread *thread, oop obj, post_field_access(thread, method, address, klass, h_obj, fieldID); } +// Returns true if a field access or modification event should be skipped while the event +// thread is initializing a class with strictly-initialized static fields or executing a +// constructor with strictly-initialized instance fields in its declaring-class hierarchy. +static bool should_skip_field_event_during_strict_initialization(JavaThread* thread, Klass* field_klass, Handle object, jfieldID field) { + fieldDescriptor fd; + if (!JvmtiEnv::get_field_descriptor(field_klass, field, &fd)) { + assert(false, "should_skip_field_event_during_strict_initialization called with invalid fieldID"); + return true; + } + + // Skip field event for a static field when the class declaring the field is being initialized + // by the event thread and the class declares strictly-initialized static fields. + if (fd.is_static()) { + InstanceKlass* ik = fd.field_holder(); + return ik->has_strict_static_fields() && ik->is_reentrant_initialization(thread); + } + + // Skip an instance field event when the current Java frame is a constructor + // whose declaring class has strictly-initialized instance fields in its hierarchy + // and slot 0 contains a reference to the object containing the watched field. + ResourceMark rm(thread); + RegisterMap reg_map(thread, + RegisterMap::UpdateMap::skip, + RegisterMap::ProcessFrames::skip, + RegisterMap::WalkContinuation::skip); + javaVFrame* jvf = thread->last_java_vframe(®_map); + if (jvf != nullptr) { + Method* method = jvf->method(); + if (method->is_object_constructor() && method->method_holder()->has_strict_instance_fields_in_hierarchy()) { + StackValueCollection* locals = jvf->locals(); + if (!locals->is_empty()) { + StackValue* receiver = locals->at(0); + return receiver->type() == T_OBJECT && !receiver->obj_is_scalar_replaced() && receiver->get_obj()() == object(); + } + } + } + + return false; +} + void JvmtiExport::post_field_access(JavaThread *thread, Method* method, address location, Klass* field_klass, Handle object, jfieldID field) { @@ -2292,6 +2332,9 @@ void JvmtiExport::post_field_access(JavaThread *thread, Method* method, if (thread->should_hide_jvmti_events()) { return; } + if (should_skip_field_event_during_strict_initialization(thread, field_klass, object, field)) { + return; + } EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_ACCESS, ("[%s] Trg Field Access event triggered", JvmtiTrace::safe_get_thread_name(thread))); @@ -2462,6 +2505,9 @@ void JvmtiExport::post_field_modification(JavaThread *thread, Method* method, if (thread->should_hide_jvmti_events()) { return; } + if (should_skip_field_event_during_strict_initialization(thread, field_klass, object, field)) { + return; + } EVT_TRIG_TRACE(JVMTI_EVENT_FIELD_MODIFICATION, ("[%s] Trg Field Modification event triggered", diff --git a/src/java.se/share/data/jdwp/jdwp.spec b/src/java.se/share/data/jdwp/jdwp.spec index 1d4b73cf8aa..38fa560fe26 100644 --- a/src/java.se/share/data/jdwp/jdwp.spec +++ b/src/java.se/share/data/jdwp/jdwp.spec @@ -2359,6 +2359,15 @@ JDWP "Java(tm) Debug Wire Protocol" "from the target VM. The two exceptions to this are the VM Start Event and " "the VM Death Event which are automatically generated events - see " "Composite Command for further details." + "

" + "When preview features are enabled in the target VM, " + "Field Access and " + "Field Modification " + "events are not generated during construction of objects with " + "" + "strictly-initializedPREVIEW instance fields or initialization " + "of classes with strictly-initialized static fields as detailed in the " + "event descriptions." (Out (byte eventKind "Event kind to request. " "See JDWP.EventKind " @@ -3152,6 +3161,17 @@ JDWP "Java(tm) Debug Wire Protocol" "Notification of a field access in the target VM. " "Field modifications " "are not considered field accesses. " + "

" + "When preview features are enabled in the target VM, this event " + "is not generated for an instance field if the event thread is " + "executing a constructor for the object containing the field and " + "the constructor's declaring class or any of its superclasses has " + "" + "strictly-initializedPREVIEW instance fields. " + "This event is also not generated for a static field when the thread " + "accessing the field is initializing its declaring class and that " + "class declares strictly-initialized static fields." + "

" "Requires canWatchFieldAccess capability - see " "CapabilitiesNew." @@ -3167,6 +3187,17 @@ JDWP "Java(tm) Debug Wire Protocol" ) (Alt FieldModification=JDWP.EventKind.FIELD_MODIFICATION "Notification of a field modification in the target VM. " + "

" + "When preview features are enabled in the target VM, this event " + "is not generated for an instance field if the event thread is " + "executing a constructor for the object containing the field and " + "the constructor's declaring class or any of its superclasses has " + "" + "strictly-initializedPREVIEW instance fields. " + "This event is also not generated for a static field when the thread " + "modifying the field is initializing its declaring class and that " + "class declares strictly-initialized static fields." + "

" "Requires canWatchFieldModification capability - see " "CapabilitiesNew." diff --git a/src/jdk.jdi/share/classes/com/sun/jdi/event/AccessWatchpointEvent.java b/src/jdk.jdi/share/classes/com/sun/jdi/event/AccessWatchpointEvent.java index b9ed43b1ba2..49d81fc68ff 100644 --- a/src/jdk.jdi/share/classes/com/sun/jdi/event/AccessWatchpointEvent.java +++ b/src/jdk.jdi/share/classes/com/sun/jdi/event/AccessWatchpointEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,11 +26,25 @@ package com.sun.jdi.event; import com.sun.jdi.VirtualMachine; +import com.sun.jdi.request.AccessWatchpointRequest; /** - * Notification of a field access in the target VM. Field modifications - * are not considered field accesses. + * Notification of a field access in the target VM. + *

+ * This notification is not generated for an instance field of {@code this} + * when executing a constructor whose declaring class or any of its superclasses + * has {@linkplain java.lang.reflect.Field#isStrictInit() strictly-initialized} + * instance fields. It is also not generated for a static field when the thread + * accessing the field is initializing its declaring class and that class + * declares strictly-initialized static fields. + *

+ * Field modifications are not considered field accesses. * + * @apiNote The instance fields of {@linkplain Class#isValue() value classes} are + * strictly-initialized. Consequently, events for watched instance fields of a value + * class are not generated for accesses or modifications directly in its constructors. + * + * @see AccessWatchpointRequest * @see EventQueue * @see VirtualMachine * diff --git a/src/jdk.jdi/share/classes/com/sun/jdi/event/ModificationWatchpointEvent.java b/src/jdk.jdi/share/classes/com/sun/jdi/event/ModificationWatchpointEvent.java index a89d1d09ecc..b01d8dbe891 100644 --- a/src/jdk.jdi/share/classes/com/sun/jdi/event/ModificationWatchpointEvent.java +++ b/src/jdk.jdi/share/classes/com/sun/jdi/event/ModificationWatchpointEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,12 +30,22 @@ import com.sun.jdi.request.ModificationWatchpointRequest; /** - * Notification of a field modification in the - * target VM. + * Notification of a field modification in the target VM. + *

+ * This notification is not generated for an instance field of {@code this} + * when executing a constructor whose declaring class or any of its superclasses + * has {@linkplain java.lang.reflect.Field#isStrictInit() strictly-initialized} + * instance fields. It is also not generated for a static field when the thread + * modifying the field is initializing its declaring class and that class + * declares strictly-initialized static fields. * + * @apiNote The instance fields of {@linkplain Class#isValue() value classes} are + * strictly-initialized. Consequently, events for watched instance fields of a value + * class are not generated for accesses or modifications directly in its constructors. + * + * @see ModificationWatchpointRequest * @see EventQueue * @see VirtualMachine - * @see ModificationWatchpointRequest * * @author Robert Field * @since 1.3 diff --git a/src/jdk.jdi/share/classes/com/sun/jdi/request/AccessWatchpointRequest.java b/src/jdk.jdi/share/classes/com/sun/jdi/request/AccessWatchpointRequest.java index dae64d66ec6..a9ec7940c47 100644 --- a/src/jdk.jdi/share/classes/com/sun/jdi/request/AccessWatchpointRequest.java +++ b/src/jdk.jdi/share/classes/com/sun/jdi/request/AccessWatchpointRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,9 +46,21 @@ * The collection of existing watchpoints is * managed by the {@link EventRequestManager}. *

+ * A notification is not generated for an instance field of {@code this} + * when executing a constructor whose declaring class or any of its superclasses + * has {@linkplain java.lang.reflect.Field#isStrictInit() strictly-initialized} + * instance fields. A notification is also not generated for a static field when + * the thread accessing the field is initializing its declaring class and that + * class declares strictly-initialized static fields. + *

* Note that the modification * of a Field is not considered an access. * + * @apiNote The instance fields of {@linkplain Class#isValue() value classes} are + * strictly-initialized. Consequently, events for watched instance fields of a value + * class are not generated for accesses or modifications directly in its constructors. + * + * @see AccessWatchpointEvent * @see ModificationWatchpointRequest * @see EventQueue * @see EventRequestManager diff --git a/src/jdk.jdi/share/classes/com/sun/jdi/request/ModificationWatchpointRequest.java b/src/jdk.jdi/share/classes/com/sun/jdi/request/ModificationWatchpointRequest.java index 91c285da9a9..5f0b0178e7c 100644 --- a/src/jdk.jdi/share/classes/com/sun/jdi/request/ModificationWatchpointRequest.java +++ b/src/jdk.jdi/share/classes/com/sun/jdi/request/ModificationWatchpointRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,6 +45,17 @@ * will be placed on the {@link EventQueue EventQueue}. * The collection of existing watchpoints is * managed by the {@link EventRequestManager}. + *

+ * A notification is not generated for an instance field of {@code this} + * when executing a constructor whose declaring class or any of its superclasses + * has {@linkplain java.lang.reflect.Field#isStrictInit() strictly-initialized} + * instance fields. A notification is also not generated for a static field when + * the thread modifying the field is initializing its declaring class and that + * class declares strictly-initialized static fields. + * + * @apiNote The instance fields of {@linkplain Class#isValue() value classes} are + * strictly-initialized. Consequently, events for watched instance fields of a value + * class are not generated for accesses or modifications directly in its constructors. * * @see ModificationWatchpointEvent * @see AccessWatchpointRequest diff --git a/test/hotspot/jtreg/serviceability/jvmti/WatchedField/WatchStrictInitFields.java b/test/hotspot/jtreg/serviceability/jvmti/WatchedField/WatchStrictInitFields.java new file mode 100644 index 00000000000..9e88285200d --- /dev/null +++ b/test/hotspot/jtreg/serviceability/jvmti/WatchedField/WatchStrictInitFields.java @@ -0,0 +1,910 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8390009 + * @summary Test FieldAccess/FieldModification events sent for fields in objects and + * classes with strictly-initialized fields + * @enablePreview + * @library /test/lib + * @build ${test.main.class} + * @run driver jdk.test.lib.helpers.StrictProcessor + * WatchStrictInitFields$InstanceField2$TestClass + * WatchStrictInitFields$InstanceField3$TestClass + * WatchStrictInitFields$InstanceField4$SuperClass + * WatchStrictInitFields$InstanceField5$TestClass + * WatchStrictInitFields$InstanceField6$TestClass + * WatchStrictInitFields$StaticField2$TestClass + * WatchStrictInitFields$StaticField3$TestClass + * WatchStrictInitFields$StaticField4$TestClass + * @run junit/othervm/native --enable-native-access=ALL-UNNAMED -agentlib:WatchStrictInitFields ${test.main.class} + */ + +import java.lang.invoke.MethodHandles; +import jdk.test.lib.helpers.StrictInit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.BeforeAll; +import static org.junit.jupiter.api.Assertions.*; + +class WatchStrictInitFields { + + /** + * Test events posted from the constructor of a class with no strict fields. + */ + @Nested + class InstanceField1 { + class TestClass { + int x; + + TestClass(int v1) { + x = v1; // modification event + super(); + assertEquals(v1, x); // access event + } + + TestClass(int v1, int v2) { + this(v1); + x = v2; // modification event + assertEquals(v2, x); // access event + } + + TestClass(int v1, int v2, int v3) { + this(v1, v2); + x(v3); // this-escape + assertEquals(v3, x()); // this-escape + } + + void x(int newX) { + x = newX; // modification event + } + + int x() { + return x; // access event + } + } + + @Test + void testFieldAccess() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100); + assertEquals(1, modCount()); + assertEquals(1, accessCount()); + + // modify after construction + obj.x = 200; + assertEquals(2, modCount()); + assertEquals(1, accessCount()); + + // access after construction + assertEquals(200, obj.x); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + + // mutator method + obj.x(300); + assertEquals(3, modCount()); + assertEquals(2, accessCount()); + + // accessor method + assertEquals(300, obj.x()); + assertEquals(3, modCount()); + assertEquals(3, accessCount()); + } + } + + @Test + void testConstructorChaining() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100, 101); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + } + } + + @Test + void testThisEscape() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100, 101, 102); + assertEquals(3, modCount()); + assertEquals(3, accessCount()); + } + } + } + + /** + * Test events posted from the constructor of a class with a strict field. + */ + @Nested + class InstanceField2 { + class TestClass { + @StrictInit int x; + + TestClass(int v1) { + x = v1; // modification event not sent + super(); + assertEquals(v1, x); // access event not sent + } + + TestClass(int v1, int v2) { + this(v1); + x = v2; // modification event not sent + assertEquals(v2, x); // access event not sent + } + + TestClass(int v1, int v2, int v3) { + this(v1, v2); + x(v3); // this-escape + assertEquals(v3, x()); // this-escape + } + + void x(int newX) { + x = newX; // modification event + } + + int x() { + return x; // access event + } + } + + @Test + void testFieldAccess() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + + // modify after construction + obj.x = 200; + assertEquals(1, modCount()); + assertEquals(0, accessCount()); + + // access after construction + assertEquals(200, obj.x); + assertEquals(1, modCount()); + assertEquals(1, accessCount()); + + // mutator method + obj.x(300); + assertEquals(2, modCount()); + assertEquals(1, accessCount()); + + // accessor method + assertEquals(300, obj.x()); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + } + } + + @Test + void testConstructorChaining() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100, 200); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + } + } + + @Test + void testThisEscape() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100, 200, 300); + assertEquals(1, modCount()); + assertEquals(1, accessCount()); + } + } + } + + /** + * Test events posted from the constructor of a class with a strict field and a + * non-strict field. + */ + @Nested + class InstanceField3 { + class TestClass { + int x; + @StrictInit int y; + + TestClass(int v1, int v2) { + x = v1; // modification event not sent + y = v2; // modification event not sent + super(); + assertEquals(v1, x); // access event not sent + assertEquals(v2, y); // access event not sent + } + + TestClass(int v1, int v2, int v3, int v4) { + this(v1, v2); + x = v3; // modification event not sent + y = v4; // modification event not sent + assertEquals(v3, x); // access event not sent + assertEquals(v4, y); // access event not sent + } + + TestClass(int v1, int v2, int v3, int v4, int v5, int v6) { + this(v1, v2, v3, v4); + x(v5); // this-escape + assertEquals(v5, x()); // this-escape + y(v6); // this-escape + assertEquals(v6, y()); // this-escape + } + + void x(int newX) { + x = newX; // modification event + } + + int x() { + return x; // access event + } + + void y(int newY) { + y = newY; // modification event + } + + int y() { + return y; // access event + } + } + + @Test + void testFieldAccess() { + try (var _ = watch(TestClass.class, "x"); + var _ = watch(TestClass.class, "y")) { + + var obj = new TestClass(100, 101); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + + // modify after construction + obj.x = 200; + assertEquals(1, modCount()); + assertEquals(0, accessCount()); + obj.y = 201; + assertEquals(2, modCount()); + assertEquals(0, accessCount()); + + // access after construction + assertEquals(200, obj.x); + assertEquals(2, modCount()); + assertEquals(1, accessCount()); + assertEquals(201, obj.y); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + + // mutator methods + obj.x(300); + assertEquals(3, modCount()); + assertEquals(2, accessCount()); + obj.y(301); + assertEquals(4, modCount()); + assertEquals(2, accessCount()); + + // accessor methods + assertEquals(300, obj.x()); + assertEquals(4, modCount()); + assertEquals(3, accessCount()); + assertEquals(301, obj.y()); + assertEquals(4, modCount()); + assertEquals(4, accessCount()); + } + } + + @Test + void testConstructorChaining() { + try (var _ = watch(TestClass.class, "x"); + var _ = watch(TestClass.class, "y")) { + + var obj = new TestClass(100, 101, 200, 201); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + } + } + + @Test + void testThisEscape() { + try (var _ = watch(TestClass.class, "x"); + var _ = watch(TestClass.class, "y")) { + + var obj = new TestClass(100, 101, 200, 201, 300, 301); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + } + } + } + + /** + * Test events posted from the constructor of a class with a strict field + * declared in a super class. + */ + @Nested + class InstanceField4 { + class SuperClass { + @StrictInit int x; + + SuperClass(int v1) { + x = v1; // modification event not sent + super(); + assertEquals(v1, x); // access event not sent + } + + SuperClass(int v1, int v2) { + this(v1); + x = v2; // modification event not sent + assertEquals(v2, x); // access event not sent + } + + void x(int newX) { + x = newX; // modification event + } + + int x() { + return x; // access event + } + } + + class TestClass extends SuperClass { + TestClass(int v1) { + super(v1); + } + + TestClass(int v1, int v2, int v3) { + super(v1, v2); + x = v3; // modification event not sent + assertEquals(v3, x); // access event not sent + } + } + + @Test + void testFieldAccess() { + try (var _ = watch(SuperClass.class, "x")) { + var obj = new TestClass(100); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + + // modify after construction + obj.x = 200; + assertEquals(1, modCount()); + assertEquals(0, accessCount()); + + // access after construction + assertEquals(200, obj.x); + assertEquals(1, modCount()); + assertEquals(1, accessCount()); + + // mutator method + obj.x(300); + assertEquals(2, modCount()); + assertEquals(1, accessCount()); + + // accessor method + assertEquals(300, obj.x()); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + } + } + + @Test + void testConstructorChaining() { + try (var _ = watch(SuperClass.class, "x")) { + var obj = new TestClass(100, 200, 300); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + } + } + } + + /** + * Test events posted from the constructor of a class with a strict field + * declared in a subclass. + */ + @Nested + class InstanceField5 { + class SuperClass { + SuperClass(int value) { + var thisObject = (TestClass) this; + thisObject.x = value; // modification event sent + assertEquals(value, thisObject.x); // access event sent + } + } + + class TestClass extends SuperClass { + @StrictInit int x; + + TestClass(int v1, int v2) { + x = v1; // modification event not sent + super(v2); + assertEquals(v2, x); // access event not sent + } + + TestClass(int v1, int v2, int v3) { + this(v1, v2); + x = v3; // modification event not sent + assertEquals(v3, x); // access event not sent + } + + void x(int newX) { + x = newX; // modification event + } + + int x() { + return x; // access event + } + } + + @Test + void testFieldAccess() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100, 200); + assertEquals(1, modCount()); + assertEquals(1, accessCount()); + + // modify after construction + obj.x = 300; + assertEquals(2, modCount()); + assertEquals(1, accessCount()); + + // access after construction + assertEquals(300, obj.x); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + + // mutator method + obj.x(400); + assertEquals(3, modCount()); + assertEquals(2, accessCount()); + + // accessor method + assertEquals(400, obj.x()); + assertEquals(3, modCount()); + assertEquals(3, accessCount()); + } + } + + @Test + void testThisEscape() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100, 200, 300); + assertEquals(1, modCount()); + assertEquals(1, accessCount()); + } + } + } + + /** + * Test events posted from the constructor of the class with a strict field when + * construction posts modification or access events for a class no strict fields. + */ + @Nested + class InstanceField6 { + class Box { + int value; + Box(int value) { + this.value = value; // modification event + super(); + assertEquals(value, this.value); // access event + } + } + + class TestClass { + @StrictInit Box x; + + TestClass(int v1) { + x = new Box(v1); // no modification event sent + super(); + var _ = x; // no access event sent + } + + TestClass(int v1, int v2) { + this(v1); + x = new Box(v2); // no modification event sent + var _ = x; // no access event sent + } + + TestClass(int v1, int v2, int v3) { + this(v1, v2); + x(v3); // this-escape + assertEquals(v3, x()); // this-escape + } + + void x(int v3) { + x = new Box(v3); // 2 x modification events + } + + int x() { + return x.value; // 2 x access events + } + } + + @Test + void testFieldAccess() { + try (var _ = watch(Box.class, "value"); + var _ = watch(TestClass.class, "x")) { + + var obj = new TestClass(100); + assertEquals(1, modCount()); // putfield Box.value + assertEquals(1, accessCount()); // getfield Box.value + + // modify after construction + obj.x = new Box(200); + assertEquals(3, modCount()); // putfield Box.value && obj.x + assertEquals(2, accessCount()); // getfield Box.value + + // access after construction + var _ = obj.x; + assertEquals(3, modCount()); + assertEquals(3, accessCount()); // getfield obj.x + + // mutator method + obj.x(300); + assertEquals(5, modCount()); // putfield Box.value && obj.x + assertEquals(4, accessCount()); // getfield Box.value + + // accessor method + assertEquals(300, obj.x()); // getfield Box.value && obj.x + assertEquals(5, modCount()); + assertEquals(6, accessCount()); + } + } + + @Test + void testConstructorChaining() { + try (var _ = watch(Box.class, "value"); + var _ = watch(TestClass.class, "x")) { + + var obj = new TestClass(100, 200); + assertEquals(2, modCount()); // 2 * putfield Box.value + assertEquals(2, accessCount()); // 2 * getfield Box.value + } + } + + @Test + void testThisEscape() { + try (var _ = watch(Box.class, "value"); + var _ = watch(TestClass.class, "x")) { + + var obj = new TestClass(100, 200, 300); + assertEquals(4, modCount()); // 3 * putfield Box.value + x(int) + assertEquals(5, accessCount()); // 4 * getfield Box.value + x() + } + } + } + + /** + * Test events posted from the constructor of a value class. + */ + @Nested + class ValueClass { + value class TestClass { + int x; + + TestClass(int v1) { + x = v1; // modification event not sent + super(); + assertEquals(v1, x); // access event not sent + } + + int x() { + return x; // access event + } + } + + @BeforeAll() + static void verifyPreconditions() throws Exception { + assertTrue(TestClass.class.getDeclaredField("x").isStrictInit(), + "expected to be strict field"); + } + + @Test + void testFieldAccess() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + + // access after construction + assertEquals(100, obj.x); + assertEquals(0, modCount()); + assertEquals(1, accessCount()); + + // accessor method + assertEquals(100, obj.x()); + assertEquals(0, modCount()); + assertEquals(2, accessCount()); + } + } + } + + /** + * Test events posted from the constructor of a record class. + */ + @Nested + class RecordClass { + record TestClass(int x) { + TestClass(int x) { + this.x = x; // modification event not sent + super(); + assertEquals(x, this.x); // access event not sent + } + } + + @BeforeAll() + static void verifyPreconditions() throws Exception { + assertTrue(TestClass.class.getDeclaredField("x").isStrictInit(), + "expected to be strict field"); + } + + @Test + void testFieldAccess() { + try (var _ = watch(TestClass.class, "x")) { + var obj = new TestClass(100); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + + // access after construction + assertEquals(100, obj.x); + assertEquals(0, modCount()); + assertEquals(1, accessCount()); + + // (compiler-generated) accessor method + assertEquals(100, obj.x()); + assertEquals(0, modCount()); + assertEquals(2, accessCount()); + } + } + } + + /** + * Test events posted from the class initializer of a class with no strict static fields. + */ + @Nested + class StaticField1 { + class TestClass { + static int x; + + static { + x = 100; // modification event + assertEquals(100, x); // access event + postSet(200); + x = 300; // modification event + assertEquals(300, x); // access event + } + + static void postSet(int newX) { + x = newX; // modification event + assertEquals(newX, x); // access event + } + } + + @Test + void testFieldAccess() throws Exception { + try (var _ = watch(TestClass.class, "x")) { + MethodHandles.lookup().ensureInitialized(TestClass.class); + assertEquals(3, modCount()); + assertEquals(3, accessCount()); + + // modify after class initializer has run + TestClass.x = 400; + assertEquals(4, modCount()); + assertEquals(3, accessCount()); + + // access after class initializer has run + assertEquals(400, TestClass.x); + assertEquals(4, modCount()); + assertEquals(4, accessCount()); + } + } + } + + /** + * Test events posted from the class initializer of a class with a strict static field. + */ + @Nested + class StaticField2 { + class TestClass { + @StrictInit static int x; + + static { + x = 100; // modification event not sent + assertEquals(100, x); // access event not sent + postSet(200); + x = 300; // modification event not sent + assertEquals(300, x); // access event not sent + } + + static void postSet(int newX) { + x = newX; // modification event not sent + assertEquals(newX, x); // access event not sent + } + } + + @Test + void testFieldAccess() throws Exception { + try (var _ = watch(TestClass.class, "x")) { + MethodHandles.lookup().ensureInitialized(TestClass.class); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + + // modify after class initializer has run + TestClass.x = 400; + assertEquals(1, modCount()); + assertEquals(0, accessCount()); + + // access after class initializer has run + assertEquals(400, TestClass.x); + assertEquals(1, modCount()); + assertEquals(1, accessCount()); + } + } + } + + /** + * Test events posted from the class initializer of a class with a strict static + * field and a non-strict static field. + */ + @Nested + class StaticField3 { + class TestClass { + static int x; + @StrictInit static int y; + + static { + x = 100; // modification event not sent + y = 101; // modification event not sent + assertEquals(100, x); // access event not sent + assertEquals(101, y); // access event not sent + postSet(200, 201); + x = 300; // modification event not sent + y = 301; // modification event not sent + assertEquals(300, x); // access event not sent + assertEquals(301, y); // access event not sent + } + + static void postSet(int newX, int newY) { + x = newX; // modification event not sent + y = newY; // modification event not sent + assertEquals(newX, x); // access event not sent + assertEquals(newY, y); // access event not sent + } + } + + @Test + void testFieldAccess() throws Exception { + try (var _ = watch(TestClass.class, "x"); + var _ = watch(TestClass.class, "y")) { + MethodHandles.lookup().ensureInitialized(TestClass.class); + assertEquals(0, modCount()); + assertEquals(0, accessCount()); + + // modify after class initializer has run + TestClass.x = 400; + assertEquals(1, modCount()); + assertEquals(0, accessCount()); + TestClass.y = 400; + assertEquals(2, modCount()); + assertEquals(0, accessCount()); + + // access after class initializer has run + assertEquals(400, TestClass.x); + assertEquals(2, modCount()); + assertEquals(1, accessCount()); + assertEquals(400, TestClass.y); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + } + } + } + + /** + * Test events posted from the class initializer of a class with a strict static + * field and where the initializer causes another class (no strict fields) to be + * initialized. + */ + @Nested + class StaticField4 { + class TestClass { + @StrictInit static int x; + + static { + x = 100; // modification event not sent + assertEquals(100, x); // access event not sent + + // force OtherClass class initializer to execute + try { + MethodHandles.lookup().ensureInitialized(OtherClass.class); + } catch (Exception e) { + fail(e); + } + } + } + + class OtherClass { + static int y; + static { + y = 100; // modification event + assertEquals(100, y); // access event + } + } + + @Test + void testFieldAccess() throws Exception { + try (var _ = watch(TestClass.class, "x"); + var _ = watch(OtherClass.class, "y")) { + MethodHandles.lookup().ensureInitialized(TestClass.class); + assertEquals(1, modCount()); // putstatic OtherClass.y + assertEquals(1, accessCount()); // getstatic OtherClass.y + + // modify after class initializer has run + TestClass.x = 200; + assertEquals(2, modCount()); + assertEquals(1, accessCount()); + + // access after class initializer has run + assertEquals(200, TestClass.x); + assertEquals(2, modCount()); + assertEquals(2, accessCount()); + } + } + } + + record Watch(Class clazz, long fieldID) implements AutoCloseable { + @Override + public void close() { + clearFieldAccessWatch(clazz, fieldID); + clearFieldModificationWatch(clazz, fieldID); + } + } + + Watch watch(Class clazz, String fieldName) { + var _ = clazz.getDeclaredFields(); // ensure class is prepared + long fieldID = fieldID(clazz, fieldName); + setFieldModificationWatch(clazz, fieldID); + setFieldAccessWatch(clazz, fieldID); + resetModCount(); + resetAccessCount(); + return new Watch(clazz, fieldID); + } + + /** + * Return the jfieldID for a static or instance field. This function does not + * cause the class to be initialized. + */ + private static native long fieldID(Class clazz, String fieldName); + + /** + * JVMTI SetFieldModificationWatch, SetFieldAccessWatch, ClearFieldModificationWatch + * and ClearFieldAccessWatch. + */ + private static native void setFieldModificationWatch(Class clazz, long fieldID); + private static native void clearFieldModificationWatch(Class clazz, long fieldID); + private static native void setFieldAccessWatch(Class clazz, long fieldID); + private static native void clearFieldAccessWatch(Class clazz, long fieldID); + + /** + * Counters. + */ + private static native void resetModCount(); + private static native void resetAccessCount(); + private static native int modCount(); + private static native int accessCount(); +} diff --git a/test/hotspot/jtreg/serviceability/jvmti/WatchedField/libWatchStrictInitFields.cpp b/test/hotspot/jtreg/serviceability/jvmti/WatchedField/libWatchStrictInitFields.cpp new file mode 100644 index 00000000000..3d7daa9fa3e --- /dev/null +++ b/test/hotspot/jtreg/serviceability/jvmti/WatchedField/libWatchStrictInitFields.cpp @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include +#include + +#include "jni.h" +#include "jvmti.h" + +static jvmtiEnv* jvmti; + +static jint mod_count; +static jint access_count; + +// Prints the class and field that triggered a watch event. +// (Prints to stderr so that it inlines with the JUnit test output) +static void print_watched_field_event(const char* event_name, jclass field_klass, jfieldID field_id) { + char* class_signature = nullptr; + char* field_name = nullptr; + jvmtiError class_error = jvmti->GetClassSignature(field_klass, &class_signature, nullptr); + jvmtiError field_error = jvmti->GetFieldName(field_klass, field_id, &field_name, nullptr, nullptr); + if (class_error == JVMTI_ERROR_NONE && field_error == JVMTI_ERROR_NONE) { + const char* class_name = class_signature; + size_t class_name_len = strlen(class_signature); + if (class_name_len >= 2 && class_signature[0] == 'L' && class_signature[class_name_len - 1] == ';') { + class_name++; + class_name_len -= 2; + } + fprintf(stderr, " %s: %.*s.%s\n", event_name, static_cast(class_name_len), class_name, field_name); + } + if (class_signature != nullptr) { + jvmti->Deallocate(reinterpret_cast(class_signature)); + } + if (field_name != nullptr) { + jvmti->Deallocate(reinterpret_cast(field_name)); + } +} + +// FieldModification callback. +static void JNICALL field_modification(jvmtiEnv*, JNIEnv*, jthread, jmethodID, jlocation, + jclass field_klass, jobject, jfieldID field_id, char, jvalue) { + print_watched_field_event("FieldModification", field_klass, field_id); + mod_count++; +} + +// FieldAccess callback. +static void JNICALL field_access(jvmtiEnv*, JNIEnv*, jthread, jmethodID, jlocation, + jclass field_klass, jobject, jfieldID field_id) { + print_watched_field_event("FieldAccess", field_klass, field_id); + access_count++; +} + +extern "C" { + +// Initializes the JVMTI agent and enables field watch events. +JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { + if (vm->GetEnv((void**)&jvmti, JVMTI_VERSION) != JNI_OK) { + return JNI_ERR; + } + + jvmtiCapabilities capabilities; + memset(&capabilities, 0, sizeof(capabilities)); + capabilities.can_generate_field_access_events = 1; + capabilities.can_generate_field_modification_events = 1; + if (jvmti->AddCapabilities(&capabilities) != JVMTI_ERROR_NONE) { + return JNI_ERR; + } + + jvmtiEventCallbacks callbacks; + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.FieldAccess = field_access; + callbacks.FieldModification = field_modification; + if (jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)) != JVMTI_ERROR_NONE) { + return JNI_ERR; + } + if (jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_ACCESS, nullptr) != JVMTI_ERROR_NONE) { + return JNI_ERR; + } + if (jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_MODIFICATION, nullptr) != JVMTI_ERROR_NONE) { + return JNI_ERR; + } + + return JNI_OK; +} + +// Returns the JNI FieldID for a field without initializing its class. +JNIEXPORT jlong JNICALL +Java_WatchStrictInitFields_fieldID(JNIEnv* env, jclass, jclass field_klass, jstring field_name) { + const char* wanted_name = env->GetStringUTFChars(field_name, nullptr); + if (wanted_name == nullptr) { + return 0; // pending OOME + } + + jint field_count = 0; + jfieldID* fields = nullptr; + jvmtiError error = jvmti->GetClassFields(field_klass, &field_count, &fields); + + jfieldID result = nullptr; + if (error == JVMTI_ERROR_NONE) { + for (jint i = 0; i < field_count; i++) { + char* name = nullptr; + error = jvmti->GetFieldName(field_klass, fields[i], &name, nullptr, nullptr); + if (error != JVMTI_ERROR_NONE) { + break; + } + bool found = (strcmp(name, wanted_name) == 0); + jvmti->Deallocate(reinterpret_cast(name)); + if (found) { + result = fields[i]; + break; + } + } + } + + if (fields != nullptr) { + jvmti->Deallocate(reinterpret_cast(fields)); + } + env->ReleaseStringUTFChars(field_name, wanted_name); + + if (error != JVMTI_ERROR_NONE || result == nullptr) { + env->FatalError("GetClassFields, GetFieldName, or field lookup failed"); + } + + return static_cast(reinterpret_cast(result)); +} + +JNIEXPORT void JNICALL +Java_WatchStrictInitFields_setFieldModificationWatch(JNIEnv* env, jclass, jclass field_klass, jlong id) { + jfieldID field_id = reinterpret_cast(static_cast(id)); + if (jvmti->SetFieldModificationWatch(field_klass, field_id) != JVMTI_ERROR_NONE) { + env->FatalError("SetFieldModificationWatch failed"); + } +} + +JNIEXPORT void JNICALL +Java_WatchStrictInitFields_clearFieldModificationWatch(JNIEnv* env, jclass, jclass field_klass, jlong id) { + jfieldID field_id = reinterpret_cast(static_cast(id)); + if (jvmti->ClearFieldModificationWatch(field_klass, field_id) != JVMTI_ERROR_NONE) { + env->FatalError("ClearFieldModificationWatch failed"); + } +} + +JNIEXPORT void JNICALL +Java_WatchStrictInitFields_setFieldAccessWatch(JNIEnv* env, jclass, jclass field_klass, jlong id) { + jfieldID field_id = reinterpret_cast(static_cast(id)); + if (jvmti->SetFieldAccessWatch(field_klass, field_id) != JVMTI_ERROR_NONE) { + env->FatalError("SetFieldAccessWatch failed"); + } +} + +JNIEXPORT void JNICALL +Java_WatchStrictInitFields_clearFieldAccessWatch(JNIEnv* env, jclass, jclass field_klass, jlong id) { + jfieldID field_id = reinterpret_cast(static_cast(id)); + if (jvmti->ClearFieldAccessWatch(field_klass, field_id) != JVMTI_ERROR_NONE) { + env->FatalError("ClearFieldAccessWatch failed"); + } +} + +JNIEXPORT jint JNICALL +Java_WatchStrictInitFields_modCount(JNIEnv*, jclass) { + return mod_count; +} + +JNIEXPORT void JNICALL +Java_WatchStrictInitFields_resetModCount(JNIEnv*, jclass) { + mod_count = 0; +} + +JNIEXPORT jint JNICALL +Java_WatchStrictInitFields_accessCount(JNIEnv*, jclass) { + return access_count; +} + +JNIEXPORT void JNICALL +Java_WatchStrictInitFields_resetAccessCount(JNIEnv*, jclass) { + access_count = 0; +} + +} // extern "C" diff --git a/test/hotspot/jtreg/serviceability/jvmti/valhalla/FieldAccessModify/FieldAccessModify.java b/test/hotspot/jtreg/serviceability/jvmti/valhalla/FieldAccessModify/FieldAccessModify.java index 9ae3037774a..13dc430afc3 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/valhalla/FieldAccessModify/FieldAccessModify.java +++ b/test/hotspot/jtreg/serviceability/jvmti/valhalla/FieldAccessModify/FieldAccessModify.java @@ -129,29 +129,10 @@ public static void main(String[] args) throws Exception { public boolean valueClass_fld2_access; }); - test("ValueClass (modify)", () -> { - ValueClass obj = new ValueClass(1, 1); - }, new TestResult() { - public boolean valueClass_fld1_modify; - public boolean valueClass_fld2_modify; - }); - test("InstanceHolder (modify)", () -> { InstanceHolder obj = new InstanceHolder(10); }, new TestResult() { public boolean instanceHolder_fld1_modify; - // ValueClass fields should be modified too - boolean valueClass_fld1_modify; - public boolean valueClass_fld2_modify; - }); - - test("ValueHolder (modify)", () -> { - ValueHolder obj = new ValueHolder(11); - }, new TestResult() { - public boolean valueHolder_fld1_modify; - // ValueClass fields should be modified too - public boolean valueClass_fld1_modify; - public boolean valueClass_fld2_modify; }); } diff --git a/test/jdk/com/sun/jdi/valhalla/FieldWatchpointsTest.java b/test/jdk/com/sun/jdi/valhalla/FieldWatchpointsTest.java index bcdb32bc569..3333758f4af 100644 --- a/test/jdk/com/sun/jdi/valhalla/FieldWatchpointsTest.java +++ b/test/jdk/com/sun/jdi/valhalla/FieldWatchpointsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -121,13 +121,13 @@ protected void runTests() throws Exception { Field watchField = valueClass.fieldByName("v"); WatchpointRequest request = eventRequestManager().createModificationWatchpointRequest(watchField); - testCases.add(new TestCase("modify", 1, request)); // instanceField ctor + testCases.add(new TestCase("modify", 0, request)); // no modify events during construction request = eventRequestManager().createAccessWatchpointRequest(watchField); testCases.add(new TestCase("access", 2, request)); // staticField, instanceField request = eventRequestManager().createModificationWatchpointRequest(instanceValueField); - testCases.add(new TestCase("modify flat", 1, request)); // instanceField ctor + testCases.add(new TestCase("modify flat", 0, request)); // no modify events during construction request = eventRequestManager().createAccessWatchpointRequest(instanceValueField); testCases.add(new TestCase("access flat", 1, request)); // println(targ.instanceField.v) From 7ea63c74b735111e9db31b43e51dffbb38780bf8 Mon Sep 17 00:00:00 2001 From: Nikita Tsarev Date: Fri, 20 Nov 2026 08:57:06 +0000 Subject: [PATCH 27/95] 8313706: [macos] Clipboard#setContents uses TIFF image data for all image content types Reviewed-by: avu, prr --- .../sun/lwawt/macosx/CDataTransferer.java | 13 +- .../classes/sun/lwawt/macosx/CImage.java | 66 ++++- .../ImageTransfer/ImageNativeFormatsTest.java | 253 ++++++++++++++++++ 3 files changed, 317 insertions(+), 15 deletions(-) create mode 100644 test/jdk/java/awt/datatransfer/ImageTransfer/ImageNativeFormatsTest.java diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java index ed8ca73a613..1fc4f34456b 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java @@ -243,7 +243,18 @@ public ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler() { } @Override - protected byte[] imageToPlatformBytes(Image image, long format) { + protected byte[] imageToPlatformBytes(Image image, long format) throws IOException { + if (format == CF_PNG) { + return imageToStandardBytes(image, "image/png"); + } + if (format == CF_JPEG) { + // JPEG doesn't support transparency, convert to opaque + Image opaque = CImage.getCreator().getOpaqueImage(image); + if (opaque == null) { + return null; + } + return imageToStandardBytes(opaque, "image/jpeg"); + } return CImage.getCreator().getPlatformImageBytes(image); } diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CImage.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CImage.java index 6cf49b5b9ff..4d6cbe050db 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CImage.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CImage.java @@ -130,23 +130,37 @@ public Image createImageFromName(final String name) { return createImageUsingNativeSize(nativeCreateNSImageFromImageName(name)); } - private static BufferedImage getAsBufferedImage(Image image, boolean prepareImage, CTrayIcon.IconObserver observer) { - if (image == null) return null; + private static boolean waitUntilImageLoaded(Image image) { + if (image instanceof BufferedImage) { + return true; + } - if (prepareImage && !(image instanceof BufferedImage)) { - final MediaTracker mt = new MediaTracker(new Label()); - final int id = 0; - mt.addImage(image, id); + final MediaTracker mt = new MediaTracker(new Label()); + final int id = 0; + mt.addImage(image, id); - try { - mt.waitForID(id); - } catch (InterruptedException e) { - return null; - } + try { + mt.waitForID(id); + } catch (InterruptedException e) { + return false; + } - if (mt.isErrorID(id)) { - return null; - } + if (mt.isErrorID(id)) { + return false; + } + + if (image.getWidth(null) < 0 || image.getHeight(null) < 0) { + return false; + } + + return true; + } + + private static BufferedImage getAsBufferedImage(Image image, boolean prepareImage, CTrayIcon.IconObserver observer) { + if (image == null) return null; + + if (prepareImage && !waitUntilImageLoaded(image)) { + return null; } int w = image.getWidth(null); @@ -165,6 +179,30 @@ private static BufferedImage getAsBufferedImage(Image image, boolean prepareImag return bimg; } + public Image getOpaqueImage(Image image) { + if (image instanceof BufferedImage bufferedImage) { + if (!bufferedImage.getColorModel().hasAlpha()) { + return bufferedImage; + } + } + + if (!waitUntilImageLoaded(image)) { + return null; + } + + int w = image.getWidth(null); + int h = image.getHeight(null); + + BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + Graphics2D g2 = bimg.createGraphics(); + g2.setColor(Color.WHITE); + g2.fillRect(0, 0, w, h); + g2.drawImage(image, 0, 0, null); + g2.dispose(); + + return bimg; + } + public byte[] getPlatformImageBytes(final Image image) { BufferedImage bimg = getAsBufferedImage(image, false, null); diff --git a/test/jdk/java/awt/datatransfer/ImageTransfer/ImageNativeFormatsTest.java b/test/jdk/java/awt/datatransfer/ImageTransfer/ImageNativeFormatsTest.java new file mode 100644 index 00000000000..a7b9350e79d --- /dev/null +++ b/test/jdk/java/awt/datatransfer/ImageTransfer/ImageNativeFormatsTest.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2026, JetBrains s.r.o.. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8313706 + * @summary To check whether images placed on macOS clipboard are encoded in + * the correct format (TIFF, PNG, JPEG) + * @key headful + * @requires os.family == "mac" + * @library /test/lib + * @run main ImageNativeFormatsTest + */ + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +import javax.imageio.ImageIO; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Point; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.SystemFlavorMap; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; + +public class ImageNativeFormatsTest { + public static void main(String[] args) throws Exception { + ImageNativeFormatsTest test = new ImageNativeFormatsTest(); + if (args.length > 0) { + assert args.length == 2; + test.verifyClipboardImage(args[0], Integer.parseInt(args[1])); + } else { + test.doTest(); + } + } + + enum Format { + TIFF("TIFF", new byte[][]{{77, 77, 0, 42}, {73, 73, 42, 0}}, true, false), + PNG("PNG", new byte[][]{{(byte) 137, 80, 78, 71, 13, 10, 26, 10}}, true, false), + JPEG("JFIF", new byte[][]{{(byte)255, (byte)216, (byte)255}}, false, true); + + final String nativeName; + final byte[][] signatures; + final boolean supportsAlpha; + final boolean isLossy; + + private DataFlavor flavor = null; + + Format(String nativeName, byte[][] signatures, boolean supportsAlpha, boolean isLossy) { + this.nativeName = nativeName; + this.signatures = signatures; + this.supportsAlpha = supportsAlpha; + this.isLossy = isLossy; + } + + public DataFlavor getFlavor() { + if (flavor != null) { + return flavor; + } + + try { + flavor = new DataFlavor("application/x-imagenativeformatstest-" + nativeName.toLowerCase() + + "; class=java.io.InputStream"); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + + SystemFlavorMap flavorMap = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap(); + flavorMap.addUnencodedNativeForFlavor(flavor, nativeName); + flavorMap.addFlavorForUnencodedNative(nativeName, flavor); + return flavor; + } + + int getSignatureLength() { + // both TIFF signatures are of the same length, so it's okay + return signatures[0].length; + } + + void checkSignature(byte[] bytes) { + byte[] signature = Arrays.copyOfRange(bytes, 0, getSignatureLength()); + + for (byte[] expected : signatures) { + if (Arrays.equals(signature, expected)) { + return; + } + } + + throw new RuntimeException("Image in clipboard not in format " + name() + + ", received signature is " + HexFormat.of().formatHex(signature)); + } + } + + BufferedImage getEagerImage(int imageType) { + BufferedImage image = new BufferedImage(32, 32, imageType); + Graphics2D g = image.createGraphics(); + g.setColor(Color.RED); + g.fillRect(0, 0, 16, 16); + g.setColor(Color.GREEN); + g.fillRect(16, 0, 16, 16); + g.setColor(Color.BLUE); + g.fillRect(0, 16, 16, 16); + g.dispose(); + return image; + } + + boolean areColorsEqualApprox(Color a, Color b) { + int delta = 10; + return Math.abs(a.getRed() - b.getRed()) <= delta && + Math.abs(a.getGreen() - b.getGreen()) <= delta && + Math.abs(a.getBlue() - b.getBlue()) <= delta && + Math.abs(a.getAlpha() - b.getAlpha()) <= delta; + } + + void verifyImageContents(BufferedImage image, int imageType, Format format) { + int w = image.getWidth(); + int h = image.getHeight(); + if (w != 32 || h != 32) { + throw new RuntimeException(String.format("Decoded image has wrong size: %dx%d", w, h)); + } + + boolean didHaveAlpha = imageType == BufferedImage.TYPE_INT_ARGB || + imageType == BufferedImage.TYPE_INT_ARGB_PRE; + + Point[] points = new Point[]{ + new Point(1, 1), + new Point(30, 1), + new Point(1, 30), + new Point(30, 30) + }; + Color[] colors = new Color[]{ + Color.RED, + Color.GREEN, + Color.BLUE, + didHaveAlpha ? (format.supportsAlpha ? new Color(0, 0, 0, 0) : Color.WHITE) : Color.BLACK, + }; + for (int i = 0; i < points.length; ++i) { + Point point = points[i]; + Color expected = colors[i]; + Color actual = new Color(image.getRGB(point.x, point.y), format.supportsAlpha); + boolean equals = format.isLossy ? areColorsEqualApprox(expected, actual) : expected.equals(actual); + if (!equals) { + throw new RuntimeException(String.format("Wrong color at (%d, %d): expected %s, got %s", point.x, point.y, expected, actual)); + } + } + } + + Image getLazyImage(int imageType) { + // make an image that needs waiting until it is loaded + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try { + ImageIO.write(getEagerImage(imageType), "png", bytes); + } catch (IOException e) { + throw new RuntimeException(e); + } + return Toolkit.getDefaultToolkit().createImage(bytes.toByteArray()); + } + + void copyImageToClipboard(Image image) { + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(new Transferable() { + @Override + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[]{DataFlavor.imageFlavor}; + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return Objects.equals(DataFlavor.imageFlavor, flavor); + } + + @Override + public Object getTransferData(DataFlavor flavor) { + return image; + } + }, null); + } + + void verifyClipboardImageIsInFormat(Format format, int imageType) { + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + try (InputStream inputStream = (InputStream) clipboard.getData(format.getFlavor())) { + byte[] bytes = inputStream.readAllBytes(); + format.checkSignature(bytes); + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + verifyImageContents(image, imageType, format); + } catch (UnsupportedFlavorException | IOException e) { + throw new RuntimeException(e); + } + } + + void verifyClipboardImage(String kind, int imageType) { + for (Format format : Format.values()) { + System.out.println("Checking " + kind + " image for format " + format.name()); + verifyClipboardImageIsInFormat(format, imageType); + } + } + + void check(String imageTypeStr, int imageType) throws Exception { + Image[] images = new Image[]{ + getEagerImage(imageType), + getLazyImage(imageType), + }; + String[] labels = new String[]{"eager", "lazy"}; + + for (int i = 0; i < images.length; ++i) { + Image image = images[i]; + String label = labels[i]; + String kind = String.format("%s %s", label, imageTypeStr); + copyImageToClipboard(image); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + ImageNativeFormatsTest.class.getName(), kind, Integer.toString(imageType)); + OutputAnalyzer out = ProcessTools.executeProcess(pb); + out.shouldHaveExitValue(0); + } + } + + void doTest() throws Exception { + check("ARGB_PRE", BufferedImage.TYPE_INT_ARGB_PRE); + check("ARGB", BufferedImage.TYPE_INT_ARGB); + check("RGB", BufferedImage.TYPE_INT_RGB); + } +} From 2209ecd82e1988c0d5af490a348587564a25f014 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20H=C3=A4ssig?= Date: Fri, 20 Nov 2026 10:27:23 +0000 Subject: [PATCH 28/95] 8397893: [Valhalla] Problemlist java/util/Arrays/largeMemory/ParallelPrefix.java Reviewed-by: mchevalier, thartmann --- test/jdk/ProblemList.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index eb2f64245d8..972c9e06876 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -646,4 +646,6 @@ tools/sincechecker/modules/jdk.management.jfr/JdkManagementJfrCheckSince.java 83 java/awt/image/multiresolution/MultiResolutionToolkitImageTest.java 8375778 macosx-aarch64 +java/util/Arrays/largeMemory/ParallelPrefix.java 8386501 generic-all + sun/tools/jhsdb/JStackStressTest.java 8247940 macosx-aarch64 From 8ed8a4d5ed50183508aeaeab8a071d68267bdd48 Mon Sep 17 00:00:00 2001 From: Thomas Schatzl Date: Fri, 20 Nov 2026 11:44:17 +0000 Subject: [PATCH 29/95] 8075229: G1 does not always scan CLDG references to the old gen potentially causing problems with eager reclaim Reviewed-by: ayang, stefank --- .../share/classfile/classLoaderData.cpp | 40 +++++----- .../share/classfile/classLoaderData.hpp | 23 +++--- .../classfile/classLoaderData.inline.hpp | 6 +- src/hotspot/share/gc/g1/g1CollectedHeap.hpp | 2 + .../share/gc/g1/g1CollectedHeap.inline.hpp | 6 ++ src/hotspot/share/gc/g1/g1HeapRegionAttr.hpp | 37 +++++---- src/hotspot/share/gc/g1/g1HeapVerifier.cpp | 28 +++++-- src/hotspot/share/gc/g1/g1OopClosures.cpp | 14 ++-- src/hotspot/share/gc/g1/g1OopClosures.hpp | 1 + .../share/gc/g1/g1OopClosures.inline.hpp | 9 +++ src/hotspot/share/gc/g1/g1YoungCollector.cpp | 2 +- .../share/gc/parallel/psClosure.inline.hpp | 4 +- .../share/gc/serial/defNewGeneration.cpp | 4 +- .../humongousObjects/TestHumongousMirror.java | 79 +++++++++++++++++++ .../hotspot/jtreg/gc/testlibrary/Helpers.java | 55 ++++++++++++- 15 files changed, 240 insertions(+), 70 deletions(-) create mode 100644 test/hotspot/jtreg/gc/g1/humongousObjects/TestHumongousMirror.java diff --git a/src/hotspot/share/classfile/classLoaderData.cpp b/src/hotspot/share/classfile/classLoaderData.cpp index 31f439fdf73..68871c42932 100644 --- a/src/hotspot/share/classfile/classLoaderData.cpp +++ b/src/hotspot/share/classfile/classLoaderData.cpp @@ -142,7 +142,7 @@ ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool has_class_mirror_ho _metaspace(nullptr), _metaspace_lock(new Mutex(Mutex::nosafepoint-2, "MetaspaceAllocation_lock")), _unloading(false), _has_class_mirror_holder(has_class_mirror_holder), - _modified_oops(true), + _has_modified_or_humongous_oops(true), // A non-strong hidden class loader data doesn't have anything to keep // it from being unloaded during parsing of the non-strong hidden class. // The null-class-loader should always be kept alive. @@ -330,7 +330,7 @@ void ClassLoaderData::demote_strong_roots() { ShouldNotReachHere(); } } cl; - oops_do(&cl, ClassLoaderData::_claim_none, false /* clear_mod_oops */); + oops_do(&cl, ClassLoaderData::_claim_none, false /* should_clear_modified_or_humongous_oops */); } // Non-strong hidden classes have their own ClassLoaderData that is marked to keep alive @@ -360,10 +360,10 @@ void ClassLoaderData::dec_keep_alive_ref_count() { } } -void ClassLoaderData::oops_do_slow(OopClosure* f, bool clear_mod_oops) { - // Only clear modified_oops after the ClassLoaderData is claimed. - if (clear_mod_oops) { - clear_modified_oops(); +void ClassLoaderData::oops_do_slow(OopClosure* f, bool should_clear_modified_or_humongous_oops) { + // Only clear _has_modified_or_humongous_oops after the ClassLoaderData is claimed. + if (should_clear_modified_or_humongous_oops) { + clear_modified_or_humongous_oops(); } _handles.oops_do(f); @@ -1012,23 +1012,23 @@ class PrintKlassClosure: public KlassClosure { void ClassLoaderData::print_on(outputStream* out) const { ResourceMark rm; out->print_cr("ClassLoaderData(" INTPTR_FORMAT ")", p2i(this)); - out->print_cr(" - name %s", loader_name_and_id()); + out->print_cr(" - name %s", loader_name_and_id()); if (!_holder.is_null()) { - out->print (" - holder "); + out->print (" - holder "); _holder.print_on(out); out->print_cr(""); } if (!_unloading) { - out->print_cr(" - class loader " INTPTR_FORMAT, p2i(_class_loader.peek())); + out->print_cr(" - class loader " INTPTR_FORMAT, p2i(_class_loader.peek())); } else { - out->print_cr(" - class loader "); - } - out->print_cr(" - metaspace " INTPTR_FORMAT, p2i(_metaspace)); - out->print_cr(" - unloading %s", _unloading ? "true" : "false"); - out->print_cr(" - class mirror holder %s", _has_class_mirror_holder ? "true" : "false"); - out->print_cr(" - modified oops %s", _modified_oops ? "true" : "false"); - out->print_cr(" - _keep_alive_ref_count %d", _keep_alive_ref_count); - out->print (" - claim "); + out->print_cr(" - class loader "); + } + out->print_cr(" - metaspace " INTPTR_FORMAT, p2i(_metaspace)); + out->print_cr(" - unloading %s", _unloading ? "true" : "false"); + out->print_cr(" - class mirror holder %s", _has_class_mirror_holder ? "true" : "false"); + out->print_cr(" - modified or humongous oops %s", _has_modified_or_humongous_oops ? "true" : "false"); + out->print_cr(" - _keep_alive_ref_count %d", _keep_alive_ref_count); + out->print (" - claim "); switch(_claim) { case _claim_none: out->print_cr("none"); break; case _claim_finalizable: out->print_cr("finalizable"); break; @@ -1040,8 +1040,8 @@ void ClassLoaderData::print_on(outputStream* out) const { case _claim_other | _claim_strong: out->print_cr("other and strong"); break; default: ShouldNotReachHere(); } - out->print_cr(" - handles %d", _handles.count()); - out->print_cr(" - dependency count %d", _dependency_count); + out->print_cr(" - handles %d", _handles.count()); + out->print_cr(" - dependency count %d", _dependency_count); out->print (" - klasses { "); if (Verbose) { PrintKlassClosure closure(out); @@ -1121,7 +1121,7 @@ void ClassLoaderData::verify() { // Check the oops in the handles area VerifyHandleOops vho; - oops_do(&vho, _claim_none, false); + oops_do(&vho, _claim_none, false /* should_clear_modified_or_humongous_oops */); } bool ClassLoaderData::contains_klass(Klass* klass) { diff --git a/src/hotspot/share/classfile/classLoaderData.hpp b/src/hotspot/share/classfile/classLoaderData.hpp index 425194989d5..7ab7452fb82 100644 --- a/src/hotspot/share/classfile/classLoaderData.hpp +++ b/src/hotspot/share/classfile/classLoaderData.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -118,7 +118,10 @@ class ClassLoaderData : public CHeapObj { // to these class loader data. // Remembered sets support for the oops in the class loader data. - bool _modified_oops; // Card Table Equivalent + // The CLDs are not placed in the Java heap, so the Card Table can't be used to mark when + // CLDs were modified. In addition to that, G1's eager reclaim mechanism also requires + // checking if the CLD contains oops to humongous objects. + bool _has_modified_or_humongous_oops; int _keep_alive_ref_count; // if this CLD should not be considered eligible for unloading. // Used for non-strong hidden classes and the @@ -190,13 +193,13 @@ class ClassLoaderData : public CHeapObj { void unload(); private: - // The CLD are not placed in the Heap, so the Card Table or - // the Mod Union Table can't be used to mark when CLD have modified oops. - // The CT and MUT bits saves this information for the whole class loader data. - void clear_modified_oops() { _modified_oops = false; } + void clear_modified_or_humongous_oops() { _has_modified_or_humongous_oops = false; } public: - void record_modified_oops() { _modified_oops = true; } - bool has_modified_oops() { return _modified_oops; } + void record_modified_oops() { _has_modified_or_humongous_oops = true; } + bool has_modified_oops() { return _has_modified_or_humongous_oops; } + + void record_humongous_oops() { _has_modified_or_humongous_oops = true; } + bool has_modified_or_humongous_oops() { return _has_modified_or_humongous_oops; } oop holder_no_keepalive() const; // Resolving the holder keeps this CLD alive for the current GC cycle. @@ -306,8 +309,8 @@ class ClassLoaderData : public CHeapObj { void initialize_holder(Handle holder); - inline void oops_do(OopClosure* f, int claim_value, bool clear_modified_oops = false); - void oops_do_slow(OopClosure* f, bool clear_modified_oops); + inline void oops_do(OopClosure* f, int claim_value, bool should_clear_modified_or_humongous_oops = false); + void oops_do_slow(OopClosure* f, bool should_clear_modified_or_humongous_oops); void classes_do(KlassClosure* klass_closure); Klass* klasses() { return _klasses; } diff --git a/src/hotspot/share/classfile/classLoaderData.inline.hpp b/src/hotspot/share/classfile/classLoaderData.inline.hpp index df29dca053b..58e47be2475 100644 --- a/src/hotspot/share/classfile/classLoaderData.inline.hpp +++ b/src/hotspot/share/classfile/classLoaderData.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,9 +98,9 @@ inline bool ClassLoaderData::try_claim(int claim) { } } -inline void ClassLoaderData::oops_do(OopClosure* f, int claim_value, bool clear_mod_oops) { +inline void ClassLoaderData::oops_do(OopClosure* f, int claim_value, bool should_clear_modified_or_humongous_oops) { if (claim_value == _claim_none || try_claim(claim_value)) { - oops_do_slow(f, clear_mod_oops); + oops_do_slow(f, should_clear_modified_or_humongous_oops); } } diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp index e3d33004a5e..f330223995b 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp @@ -630,6 +630,8 @@ class G1CollectedHeap : public CollectedHeap { // Register the given region to be part of the collection set. inline void register_humongous_candidate_region_with_region_attr(uint index); + inline void register_humongous_non_candidate_region_with_region_attr(uint index); + void set_humongous_metadata(G1HeapRegion* first_hr, uint num_regions, size_t word_size, diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.inline.hpp b/src/hotspot/share/gc/g1/g1CollectedHeap.inline.hpp index 1690c061858..be8a0503221 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.inline.hpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.inline.hpp @@ -196,6 +196,12 @@ void G1CollectedHeap::register_humongous_candidate_region_with_region_attr(uint _region_attr.set_humongous_candidate(index); } +void G1CollectedHeap::register_humongous_non_candidate_region_with_region_attr(uint index) { + _region_attr.set_humongous_non_candidate(index, + region_at(index)->rem_set()->is_tracked(), + region_at(index)->has_pinned_objects()); +} + void G1CollectedHeap::register_young_region_with_region_attr(G1HeapRegion* r) { assert(!is_in_cset(r), "should not already be registered as in collection set"); _region_attr.set_in_young(r->hrm_index(), r->has_pinned_objects()); diff --git a/src/hotspot/share/gc/g1/g1HeapRegionAttr.hpp b/src/hotspot/share/gc/g1/g1HeapRegionAttr.hpp index 7c715ebc0e6..1932b81368b 100644 --- a/src/hotspot/share/gc/g1/g1HeapRegionAttr.hpp +++ b/src/hotspot/share/gc/g1/g1HeapRegionAttr.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,8 +55,9 @@ struct G1HeapRegionAttr { // // The other values are used for objects in regions requiring various special handling, // eager reclamation of humongous objects or optional regions. - static const region_type_t Optional = -4; // The region is optional not in the current collection set. - static const region_type_t HumongousCandidate = -3; // The region is a humongous candidate not in the current collection set. + static const region_type_t HumongousCandidate = -5; // The region is a humongous candidate. + static const region_type_t HumongousNonCandidate = -4; // The region is a humongous region that is not a candidate. + static const region_type_t Optional = -3; // The region is optional not in the current collection set. static const region_type_t NewSurvivor = -2; // The region is a new (ly allocated) survivor region. static const region_type_t NotInCSet = -1; // The region is not in the collection set. static const region_type_t Young = 0; // The region is in the collection set and a young region. @@ -72,8 +73,9 @@ struct G1HeapRegionAttr { const char* get_type_str() const { switch (type()) { - case Optional: return "Optional"; case HumongousCandidate: return "HumongousCandidate"; + case HumongousNonCandidate: return "Humongous"; + case Optional: return "Optional"; case NewSurvivor: return "NewSurvivor"; case NotInCSet: return "NotInCSet"; case Young: return "Young"; @@ -82,14 +84,14 @@ struct G1HeapRegionAttr { } } - bool is_remset_tracked() const { return _is_remset_tracked != 0; } + bool is_remset_tracked() const { return _is_remset_tracked != 0; } bool is_pinned() const { return _is_pinned != 0; } void set_old() { _type = Old; } - void clear_humongous_candidate() { - assert(is_humongous_candidate() || !is_in_cset(), "must be"); - _type = NotInCSet; + void clear_humongous_candidate() { + assert(is_humongous(), "must be"); + _type = HumongousNonCandidate; } void set_is_remset_tracked(bool value) { _is_remset_tracked = value ? 1 : 0; } @@ -98,7 +100,8 @@ struct G1HeapRegionAttr { bool is_in_cset_or_humongous_candidate() const { return is_in_cset() || is_humongous_candidate(); } bool is_in_cset() const { return type() >= Young; } - bool is_humongous_candidate() const { return type() == HumongousCandidate; } + bool is_humongous_candidate() const { return type() == HumongousCandidate; } + bool is_humongous() const { return type() <= HumongousNonCandidate; } bool is_new_survivor() const { return type() == NewSurvivor; } bool is_young() const { return type() == Young; } bool is_old() const { return type() == Old; } @@ -106,7 +109,7 @@ struct G1HeapRegionAttr { #ifdef ASSERT bool is_default() const { return type() == NotInCSet; } - bool is_valid() const { return (type() >= Optional && type() < Num); } + bool is_valid() const { return (type() >= HumongousCandidate && type() < Num); } #endif }; @@ -114,10 +117,10 @@ struct G1HeapRegionAttr { // // We use this to speed up reference processing during young collection and // quickly reclaim humongous objects. For the latter, at the start of GC, by adding -// it as a humongous region we enable special handling for that region. During the -// reference iteration closures, when we see a humongous region, we then simply mark -// it as referenced, i.e. live, and remove it from this table to prevent further -// processing on it. +// it as a humongous candidate we enable special handling for that region. +// During the reference iteration closures, when we see a humongous region candidate, +// we then simply mark it as referenced, i.e. live, and change it to a humongous +// non-candidate to prevent further processing on it. // // This means that this does NOT completely correspond to the information stored // in a G1HeapRegion, but only to what is interesting for the current young collection. @@ -147,6 +150,12 @@ class G1HeapRegionAttrBiasedMappedArray : public G1BiasedMappedArrayclear_humongous_candidate(); } diff --git a/src/hotspot/share/gc/g1/g1HeapVerifier.cpp b/src/hotspot/share/gc/g1/g1HeapVerifier.cpp index a7c87305d57..fbcddf71370 100644 --- a/src/hotspot/share/gc/g1/g1HeapVerifier.cpp +++ b/src/hotspot/share/gc/g1/g1HeapVerifier.cpp @@ -150,12 +150,21 @@ class G1VerifyCodeRootNMethodClosure: public NMethodClosure { } }; -class YoungRefCounterClosure : public OopClosure { +class YoungOrHumongousRefCounterClosure : public OopClosure { G1CollectedHeap* _g1h; int _count; public: - YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {} - void do_oop(oop* p) { if (_g1h->is_in_young(*p)) { _count++; } } + YoungOrHumongousRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {} + void do_oop(oop* p) { + oop obj = *p; + if (obj == nullptr) { + return; + } + G1HeapRegion* r = _g1h->heap_region_containing(obj); + if (r->is_young() || r->is_humongous()) { + _count++; + } + } void do_oop(narrowOop* p) { ShouldNotReachHere(); } int count() { return _count; } @@ -163,7 +172,7 @@ class YoungRefCounterClosure : public OopClosure { }; class VerifyCLDClosure: public CLDClosure { - YoungRefCounterClosure _young_ref_counter_closure; + YoungOrHumongousRefCounterClosure _young_ref_counter_closure; OopClosure *_oop_closure; public: VerifyCLDClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {} @@ -173,7 +182,7 @@ class VerifyCLDClosure: public CLDClosure { _young_ref_counter_closure.reset_count(); cld->oops_do(&_young_ref_counter_closure, ClassLoaderData::_claim_none); if (_young_ref_counter_closure.count() > 0) { - guarantee(cld->has_modified_oops(), "CLD " PTR_FORMAT ", has young %d refs but is not dirty.", p2i(cld), _young_ref_counter_closure.count()); + guarantee(cld->has_modified_or_humongous_oops(), "CLD " PTR_FORMAT ", has %d young or humongous refs but is not dirty.", p2i(cld), _young_ref_counter_closure.count()); } } }; @@ -715,13 +724,18 @@ class G1CheckRegionAttrTableClosure : public G1HeapRegionClosure { _failures = true; return true; } - if (hr->is_continues_humongous() && region_attr.is_humongous_candidate()) { + if (hr->is_starts_humongous() && !region_attr.is_humongous()) { + log_error(gc, verify)("## inconsistent region attr type %s for humongous starts region %u", region_attr.get_type_str(), i); + _failures = true; + return true; + } + if (hr->is_continues_humongous() && region_attr.is_humongous()) { log_error(gc, verify)("## inconsistent region attr type %s for continues humongous region %u", region_attr.get_type_str(), i); _failures = true; return true; } } else { - if (region_attr.is_humongous_candidate()) { + if (region_attr.is_humongous()) { log_error(gc, verify)("## inconsistent region attr type %s for non-humongous region %u", region_attr.get_type_str(), i); _failures = true; return true; diff --git a/src/hotspot/share/gc/g1/g1OopClosures.cpp b/src/hotspot/share/gc/g1/g1OopClosures.cpp index 44085269d45..509a99ebecf 100644 --- a/src/hotspot/share/gc/g1/g1OopClosures.cpp +++ b/src/hotspot/share/gc/g1/g1OopClosures.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,14 +42,14 @@ G1ScanClosureBase::G1ScanClosureBase(G1CollectedHeap* g1h, G1ParScanThreadState* void G1CLDScanClosure::do_cld(ClassLoaderData* cld) { // If the class loader data has not been dirtied we know that there's - // no references into the young gen and we can skip it. - if (!_process_only_dirty || cld->has_modified_oops()) { - + // no references into the young gen or humongous regions and we can skip it. + if (!_process_only_dirty || cld->has_modified_or_humongous_oops()) { // Tell the closure that this class loader data is the CLD to scavenge - // and is the one to dirty if oops are left pointing into the young gen. + // and is the one to dirty if oops are left pointing into the young gen + // or humongous regions. _closure->set_scanned_cld(cld); - // Clean modified oops since we're going to scavenge all the metadata. - cld->oops_do(_closure, ClassLoaderData::_claim_none, true /*clear_modified_oops*/); + // Clear the flag before iterating the oops - it will be set again if needed. + cld->oops_do(_closure, ClassLoaderData::_claim_none, true /* should_clear_modified_or_humongous_oops */); _closure->set_scanned_cld(nullptr); diff --git a/src/hotspot/share/gc/g1/g1OopClosures.hpp b/src/hotspot/share/gc/g1/g1OopClosures.hpp index b6cbb765280..5a84a5e7586 100644 --- a/src/hotspot/share/gc/g1/g1OopClosures.hpp +++ b/src/hotspot/share/gc/g1/g1OopClosures.hpp @@ -148,6 +148,7 @@ class G1ParCopyHelper : public OopClosure { public: void set_scanned_cld(ClassLoaderData* cld) { _scanned_cld = cld; } inline void do_cld_barrier(oop new_obj); + inline void do_cld_barrier_non_cset(G1HeapRegionAttr state); inline void trim_queue_partially(); }; diff --git a/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp b/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp index c7ea27882ab..ce1c50e8de6 100644 --- a/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp +++ b/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp @@ -215,6 +215,12 @@ void G1ParCopyHelper::do_cld_barrier(oop new_obj) { } } +void G1ParCopyHelper::do_cld_barrier_non_cset(G1HeapRegionAttr attr) { + if (attr.is_humongous()) { + _scanned_cld->record_humongous_oops(); + } +} + void G1ParCopyHelper::mark_object(oop obj) { assert(!_g1h->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet"); @@ -255,6 +261,9 @@ void G1ParCopyClosure::do_oop_work(T* p) { do_cld_barrier(forwardee); } } else { + if (barrier == G1BarrierCLD) { + do_cld_barrier_non_cset(state); + } if (state.is_humongous_candidate()) { _g1h->set_humongous_is_live(obj); } else if ((barrier != G1BarrierNoOptRoots) && state.is_optional()) { diff --git a/src/hotspot/share/gc/g1/g1YoungCollector.cpp b/src/hotspot/share/gc/g1/g1YoungCollector.cpp index 90d430ac601..5cd5bcd42f2 100644 --- a/src/hotspot/share/gc/g1/g1YoungCollector.cpp +++ b/src/hotspot/share/gc/g1/g1YoungCollector.cpp @@ -423,7 +423,7 @@ class G1PrepareEvacuationTask : public WorkerTask { _worker_humongous_candidates++; // We will later handle the remembered sets of these regions. } else { - _g1h->update_region_attr(hr); + _g1h->register_humongous_non_candidate_region_with_region_attr(index); } // Sample card set sizes for humongous regions before GC: this makes the policy diff --git a/src/hotspot/share/gc/parallel/psClosure.inline.hpp b/src/hotspot/share/gc/parallel/psClosure.inline.hpp index 0edf8421205..4282773f0c7 100644 --- a/src/hotspot/share/gc/parallel/psClosure.inline.hpp +++ b/src/hotspot/share/gc/parallel/psClosure.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -115,7 +115,7 @@ class PSScavengeCLDClosure: public CLDClosure { PSScavengeCLDOopClosure oop_closure{_pm}; // Clean the cld since we're going to scavenge all the metadata. - cld->oops_do(&oop_closure, ClassLoaderData::_claim_none, /*clear_modified_oops*/true); + cld->oops_do(&oop_closure, ClassLoaderData::_claim_none, true /* should_clear_modified_or_humongous_oops */); if (oop_closure._has_oops_into_young_gen) { cld->record_modified_oops(); diff --git a/src/hotspot/share/gc/serial/defNewGeneration.cpp b/src/hotspot/share/gc/serial/defNewGeneration.cpp index 0c44e7a8c14..194b821f48b 100644 --- a/src/hotspot/share/gc/serial/defNewGeneration.cpp +++ b/src/hotspot/share/gc/serial/defNewGeneration.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -128,7 +128,7 @@ class CLDScanClosure: public CLDClosure { CLDOopClosure oop_closure{_g}; // Clean the cld since we're going to scavenge all the metadata. - cld->oops_do(&oop_closure, ClassLoaderData::_claim_none, /*clear_modified_oops*/true); + cld->oops_do(&oop_closure, ClassLoaderData::_claim_none, true /* should_clear_modified_or_humongous_oops */); if (oop_closure._has_oops_into_young_gen) { cld->record_modified_oops(); diff --git a/test/hotspot/jtreg/gc/g1/humongousObjects/TestHumongousMirror.java b/test/hotspot/jtreg/gc/g1/humongousObjects/TestHumongousMirror.java new file mode 100644 index 00000000000..bb2c2955854 --- /dev/null +++ b/test/hotspot/jtreg/gc/g1/humongousObjects/TestHumongousMirror.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package gc.g1.humongousObjects; + +import gc.testlibrary.Helpers; +import jdk.test.whitebox.WhiteBox; + +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * @test gc.g1.humongousObjects.TestHumongousMirror + * @bug 8075229 + * @summary Checks that a humongous mirror is not reclaimed eagerly as long as a CLD has a reference to it. + * @requires vm.gc.G1 + * @requires vm.opt.G1HeapRegionSize == "null" | vm.opt.G1HeapRegionSize == "1M" + * @requires vm.opt.ClassUnloading != false + * @requires vm.opt.ClassUnloadingWithConcurrentMark != false + * @library /test/lib / + * @modules java.base/jdk.internal.misc + * @modules java.management + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm -Xms64M -Xmx64M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. + * -Xlog:gc,gc+humongous=debug,class+load,class+unload=debug:file=TestHumongousMirror.log + * -XX:G1HeapRegionSize=1M -XX:MaxTenuringThreshold=1 -XX:+VerifyAfterGC + * gc.g1.humongousObjects.TestHumongousMirror + */ + +public class TestHumongousMirror { + private static final WhiteBox WB = WhiteBox.getWhiteBox(); + + private static final String className = "HumongousMirror"; + + public static void main(String[] args) throws Exception { + final Path workDir = Paths.get(""); + + // 65523 statics make the mirror of the class humongous on both 32 and 64 bit VMs. + String c = Helpers.generate(className, null, null, 0, 65523); + Helpers.compileClass(className, workDir, c); + + Class clazz = Class.forName(className, false, null); + if (!WB.g1IsHumongous(clazz)) { + throw new Error("Mirror is not humongous"); + } + long mirrorAddress = WB.getObjectAddress(clazz); + // Remove all Java references. The CLD still has a reference to the humongous mirror. + clazz = null; + + for (int i = 0; i < 5; i++) { + WB.youngGC(); + if (WB.g1BelongsToFreeRegion(mirrorAddress)) { + throw new Error("Mirror at " + mirrorAddress + " has been reclaimed"); + } + } + } +} diff --git a/test/hotspot/jtreg/gc/testlibrary/Helpers.java b/test/hotspot/jtreg/gc/testlibrary/Helpers.java index 32745ec3037..058adc6593f 100644 --- a/test/hotspot/jtreg/gc/testlibrary/Helpers.java +++ b/test/hotspot/jtreg/gc/testlibrary/Helpers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -97,6 +97,7 @@ public static void compileClass(String className, Path root, String source) thro JDKToolLauncher jar = JDKToolLauncher.create("javac") .addToolArg("-d") .addToolArg(root.toAbsolutePath().toString()) + .addToolArg("-g:none") .addToolArg("-cp") .addToolArg(System.getProperty("java.class.path") + File.pathSeparator + root.toAbsolutePath()) .addToolArg(sourceFile.toAbsolutePath().toString()); @@ -123,13 +124,39 @@ public static void compileClass(String className, Path root, String source) thro * @param fieldCount count of long fields * @return class text */ - public static String generate(String className, String superClass, String constructor, long fieldCount) { + public static String generate(String className, String superClass, String constructor, int fieldCount) { + return generate(className, superClass, constructor, fieldCount, 0); + } + /** + * Generates class with specified name, which extends specified class, with specified constructor, specified + * count of long fields and specified count of long static fields. + * Generated class will looks like this: + * public class ClassName extends SuperClass { + * ClassName() {super();} + * long f0; + * ... + * long fNNN; + * static long s0; + * ... + * static long sMMM; + *

+ * } + * + * @param className class name + * @param superClass super class. if null - no extends clause + * @param constructor constructor. if null - no constructor + * @param fieldCount count of long fields + * @param staticFieldCount count of static long field + * @return class text + */ + public static String generate(String className, String superClass, String constructor, int fieldCount, int staticFieldCount) { return new StringBuilder() .append(String.format("public class %s%s {\n", className, superClass == null ? "" : " extends " + superClass)) .append(constructor == null ? "" : constructor) .append(fieldsGenerator(fieldCount)) + .append(staticsGenerator(staticFieldCount)) .append("}\n") .toString(); } @@ -145,8 +172,8 @@ public static String generate(String className, String superClass, String constr * @param fieldCount count of long fields * @return generated fields */ - private static String fieldsGenerator(long fieldCount) { - StringBuilder fieldsBuilder = new StringBuilder(); + private static String fieldsGenerator(int fieldCount) { + StringBuilder fieldsBuilder = new StringBuilder(""); for (int i = 0; i < fieldCount; ++i) { fieldsBuilder.append(String.format("long f%d;\n", i)); @@ -155,6 +182,26 @@ private static String fieldsGenerator(long fieldCount) { return fieldsBuilder.toString(); } + /** + * Generates specified amount of static long fields + * Result string will looks like this: + *

+ * static long s0; + * ... + * static long sMMM; + * + * @param staticFieldCount count of static long fields + * @return generated fields + */ + private static String staticsGenerator(int staticFieldCount) { + StringBuilder staticsBuilder = new StringBuilder(""); + + for (int i = 0; i < staticFieldCount; ++i) { + staticsBuilder.append(String.format("static long s%d;\n", i)); + } + + return staticsBuilder.toString(); + } /** * Changes string from enum notation to class notation - i.e. "VERY_SMALL_CAT" to "VerySmallCat" From 7d35cf2baf5b2e35e9bc7908fca68531f8adee14 Mon Sep 17 00:00:00 2001 From: Albert Mingkun Yang Date: Fri, 20 Nov 2026 12:13:17 +0000 Subject: [PATCH 30/95] 8397771: x86: Remove redundant zero-fill predicates from ClearArray matching rules Reviewed-by: gcao, gli --- src/hotspot/cpu/x86/x86.ad | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/src/hotspot/cpu/x86/x86.ad b/src/hotspot/cpu/x86/x86.ad index 6c54ffea6fe..899cda62514 100644 --- a/src/hotspot/cpu/x86/x86.ad +++ b/src/hotspot/cpu/x86/x86.ad @@ -14794,8 +14794,7 @@ instruct rep_stos(rcx_RegL cnt, rdi_RegP base, regD tmp, immL0 zero, rax_RegL va Universe dummy, rFlagsReg cr) %{ predicate((UseAVX <= 2) && - !((ClearArrayNode*)n)->is_large() && - ((ClearArrayNode*)n)->is_zero_fill()); + !((ClearArrayNode*)n)->is_large()); match(Set dummy (ClearArray (Binary cnt base) zero)); effect(USE_KILL cnt, USE_KILL base, TEMP tmp, KILL val, KILL cr); @@ -14916,8 +14915,7 @@ instruct rep_stos_evex(rcx_RegL cnt, rdi_RegP base, legRegD tmp, kReg ktmp, immL Universe dummy, rFlagsReg cr) %{ predicate((UseAVX > 2) && - !((ClearArrayNode*)n)->is_large() && - ((ClearArrayNode*)n)->is_zero_fill()); + !((ClearArrayNode*)n)->is_large()); match(Set dummy (ClearArray (Binary cnt base) zero)); ins_cost(125); effect(USE_KILL cnt, USE_KILL base, TEMP tmp, TEMP ktmp, KILL val, KILL cr); @@ -15040,8 +15038,7 @@ instruct rep_stos_large(rcx_RegL cnt, rdi_RegP base, regD tmp, immL0 zero, rax_R Universe dummy, rFlagsReg cr) %{ predicate((UseAVX <= 2) && - ((ClearArrayNode*)n)->is_large() && - ((ClearArrayNode*)n)->is_zero_fill()); + ((ClearArrayNode*)n)->is_large()); match(Set dummy (ClearArray (Binary cnt base) zero)); effect(USE_KILL cnt, USE_KILL base, TEMP tmp, KILL val, KILL cr); @@ -15142,8 +15139,7 @@ instruct rep_stos_large_evex(rcx_RegL cnt, rdi_RegP base, legRegD tmp, kReg ktmp Universe dummy, rFlagsReg cr) %{ predicate((UseAVX > 2) && - ((ClearArrayNode*)n)->is_large() && - ((ClearArrayNode*)n)->is_zero_fill()); + ((ClearArrayNode*)n)->is_large()); match(Set dummy (ClearArray (Binary cnt base) zero)); effect(USE_KILL cnt, USE_KILL base, TEMP tmp, TEMP ktmp, KILL val, KILL cr); @@ -15244,8 +15240,7 @@ instruct rep_stos_im(immL cnt, rRegP base, regD tmp, immL0 zero, rRegI val, kReg %{ predicate((MaxVectorSize >= 32) && VM_Version::supports_avx512vl() && - !((ClearArrayNode*)n)->is_large() && - ((ClearArrayNode*)n)->is_zero_fill()); + !((ClearArrayNode*)n)->is_large()); match(Set dummy (ClearArray (Binary cnt base) zero)); ins_cost(100); effect(TEMP tmp, TEMP val, TEMP ktmp, KILL cr); From 39421b85e18fde0053f1c34c0ec7ad07161926c0 Mon Sep 17 00:00:00 2001 From: Frederic Parain Date: Fri, 20 Nov 2026 14:25:49 +0000 Subject: [PATCH 31/95] 8396195: [Valhalla] New TestNullnessPropagation fails on Big Endian platforms Reviewed-by: mdoerr, thartmann --- .../valuetypes/TestNullnessPropagation.java | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullnessPropagation.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullnessPropagation.java index 5b697ae0b91..610aa3b6ec5 100644 --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullnessPropagation.java +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullnessPropagation.java @@ -27,12 +27,9 @@ import compiler.valhalla.valuetypes.ValueTypes; import jdk.test.lib.Asserts; -import static compiler.lib.ir_framework.IRNode.LSHIFT_L; - /* * @test * @bug 8395611 8396195 - * @requires vm.endian == "little" * @summary Test nullness propagation during parsing * @library /test/lib / * @enablePreview @@ -41,6 +38,8 @@ public class TestNullnessPropagation { + private static final String MYVALUE_NOTNULL = "ValueType.*#instptr:.*TestNullnessPropagation\\$MyValue:NotNull"; + public static void main(String[] args) { ValueTypes.getFramework() .addFlags("--enable-preview") @@ -55,16 +54,12 @@ static class Holder { MyValue v; } - // Why IR verification is looking for a LSHIFT_L node? - // Without the nullness propagation fix, C2 reconstructs the value v using - // a formulae like this one: - // (I2L(null_marker) << 32) | (I2L(L2I(CastP2X(EncodeP(v.o_ref)))) & 0ffff_ffff) - // The value of the null marker dynamically read from a buffered value or - // a method argument has to be shifted to be put at the right place. - // With the nullness propagation fixed, C2 uses a ConL node to directly get - // the null_marker bit set in place, and no shift operation is needed. + // Check that the non-nullness has been propagated correctly + // by the parser by checking that the ValueType node used by + // the field store is marked NotNull (used for test 0 and 1). @Test - @IR(failOn = {LSHIFT_L}) + @IR(phase = CompilePhase.AFTER_PARSING, + counts = {MYVALUE_NOTNULL, "> 0"}) public Holder test0(MyValue v) { if (v == null) { return null; @@ -86,7 +81,8 @@ public void test0_verifier() { // Same IR verification rule as for test0 @Test - @IR(failOn = {LSHIFT_L}) + @IR(phase = CompilePhase.AFTER_PARSING, + counts = {MYVALUE_NOTNULL, "> 0"}) public Holder test1(MyValue v) { if (v != null) { Holder h = new Holder(); @@ -105,4 +101,21 @@ public void test1_verifier() { Holder nh = test1(null); Asserts.assertNull(nh); } -} \ No newline at end of file + + @Test + @IR(phase = CompilePhase.AFTER_PARSING, + failOn = {IRNode.NULL_CHECK_TRAP}) + public Object test2(MyValue v) { + if (v == null) { + return null; + } + return v.o; + } + + @Run(test = "test2") + public void test2_verifier() { + Asserts.assertNull(test2(null)); + var mv = new MyValue(); + Asserts.assertEQ(test2(mv), mv.o); + } +} From 47aa18053c827fea8619ed2f83c34d8328e8dc96 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Fri, 20 Nov 2026 14:50:37 +0000 Subject: [PATCH 32/95] 8397817: System.nanoTime() does not scale with the number of threads on macOS Reviewed-by: dholmes, shade --- src/hotspot/os/bsd/os_bsd.cpp | 5 ++ .../runtime/os/TestNanoTimeMonotonicity.java | 77 +++++++++++++++++++ .../openjdk/bench/java/lang/SystemTime.java | 7 ++ 3 files changed, 89 insertions(+) create mode 100644 test/hotspot/jtreg/runtime/os/TestNanoTimeMonotonicity.java diff --git a/src/hotspot/os/bsd/os_bsd.cpp b/src/hotspot/os/bsd/os_bsd.cpp index 2d1540ea641..ba1c0a57659 100644 --- a/src/hotspot/os/bsd/os_bsd.cpp +++ b/src/hotspot/os/bsd/os_bsd.cpp @@ -841,6 +841,10 @@ void os::Bsd::clock_init() { jlong os::javaTimeNanos() { const uint64_t tm = mach_absolute_time(); const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom; +// On Aarch64 we trust the monotonicity of the time value. For x86_64 we ensure the time does not go backwards. +#ifdef AARCH64 + return now; +#else const uint64_t prev = Bsd::_max_abstime; if (now <= prev) { return prev; // same or retrograde time; @@ -861,6 +865,7 @@ jlong os::javaTimeNanos() { // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate // https://web.archive.org/web/20131214182431/https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate return (prev == obsv) ? now : obsv; +#endif } void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { diff --git a/test/hotspot/jtreg/runtime/os/TestNanoTimeMonotonicity.java b/test/hotspot/jtreg/runtime/os/TestNanoTimeMonotonicity.java new file mode 100644 index 00000000000..7a6318d967c --- /dev/null +++ b/test/hotspot/jtreg/runtime/os/TestNanoTimeMonotonicity.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.ArrayList; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicLong; + +/** + * @test + * @bug 8397817 + * @summary Check that System.nanoTime is monotonic across threads + * @run main/othervm TestNanoTimeMonotonicity + */ +class TestNanoTimeMonotonicity { + + static void main() throws Exception { + var numWorkers = Math.max(Runtime.getRuntime().availableProcessors(), 2); + var futures = new ArrayList>(); + var start = new CyclicBarrier(numWorkers); + var deadline = System.nanoTime() + 1_000_000_000L; + var sharedTime = new AtomicLong(System.nanoTime()); + try (var executor = Executors.newFixedThreadPool(numWorkers)) { + for (int i = 0; i < numWorkers; i++) { + futures.add( + executor.submit(() -> { + start.await(); + + long now; + long lastOwn = System.nanoTime(); + long lastShared; + do { + lastShared = sharedTime.getAcquire(); + now = System.nanoTime(); + if (now - lastOwn < 0) { + throw new AssertionError( + "System.nanoTime is not monotonic on a single thread: %d < %d" + .formatted(now, lastOwn)); + } + if (now - lastShared < 0) { + throw new AssertionError( + "System.nanoTime is not monotonic across threads: %d < %d" + .formatted(now, lastShared)); + } + sharedTime.setRelease(now); + lastOwn = now; + } while (now < deadline); + return null; + })); + } + } + for (var future : futures) { + future.get(); + } + } +} diff --git a/test/micro/org/openjdk/bench/java/lang/SystemTime.java b/test/micro/org/openjdk/bench/java/lang/SystemTime.java index 6b12097f4a5..552d82bbffb 100644 --- a/test/micro/org/openjdk/bench/java/lang/SystemTime.java +++ b/test/micro/org/openjdk/bench/java/lang/SystemTime.java @@ -28,6 +28,7 @@ import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; import java.time.Instant; @@ -50,6 +51,12 @@ public long nanoTime() { return System.nanoTime(); } + @Benchmark + @Threads(Threads.MAX) + public long nanoTimeContended() { + return System.nanoTime(); + } + @Benchmark public long instantNowAsEpochNanos() { Instant now = Instant.now(); From 2e2c2abfc6fb26f943673e262ccd4d99073c9470 Mon Sep 17 00:00:00 2001 From: Alexey Ivanov Date: Fri, 20 Nov 2026 18:55:12 +0000 Subject: [PATCH 33/95] 8316165: GIF image with one frame set to loop indefinitely causes excessive memory usage Reviewed-by: prr, jdv --- .../sun/awt/image/GifImageDecoder.java | 11 +- .../classes/sun/awt/image/ImageFetcher.java | 17 ++ test/jdk/ProblemList.txt | 1 + .../javax/imageio/plugins/gif/GIFWriter.java | 216 ++++++++++++++++ .../awt/image/gif/GIFLoopAnimationTest.java | 237 ++++++++++++++++++ 5 files changed, 479 insertions(+), 3 deletions(-) create mode 100644 test/jdk/javax/imageio/plugins/gif/GIFWriter.java create mode 100644 test/jdk/sun/awt/image/gif/GIFLoopAnimationTest.java diff --git a/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java b/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java index a8deaa71a4b..e6b6b07a564 100644 --- a/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java +++ b/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -242,7 +242,12 @@ public void produceImage() throws IOException, ImageFormatException { // Fall through case TERMINATOR: - if (nloops == 0 || nloops-- >= 0) { + if (isAnimation && totalframes == 1) { + isAnimation = false; + ImageFetcher.stoppingAnimation(); + } + + if (isAnimation && (nloops == 0 || nloops-- >= 0)) { try { if (curframe != null) { curframe.dispose(); @@ -257,7 +262,7 @@ public void produceImage() throws IOException, ImageFormatException { return; // Unable to reset input buffer } } - if (verbose && frameno != 1) { + if (verbose) { System.out.println("processing GIF terminator," + " frames: " + frameno + " total: " + totalframes); diff --git a/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java b/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java index 986b79edde9..4dd6febbde6 100644 --- a/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java +++ b/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java @@ -217,6 +217,10 @@ private void fetchloop() { * Recycles this ImageFetcher thread as an image animator thread. * Removes this ImageFetcher from the array of ImageFetchers, and * resets the thread name to "ImageAnimator". + *

+ * Note: This method must be called only from + * an {@code ImageFetcher} thread. + * @see #stoppingAnimation() */ static void startingAnimation() { final FetcherInfo info = FetcherInfo.getFetcherInfo(); @@ -238,6 +242,19 @@ static void startingAnimation() { me.setName("Image Animator"); } + /** + * Returns the current animator thread into the pool as + * an {@code ImageFetcher} if possible. + *

+ * Note: This method must be called only from + * an {@code ImageFetcher} thread. + * @see #startingAnimation() + * @see #stoppingAnimation(Thread) + */ + static void stoppingAnimation() { + stoppingAnimation(Thread.currentThread()); + } + /** * Returns this image animator thread back to service as an ImageFetcher * if possible. Puts it back into the array of ImageFetchers and sets diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index 972c9e06876..3e3cabaa968 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -216,6 +216,7 @@ sun/java2d/SunGraphics2D/PolyVertTest.java#opengl 8392801 linux-all sun/java2d/SunGraphics2D/SimplePrimQuality.java#default 6322554,8392436 windows-all,macosx-all sun/java2d/SunGraphics2D/SimplePrimQuality.java#nod3d 6322554 windows-all sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java 8392471 linux-all +sun/awt/image/gif/GIFLoopAnimationTest.java#five-frames-loop5 8396534 generic-all java/awt/FullScreen/DisplayChangeVITest/DisplayChangeVITest.java 8169469,8273617 windows-all,macosx-aarch64 java/awt/FullScreen/SetFSWindow/FSFrame.java#default 8390445 macosx-aarch64 diff --git a/test/jdk/javax/imageio/plugins/gif/GIFWriter.java b/test/jdk/javax/imageio/plugins/gif/GIFWriter.java new file mode 100644 index 00000000000..3f37b0d3835 --- /dev/null +++ b/test/jdk/javax/imageio/plugins/gif/GIFWriter.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.image.BufferedImage; +import java.awt.image.IndexColorModel; +import java.io.File; +import java.io.IOException; + +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageTypeSpecifier; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.metadata.IIOInvalidTreeException; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.metadata.IIOMetadataNode; +import javax.imageio.stream.ImageOutputStream; + +import org.w3c.dom.NodeList; + +/** + * Utility class to create animated GIF images with the specified number + * of frames and loop count. The frames are generated as the image is + * written into the file. + */ +public final class GIFWriter implements AutoCloseable { + private static final int WIDTH = 100; + private static final int HEIGHT = 100; + private static final int STROKE = 4; + + /** + * The image that stores the current frame. + */ + private final BufferedImage image; + + private final ImageWriter writer; + private final ImageOutputStream outputStream; + + /** Number of frames. */ + private final int frameCount; + /** Number of animation loops. */ + private final int loopCount; + + private int x; + private int y; + + /** + * Creates a {@code GIFWriter} object which allows creating + * different types of GIF images, including animated. + * @param fileName file name to write the image + * @param frameCount number of frames to write + * @param loopCount number of animation loops + */ + public GIFWriter(final String fileName, + final int frameCount, + final int loopCount) throws IOException { + if (frameCount <= 0) { + throw new IllegalArgumentException("frameCount must be positive"); + } + this.frameCount = frameCount; + + if (loopCount < 0) { + throw new IllegalArgumentException("loopCount cannot be negative"); + } + this.loopCount = loopCount; + + this.image = new BufferedImage(WIDTH, HEIGHT, + BufferedImage.TYPE_BYTE_INDEXED, + createIndexColorModel()); + createNextFrame(); + + + writer = ImageIO.getImageWritersByFormatName("GIF").next(); + outputStream = ImageIO.createImageOutputStream(new File(fileName)); + writer.setOutput(outputStream); + } + + /** + * Write the frames into the image stream. + * @throws IOException if an error occurs during writing. + */ + public void writeFrames() throws IOException { + final ImageWriteParam writeParam = writer.getDefaultWriteParam(); + final ImageTypeSpecifier type = + ImageTypeSpecifier.createFromRenderedImage(image); + + writer.prepareWriteSequence( + writer.getDefaultStreamMetadata(writeParam)); + + IIOMetadata meta = writer.getDefaultImageMetadata(type, writeParam); + if (loopCount != 1) { + setLoopCount(meta, loopCount); + } + writer.writeToSequence(new IIOImage(image, null, meta), + writeParam); + + for (int i = 1; i < frameCount; i++) { + createNextFrame(); + + meta = writer.getDefaultImageMetadata(type, writeParam); + writer.writeToSequence(new IIOImage(image, null, meta), + writeParam); + } + + writer.endWriteSequence(); + } + + /** + * Renders a frame into the image and + * adjusts the {@code x } and {@code y} coordinates. + */ + private void createNextFrame() { + Graphics g = image.createGraphics(); + g.setColor(Color.WHITE); + g.fillRect(0, 0, WIDTH, HEIGHT); + + g.setColor(Color.RED); + g.fillRect(x, 0, STROKE, HEIGHT); + + g.setColor(Color.BLUE); + g.fillRect(STROKE, y, WIDTH, STROKE); + + g.setColor(Color.GREEN); + g.fillRect(x + WIDTH / 2, y + HEIGHT / 2, + STROKE, STROKE); + + x += STROKE; + y += STROKE; + + x %= WIDTH; + y %= HEIGHT; + + g.dispose(); + } + + private static void setLoopCount(IIOMetadata meta, int loopCount) + throws IIOInvalidTreeException { + String formatName = meta.getNativeMetadataFormatName(); + + IIOMetadataNode loopNode = new IIOMetadataNode("ApplicationExtension"); + loopNode.setAttribute("applicationID", "NETSCAPE"); + loopNode.setAttribute("authenticationCode", "2.0"); + loopNode.setUserObject(new byte[] { + 0x01, + (byte) (loopCount & 0xff), + (byte) ((loopCount >> 8) & 0xff) + }); + + IIOMetadataNode root = (IIOMetadataNode) meta.getAsTree(formatName); + + IIOMetadataNode exts = getMetaNode(root, "ApplicationExtensions"); + exts.appendChild(loopNode); + + meta.setFromTree(formatName, root); + } + + private static IIOMetadataNode getMetaNode(IIOMetadataNode root, + String name) { + NodeList nodes = root.getElementsByTagName(name); + if (nodes.getLength() > 0) { + return (IIOMetadataNode) nodes.item(0); + } + + IIOMetadataNode node = new IIOMetadataNode(name); + root.appendChild(node); + return node; + } + + /** + * {@inheritDoc} + * @throws Exception {@inheritDoc} + */ + @Override + public void close() throws IOException { + outputStream.close(); + writer.dispose(); + } + + /** + * Creates an {@code IndexColorModel} that contains five colors: + * black, red, green, blue, and white. + * + * @return the {@code IndexColorModel} with the five colors + */ + private static IndexColorModel createIndexColorModel() { + byte[] r = {(byte)0x00, (byte)0xFF, (byte)0x00, (byte)0x00, (byte)0xFF}; + byte[] g = {(byte)0x00, (byte)0x00, (byte)0xFF, (byte)0x00, (byte)0xFF}; + byte[] b = {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0xFF, (byte)0xFF}; + + return new IndexColorModel(8, r.length, + r, g, b); + } + +} diff --git a/test/jdk/sun/awt/image/gif/GIFLoopAnimationTest.java b/test/jdk/sun/awt/image/gif/GIFLoopAnimationTest.java new file mode 100644 index 00000000000..899b3803263 --- /dev/null +++ b/test/jdk/sun/awt/image/gif/GIFLoopAnimationTest.java @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Dimension; +import java.awt.Image; +import java.awt.image.ImageObserver; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CountDownLatch; + +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.SwingUtilities; + +import static java.util.concurrent.TimeUnit.SECONDS; + +/* + * @ test id=one-frame + * @ignore Sanity check + * @key headful + * @summary One-frame GIF without loop extension doesn't animate + * @library /javax/imageio/plugins/gif + * @build GIFWriter + * @run main GIFLoopAnimationTest one-frame + */ + +/* + * @test id=one-frame-loop + * @bug 8316165 + * @key headful + * @summary One-frame GIF with the infinite loop stops animation + * @library /javax/imageio/plugins/gif + * @build GIFWriter + * @run main GIFLoopAnimationTest one-frame-loop + */ + +/* + * @test id=one-frame-loop2 + * @bug 8316165 + * @key headful + * @summary One-frame GIF with a fixed loop repeat stops animating + * @library /javax/imageio/plugins/gif + * @build GIFWriter + * @run main GIFLoopAnimationTest one-frame-loop2 + */ + +/* + * @test id=five-frames + * @key headful + * @summary Five-frame GIF without loop stops animating at the last frame + * @library /javax/imageio/plugins/gif + * @build GIFWriter + * @run main GIFLoopAnimationTest five-frames + */ + +/* + * @test id=five-frames-loop5 + * @bug 8396534 + * @key headful + * @summary Five-frame GIF with 5 repeats stops animating after + * repeating animation 5 times + * @library /javax/imageio/plugins/gif + * @build GIFWriter + * @run main GIFLoopAnimationTest five-frames-loop5 + */ + +public final class GIFLoopAnimationTest { + + private static JFrame frame; + + private record TestData(String fileName, + int frameCount, + int loopCount) { + } + + private static final List testList = + List.of(new TestData("one-frame.gif", 1, 1), + new TestData("one-frame-loop.gif", 1, 0), + new TestData("one-frame-loop2.gif", 1, 2), + new TestData("five-frames.gif", 5, 1), + new TestData("five-frames-loop5.gif", 5, 5) + ); + + + private static final CountDownLatch done = new CountDownLatch(1); + // Access to the error is synchronized by the above latch + private static Throwable error; + + + private static void createGIFImage(final TestData test) throws IOException { + try (GIFWriter gifWriter = new GIFWriter(test.fileName, + test.frameCount, + test.loopCount)) { + gifWriter.writeFrames(); + } + } + + public static void main(String[] args) throws Throwable { + if (args.length != 1) { + throw new IllegalArgumentException( + "Pass a test name as the first and only argument"); + } + + final TestData test = + testList.stream() + .filter(t -> t.fileName.startsWith(args[0])) + .findFirst() + .orElseThrow(); + + + System.out.println("Starting " + test); + createGIFImage(test); + + SwingUtilities.invokeAndWait(() -> createUI(test)); + + try { + if (test.loopCount == 1 && test.frameCount == 1) { + if (done.await(3, SECONDS)) { + throw new RuntimeException("imageUpdate should not be called for one-frame GIF"); + } + } + + if (done.await(3, SECONDS)) { + if (error != null) { + throw error; + } + } + + System.out.println("Test: " + test + " - passed"); + } finally { + SwingUtilities.invokeAndWait(GIFLoopAnimationTest::disposeUI); + } + } + + private static JLabel createGIFLabel(final TestData test) { + return new JLabel(new ImageIcon(test.fileName)) { + private int frame = 0; + @Override + public boolean imageUpdate(Image img, int flags, + int x, int y, int w, int h) { + if (test.frameCount == 1 && test.loopCount == 1) { + error = new Error( + "Animation must not start for one-frame image - " + + "imageUpdate must never be called"); + done.countDown(); + } + + final boolean result = super.imageUpdate(img, flags, x, y, w, h); + if ((flags & (ImageObserver.ALLBITS + | ImageObserver.FRAMEBITS)) == 0) { + // Skip any other invocations of imageUpdate + return result; + } + + System.out.println("> imageUpdate: " + frame); + + if ((flags & ImageObserver.ALLBITS) != 0) { + System.out.println(" ALLBITS"); + done.countDown(); + } else if ((flags & ImageObserver.FRAMEBITS) != 0) { + System.out.println(" FRAMEBITS"); + System.out.println(" " + (++frame)); + + if (test.frameCount == 1) { + error = new Error( + "GIF with one frame should stop animating " + + "after showing the frame"); + done.countDown(); + } + + if (test.loopCount != 0) { + if (frame > test.frameCount * test.loopCount) { + error = new Error( + "GIF with fixed number of loops should stop " + + "animating after repeating animation loop " + + "the specified amount of times"); + System.out.println(" too many loops"); + done.countDown(); + } + } else { + System.out.println(" infinite looping"); + if (frame > 500) { + if (error != null) { + error = new Error("Infinite animation - too many frames"); + } + done.countDown(); + } + } + } + + System.out.println("< imageUpdate"); + return result; + } + }; + } + + private static void createUI(TestData test) { + JLabel gifLabel = createGIFLabel(test); + + frame = new JFrame("GIF Loop Animation Test"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + frame.setMinimumSize(new Dimension(300, 200)); + frame.add(gifLabel); + frame.pack(); + + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void disposeUI() { + if (frame != null) { + frame.dispose(); + } + } +} From 08dc919f2d59542747c94e010254a58f8f0e6f44 Mon Sep 17 00:00:00 2001 From: Ashay Rane Date: Fri, 20 Nov 2026 19:24:12 +0000 Subject: [PATCH 34/95] 8397853: Make local datagram tests use loopback address Reviewed-by: djelinski --- test/jdk/java/net/DatagramSocket/SendSize.java | 6 +++--- test/jdk/java/nio/channels/DatagramChannel/Sender.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/jdk/java/net/DatagramSocket/SendSize.java b/test/jdk/java/net/DatagramSocket/SendSize.java index 3dd75f66f81..4e3798d5292 100644 --- a/test/jdk/java/net/DatagramSocket/SendSize.java +++ b/test/jdk/java/net/DatagramSocket/SendSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public class SendSize { public static void main(String[] args) throws Exception { DatagramSocket serverSocket = new DatagramSocket( - new InetSocketAddress(InetAddress.getLocalHost(), 0) + new InetSocketAddress(InetAddress.getLoopbackAddress(), 0) ); Thread server = new ServerThread(serverSocket); server.start(); @@ -99,7 +99,7 @@ static class ClientThread extends Thread { ClientThread(int serverPort)throws IOException { this.serverPort = serverPort; - this.host = InetAddress.getLocalHost(); + this.host = InetAddress.getLoopbackAddress(); this.client = new DatagramSocket(); } diff --git a/test/jdk/java/nio/channels/DatagramChannel/Sender.java b/test/jdk/java/nio/channels/DatagramChannel/Sender.java index fcecdf9d79a..54c2d77bf2d 100644 --- a/test/jdk/java/nio/channels/DatagramChannel/Sender.java +++ b/test/jdk/java/nio/channels/DatagramChannel/Sender.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -87,7 +87,7 @@ public void run() { bb.order(ByteOrder.BIG_ENDIAN); bb.putInt(1).putLong(1); bb.flip(); - InetAddress address = InetAddress.getLocalHost(); + InetAddress address = InetAddress.getLoopbackAddress(); InetSocketAddress isa = new InetSocketAddress(address, port); if (Platform.isOSX()) { // avoid binding on wildcard on macOS @@ -109,7 +109,7 @@ public static class Server implements Runnable, AutoCloseable { Server() throws IOException { // avoid binding to wildcard address on macOS InetSocketAddress lo = Platform.isOSX() - ? new InetSocketAddress(InetAddress.getLocalHost(), 0) + ? new InetSocketAddress(InetAddress.getLoopbackAddress(), 0) : new InetSocketAddress(0); dc = DatagramChannel.open().bind(lo); } From b76004bf59b75303c539de649ce9321fd8d28cf3 Mon Sep 17 00:00:00 2001 From: Alexander Zuev Date: Fri, 20 Nov 2026 22:10:30 +0000 Subject: [PATCH 35/95] 8390445: [macos] Test java/awt/FullScreen/SetFSWindow/FSFrame.java failed: Some pixel colors not correct Reviewed-by: azvegint, prr --- test/jdk/ProblemList.txt | 1 - test/jdk/java/awt/FullScreen/SetFSWindow/FSFrame.java | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index 3e3cabaa968..3f29d253a11 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -219,7 +219,6 @@ sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java 8392 sun/awt/image/gif/GIFLoopAnimationTest.java#five-frames-loop5 8396534 generic-all java/awt/FullScreen/DisplayChangeVITest/DisplayChangeVITest.java 8169469,8273617 windows-all,macosx-aarch64 -java/awt/FullScreen/SetFSWindow/FSFrame.java#default 8390445 macosx-aarch64 java/awt/FullScreen/UninitializedDisplayModeChangeTest/UninitializedDisplayModeChangeTest.java 8273617 macosx-all java/awt/Component/GetScreenLocTest/GetScreenLocTest.java 4753654 generic-all java/awt/Clipboard/PasteNullToTextComponentsTest.java 8234140 macosx-all,windows-all diff --git a/test/jdk/java/awt/FullScreen/SetFSWindow/FSFrame.java b/test/jdk/java/awt/FullScreen/SetFSWindow/FSFrame.java index 69ce6047aac..7272fef83bc 100644 --- a/test/jdk/java/awt/FullScreen/SetFSWindow/FSFrame.java +++ b/test/jdk/java/awt/FullScreen/SetFSWindow/FSFrame.java @@ -101,10 +101,10 @@ void checkFSDisplay(boolean fsSupported) { // fill color boolean colorCorrect = true; - colorCorrect &= checkColor(0, 0, bImg); - colorCorrect &= checkColor(0, bImg.getHeight() - 1, bImg); - colorCorrect &= checkColor(bImg.getWidth() - 1, 0, bImg); - colorCorrect &= checkColor(bImg.getWidth() - 1, bImg.getHeight() - 1, bImg); + colorCorrect &= checkColor(5, 5, bImg); + colorCorrect &= checkColor(5, bImg.getHeight() - 6, bImg); + colorCorrect &= checkColor(bImg.getWidth() - 6, 5, bImg); + colorCorrect &= checkColor(bImg.getWidth() - 6, bImg.getHeight() - 6, bImg); colorCorrect &= checkColor(bImg.getWidth() / 2, bImg.getHeight() / 2, bImg); if (!colorCorrect) { System.err.println("Test failed for mode: fsSupported="+fsSupported); From 78bf06f425a99c26dbbc39b81aecf0912a50190b Mon Sep 17 00:00:00 2001 From: Leonid Mesnik Date: Sat, 21 Nov 2026 04:12:08 +0000 Subject: [PATCH 36/95] 8397860: Add vm.flagless requirements to hotspot tests ignoring flags Reviewed-by: dholmes, sspitsyn, cjplummer --- test/hotspot/jtreg/compiler/splitif/TestTraceSplitIf.java | 1 + .../jtreg/gc/g1/TestConcParallelGCThreadsCombinations.java | 1 + test/hotspot/jtreg/gc/g1/TestMinHeapDeltaBytes.java | 1 + test/hotspot/jtreg/gc/g1/TestOptionalRegionGC.java | 3 ++- .../hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java | 1 + test/hotspot/jtreg/gc/z/TestZAllocationSpikeTolerance.java | 1 + .../jtreg/runtime/ErrorHandling/TestAVXRegisterDump.java | 1 + .../runtime/StackGuardPages/TestStackGuardPagesNative.java | 1 + test/hotspot/jtreg/runtime/logging/RelocatorTest.java | 1 + .../valhalla/valuetypes/TestValueObjectMethodsInit.java | 1 + 10 files changed, 11 insertions(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/compiler/splitif/TestTraceSplitIf.java b/test/hotspot/jtreg/compiler/splitif/TestTraceSplitIf.java index 32f3a213215..389c7c09b1c 100644 --- a/test/hotspot/jtreg/compiler/splitif/TestTraceSplitIf.java +++ b/test/hotspot/jtreg/compiler/splitif/TestTraceSplitIf.java @@ -27,6 +27,7 @@ * @summary Sanity test for -XX:+TraceSplitIf to ensure it doesn't crash and produces output. * @library /test/lib * @requires vm.compiler2.enabled & vm.debug + * @requires vm.flagless * @run driver ${test.main.class} */ diff --git a/test/hotspot/jtreg/gc/g1/TestConcParallelGCThreadsCombinations.java b/test/hotspot/jtreg/gc/g1/TestConcParallelGCThreadsCombinations.java index 81808658dbf..5e6a4c20c40 100644 --- a/test/hotspot/jtreg/gc/g1/TestConcParallelGCThreadsCombinations.java +++ b/test/hotspot/jtreg/gc/g1/TestConcParallelGCThreadsCombinations.java @@ -27,6 +27,7 @@ * @test * @bug 8395992 * @requires vm.gc.G1 + * @requires vm.flagless * @summary Test valid and invalid combinations of ConcGCThreads and ParallelGCThreads and the expected error message when invalid. * @library /test/lib * @modules java.base/jdk.internal.misc diff --git a/test/hotspot/jtreg/gc/g1/TestMinHeapDeltaBytes.java b/test/hotspot/jtreg/gc/g1/TestMinHeapDeltaBytes.java index a38772c0087..7e68db663b9 100644 --- a/test/hotspot/jtreg/gc/g1/TestMinHeapDeltaBytes.java +++ b/test/hotspot/jtreg/gc/g1/TestMinHeapDeltaBytes.java @@ -28,6 +28,7 @@ * @bug 8394507 * @summary G1 heap expansion must not truncate a large region count. * @requires vm.gc.G1 & (vm.bits == "64") + * @requires vm.flagless * @library /test/lib * @run driver gc.g1.TestMinHeapDeltaBytes */ diff --git a/test/hotspot/jtreg/gc/g1/TestOptionalRegionGC.java b/test/hotspot/jtreg/gc/g1/TestOptionalRegionGC.java index 3a5bb17fffc..0edca8c79c7 100644 --- a/test/hotspot/jtreg/gc/g1/TestOptionalRegionGC.java +++ b/test/hotspot/jtreg/gc/g1/TestOptionalRegionGC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @summary Tests optional evacuation. * @requires vm.gc.G1 * @requires vm.debug + * @requires vm.flagless * @library /test/lib * @build jdk.test.whitebox.WhiteBox * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox diff --git a/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java b/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java index 385b3da1d45..e11d6d85ba4 100644 --- a/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java +++ b/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java @@ -28,6 +28,7 @@ * @bug 8396872 * @requires vm.gc.G1 * @requires vm.bits != "32" + * @requires vm.flagless * @summary Test that the VM does not start with heaps exceeding maximum region indexes. * @library /test/lib * @modules java.base/jdk.internal.misc diff --git a/test/hotspot/jtreg/gc/z/TestZAllocationSpikeTolerance.java b/test/hotspot/jtreg/gc/z/TestZAllocationSpikeTolerance.java index 678829c33e7..94e477aa80d 100644 --- a/test/hotspot/jtreg/gc/z/TestZAllocationSpikeTolerance.java +++ b/test/hotspot/jtreg/gc/z/TestZAllocationSpikeTolerance.java @@ -29,6 +29,7 @@ * - succeeds for valid value * @library /test/lib * @requires vm.gc.Z + * @requires vm.flagless * @run driver gc.z.TestZAllocationSpikeTolerance */ package gc.z; diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestAVXRegisterDump.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestAVXRegisterDump.java index 59692d94d2f..09685c69fd9 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestAVXRegisterDump.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestAVXRegisterDump.java @@ -28,6 +28,7 @@ * @requires os.family == "linux" & os.arch == "amd64" * @requires vm.cpu.features ~= ".*avx.*" * @requires vm.debug == true + * @requires vm.flagless * @modules java.base/jdk.internal.misc * @build jdk.test.whitebox.WhiteBox * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox diff --git a/test/hotspot/jtreg/runtime/StackGuardPages/TestStackGuardPagesNative.java b/test/hotspot/jtreg/runtime/StackGuardPages/TestStackGuardPagesNative.java index 7d3aae549e1..0b2ff64828d 100644 --- a/test/hotspot/jtreg/runtime/StackGuardPages/TestStackGuardPagesNative.java +++ b/test/hotspot/jtreg/runtime/StackGuardPages/TestStackGuardPagesNative.java @@ -28,6 +28,7 @@ * @library /test/lib * @requires os.family == "linux" * @requires !jdk.static + * @requires vm.flagless * @compile DoOverflow.java * @run main/native TestStackGuardPagesNative */ diff --git a/test/hotspot/jtreg/runtime/logging/RelocatorTest.java b/test/hotspot/jtreg/runtime/logging/RelocatorTest.java index edbe71f2638..82f110328ec 100644 --- a/test/hotspot/jtreg/runtime/logging/RelocatorTest.java +++ b/test/hotspot/jtreg/runtime/logging/RelocatorTest.java @@ -29,6 +29,7 @@ * @modules java.compiler * java.instrument * @requires vm.jvmti + * @requires vm.flagless * @run main RedefineClassHelper * @run driver RelocatorTest */ diff --git a/test/hotspot/jtreg/runtime/valhalla/valuetypes/TestValueObjectMethodsInit.java b/test/hotspot/jtreg/runtime/valhalla/valuetypes/TestValueObjectMethodsInit.java index dedbe4be227..0fac1e7ac81 100644 --- a/test/hotspot/jtreg/runtime/valhalla/valuetypes/TestValueObjectMethodsInit.java +++ b/test/hotspot/jtreg/runtime/valhalla/valuetypes/TestValueObjectMethodsInit.java @@ -27,6 +27,7 @@ * @summary Test ValueObjectMethods class initialization * @bug 8391022 * @requires vm.cds.supports.aot.class.linking + * @requires vm.flagless * @comment DeoptimizeALot flag requires debug VM * @requires vm.debug * @library /test/lib From 670f6dc2c6a90003c4e7fbc92799ae7baf25b469 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Mon, 23 Nov 2026 06:41:03 +0000 Subject: [PATCH 37/95] 8388340: javac rejects a legal class modifier ordering when sealed follows the value modifier Reviewed-by: vromero --- .../sun/tools/javac/parser/JavacParser.java | 115 +++--- .../tools/javac/lvti/ParserTest.java | 2 + .../langtools/tools/javac/lvti/ParserTest.out | 24 +- .../tools/javac/lvti/ParserTest9.out | 36 +- .../javac/sealed/SealedCompilationTests.java | 2 +- .../value-objects/SourceLevelChecks.java | 377 ++++++++++++++++++ .../ValueObjectCompilationTests.java | 93 ++++- .../VarInImplicitLambdaNegTest01.java | 9 +- .../VarInImplicitLambdaNegTest01.out | 14 +- .../VarInImplicitLambdaNegTest01_source10.out | 12 +- 10 files changed, 588 insertions(+), 96 deletions(-) create mode 100644 test/langtools/tools/javac/valhalla/value-objects/SourceLevelChecks.java diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java index 4b56adae03c..df113495199 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java @@ -1093,10 +1093,10 @@ public JCExpression unannotatedType(boolean allowVar) { public JCExpression unannotatedType(boolean allowVar, int newmode) { JCExpression result = term(newmode); - Name restrictedTypeName = restrictedTypeName(result, !allowVar); + JCIdent restrictedTypeTree = restrictedTypeName(result, !allowVar); - if (restrictedTypeName != null && (!allowVar || restrictedTypeName != names.var)) { - syntaxError(result.pos, Errors.RestrictedTypeNotAllowedHere(restrictedTypeName)); + if (restrictedTypeTree != null && (!allowVar || restrictedTypeTree.name != names.var)) { + syntaxError(restrictedTypeTree.pos, Errors.RestrictedTypeNotAllowedHere(restrictedTypeTree.name)); } if ((lastmode & TYPE) == 0) { @@ -2162,13 +2162,14 @@ JCExpression lambdaExpressionOrStatement(boolean hasParens, boolean explicitPara if (explicitParams) { LambdaClassifier lambdaClassifier = new LambdaClassifier(); for (JCVariableDecl param: params) { - Name restrictedTypeName; + JCIdent restrictedTypeTree; if (param.vartype != null && - (restrictedTypeName = restrictedTypeName(param.vartype, false)) != null && - param.vartype.hasTag(TYPEARRAY)) { + (restrictedTypeTree = restrictedTypeName(param.vartype, false)) != null && + skipAnnotatedType(param.vartype).hasTag(TYPEARRAY)) { log.error(DiagnosticFlag.SYNTAX, param.pos, Feature.VAR_SYNTAX_IMPLICIT_LAMBDAS.allowedInSource(source) - ? Errors.RestrictedTypeNotAllowedArray(restrictedTypeName) : Errors.RestrictedTypeNotAllowedHere(restrictedTypeName)); + ? Errors.RestrictedTypeNotAllowedArray(restrictedTypeTree.name) + : Errors.RestrictedTypeNotAllowedHere(restrictedTypeTree.name)); } lambdaClassifier.addParameter(param); if (lambdaClassifier.result() == LambdaParameterKind.ERROR) { @@ -2190,6 +2191,10 @@ && restrictedTypeName(param.vartype, true) != null) { return lambdaExpressionOrStatementRest(params, pos); } + private JCTree skipAnnotatedType(JCTree type) { + return type instanceof JCAnnotatedType at ? at.underlyingType + : type; + } enum LambdaParameterKind { VAR(0), EXPLICIT(1), @@ -3013,8 +3018,7 @@ List blockStatement() { } } } - if ((isValueModifier()) && allowValueClasses) { - checkSourceLevel(Feature.VALUE_CLASSES); + if (isValueModifier(true)) { dc = token.docComment(); return List.of(classOrRecordOrInterfaceOrEnumDeclaration(modifiersOpt(), dc)); } @@ -3631,8 +3635,7 @@ protected JCModifiers modifiersOpt(JCModifiers partial) { flag = Flags.SEALED; break; } - if (isValueModifier()) { - checkSourceLevel(Feature.VALUE_CLASSES); + if (isValueModifier(false)) { flag = Flags.VALUE_CLASS; break; } @@ -3845,7 +3848,7 @@ JCVariableDecl variableDeclaratorRest(int pos, JCModifiers mods, JCExpression ty if (restrictedTypeNameStartingAtSource(typeName, pos, !compound && localDecl) != null) { if (typeName != names.var) { reportSyntaxError(elemType.pos, Errors.RestrictedTypeNotAllowedHere(typeName)); - } else if (type.hasTag(TYPEARRAY) && !compound) { + } else if (skipAnnotatedType(type).hasTag(TYPEARRAY) && !compound) { //error - 'var' and arrays reportSyntaxError(elemType.pos, Errors.RestrictedTypeNotAllowedArray(typeName)); } else { @@ -3870,12 +3873,14 @@ JCExpression replaceTypeWithVar(JCExpression type) { return varType; } - Name restrictedTypeName(JCExpression e, boolean shouldWarn) { + JCIdent restrictedTypeName(JCExpression e, boolean shouldWarn) { switch (e.getTag()) { case IDENT: - return restrictedTypeNameStartingAtSource(((JCIdent)e).name, e.pos, shouldWarn) != null ? ((JCIdent)e).name : null; + return restrictedTypeNameStartingAtSource(((JCIdent)e).name, e.pos, shouldWarn) != null ? (JCIdent)e : null; case TYPEARRAY: return restrictedTypeName(((JCArrayTypeTree)e).elemtype, shouldWarn); + case ANNOTATED_TYPE: + return restrictedTypeName(((JCAnnotatedType)e).underlyingType, shouldWarn); default: return null; } @@ -5010,8 +5015,10 @@ protected boolean isRecordStart() { protected boolean isNonSealedClassStart(boolean local) { if (isNonSealedIdentifier(token, 0)) { - Token next = S.token(3); - return allowedAfterSealedOrNonSealed(next, local, true); + if (allowedAfterSealedNonSealedOrValue(3, local)) { + checkSourceLevel(Feature.SEALED_CLASSES); + return true; + } } return false; } @@ -5023,32 +5030,16 @@ protected boolean isNonSealedIdentifier(Token someToken, int lookAheadOffset) { if (someToken.endPos == tokenSub.pos && tokenSub.endPos == tokenSealed.pos && tokenSealed.name() == names.sealed) { - checkSourceLevel(Feature.SEALED_CLASSES); return true; } } return false; } - protected boolean isValueModifier() { + protected boolean isValueModifier(boolean local) { if (token.kind == IDENTIFIER && token.name() == names.value) { - boolean isValueModifier = false; - Token next = S.token(1); - switch (next.kind) { - case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case TRANSIENT: - case FINAL: case ABSTRACT: case NATIVE: case VOLATILE: case SYNCHRONIZED: - case STRICTFP: case MONKEYS_AT: case DEFAULT: case BYTE: case SHORT: - case CHAR: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case VOID: - case CLASS: case INTERFACE: case ENUM: - isValueModifier = true; - break; - case IDENTIFIER: // value record R || value value - if (next.name() == names.record || next.name() == names.value - || (mode & EXPR) != 0) - isValueModifier = true; - break; - } - if (isValueModifier) { + if (allowedAfterSealedNonSealedOrValue(1, local)) { + checkSourceLevel(Feature.VALUE_CLASSES); return true; } } @@ -5057,8 +5048,7 @@ protected boolean isValueModifier() { protected boolean isSealedClassStart(boolean local) { if (token.name() == names.sealed) { - Token next = S.token(1); - if (allowedAfterSealedOrNonSealed(next, local, false)) { + if (allowedAfterSealedNonSealedOrValue(1, local)) { checkSourceLevel(Feature.SEALED_CLASSES); return true; } @@ -5066,27 +5056,46 @@ protected boolean isSealedClassStart(boolean local) { return false; } - private boolean allowedAfterSealedOrNonSealed(Token next, boolean local, boolean currentIsNonSealed) { - return local ? + private boolean allowedAfterSealedNonSealedOrValue(int lookahead, boolean local) { + while (true) { + Token next = S.token(lookahead); switch (next.kind) { case MONKEYS_AT -> { - Token afterNext = S.token(2); - yield afterNext.kind != INTERFACE || currentIsNonSealed; + Token afterNext = S.token(lookahead + 1); + if (afterNext.kind == INTERFACE) { + return true; + } + lookahead = skipAnnotation(lookahead) + 1; } - case ABSTRACT, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true; - default -> false; - } : - switch (next.kind) { - case MONKEYS_AT -> { - Token afterNext = S.token(2); - yield afterNext.kind != INTERFACE || currentIsNonSealed; + case ABSTRACT, STATIC, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> {return true;} + case PUBLIC, PROTECTED, PRIVATE -> {return !local;} + case VOID, BOOLEAN, BYTE, SHORT, CHAR, INT, LONG, FLOAT, DOUBLE -> {return true;} + case IDENTIFIER -> { + if (next.name() == names.record && S.token(lookahead + 1).kind == IDENTIFIER) { + return true; + } else if (isNonSealedIdentifier(next, lookahead)) { + lookahead += 3; + } else if (next.name() == names.sealed || + next.name() == names.value) { + lookahead++; + } else { + switch (S.token(lookahead + 1).kind) { + case IDENTIFIER, DOT, LT -> { + return true; + } + case MONKEYS_AT -> { + //continue search + lookahead++; + } + default -> { + return false; + } + } + } } - case PUBLIC, PROTECTED, PRIVATE, ABSTRACT, STATIC, FINAL, STRICTFP, CLASS, INTERFACE, ENUM -> true; - case IDENTIFIER -> isNonSealedIdentifier(next, currentIsNonSealed ? 3 : 1) || - next.name() == names.sealed || - allowValueClasses && next.name() == names.value; - default -> false; + default -> {return false;} }; + } } /** MethodDeclaratorRest = diff --git a/test/langtools/tools/javac/lvti/ParserTest.java b/test/langtools/tools/javac/lvti/ParserTest.java index 3a561e49ec6..291b6ccefdc 100644 --- a/test/langtools/tools/javac/lvti/ParserTest.java +++ b/test/langtools/tools/javac/lvti/ParserTest.java @@ -43,7 +43,9 @@ void test() { var[][] x3 = null; //illegal var x4[][] = null; //illegal var[] x5 = null; //illegal + var @TA [] x5a = null; //illegal var x6[] = null; //illegal + var x6a @TA [] = null; //illegal var@TA[]@TA[] x7 = null; //illegal var x8@TA[]@TA[] = null; //illegal var x9 = null, y = null; //illegal diff --git a/test/langtools/tools/javac/lvti/ParserTest.out b/test/langtools/tools/javac/lvti/ParserTest.out index ce48e3c261e..7c1cd289fc0 100644 --- a/test/langtools/tools/javac/lvti/ParserTest.out +++ b/test/langtools/tools/javac/lvti/ParserTest.out @@ -11,14 +11,18 @@ ParserTest.java:43:9: compiler.err.restricted.type.not.allowed.array: var ParserTest.java:44:9: compiler.err.restricted.type.not.allowed.array: var ParserTest.java:45:9: compiler.err.restricted.type.not.allowed.array: var ParserTest.java:46:9: compiler.err.restricted.type.not.allowed.array: var -ParserTest.java:49:9: compiler.err.restricted.type.not.allowed.compound: var -ParserTest.java:54:5: compiler.err.restricted.type.not.allowed.here: var -ParserTest.java:58:16: compiler.err.restricted.type.not.allowed.here: var -ParserTest.java:59:14: compiler.err.restricted.type.not.allowed.here: var -ParserTest.java:60:24: compiler.err.restricted.type.not.allowed.here: var -ParserTest.java:61:22: compiler.err.restricted.type.not.allowed.here: var +ParserTest.java:47:9: compiler.err.restricted.type.not.allowed.array: var +ParserTest.java:48:9: compiler.err.restricted.type.not.allowed.array: var +ParserTest.java:49:9: compiler.err.restricted.type.not.allowed.array: var +ParserTest.java:50:9: compiler.err.restricted.type.not.allowed.array: var +ParserTest.java:51:9: compiler.err.restricted.type.not.allowed.compound: var +ParserTest.java:56:5: compiler.err.restricted.type.not.allowed.here: var +ParserTest.java:60:16: compiler.err.restricted.type.not.allowed.here: var +ParserTest.java:61:14: compiler.err.restricted.type.not.allowed.here: var +ParserTest.java:62:24: compiler.err.restricted.type.not.allowed.here: var ParserTest.java:63:22: compiler.err.restricted.type.not.allowed.here: var -ParserTest.java:64:18: compiler.err.restricted.type.not.allowed.here: var -ParserTest.java:68:35: compiler.err.restricted.type.not.allowed.here: var -ParserTest.java:69:22: compiler.err.restricted.type.not.allowed.here: var -23 errors +ParserTest.java:65:22: compiler.err.restricted.type.not.allowed.here: var +ParserTest.java:66:18: compiler.err.restricted.type.not.allowed.here: var +ParserTest.java:70:35: compiler.err.restricted.type.not.allowed.here: var +ParserTest.java:71:22: compiler.err.restricted.type.not.allowed.here: var +27 errors diff --git a/test/langtools/tools/javac/lvti/ParserTest9.out b/test/langtools/tools/javac/lvti/ParserTest9.out index 14714b5a97a..43d6f062fd3 100644 --- a/test/langtools/tools/javac/lvti/ParserTest9.out +++ b/test/langtools/tools/javac/lvti/ParserTest9.out @@ -10,22 +10,24 @@ ParserTest.java:42:13: compiler.warn.restricted.type.not.allowed: var, 10 ParserTest.java:43:17: compiler.warn.restricted.type.not.allowed: var, 10 ParserTest.java:44:13: compiler.warn.restricted.type.not.allowed: var, 10 ParserTest.java:45:15: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:46:13: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:47:23: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:46:20: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:47:13: compiler.warn.restricted.type.not.allowed: var, 10 ParserTest.java:48:13: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:49:13: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:50:23: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:51:23: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:54:5: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:58:16: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:59:14: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:60:24: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:61:22: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:49:23: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:50:13: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:51:13: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:52:23: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:53:23: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:56:5: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:60:16: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:61:14: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:62:24: compiler.warn.restricted.type.not.allowed: var, 10 ParserTest.java:63:22: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:63:40: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:64:18: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:68:35: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:69:22: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:73:24: compiler.warn.restricted.type.not.allowed: var, 10 -ParserTest.java:74:18: compiler.warn.restricted.type.not.allowed: var, 10 -30 warnings \ No newline at end of file +ParserTest.java:65:22: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:65:40: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:66:18: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:70:35: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:71:22: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:75:24: compiler.warn.restricted.type.not.allowed: var, 10 +ParserTest.java:76:18: compiler.warn.restricted.type.not.allowed: var, 10 +32 warnings diff --git a/test/langtools/tools/javac/sealed/SealedCompilationTests.java b/test/langtools/tools/javac/sealed/SealedCompilationTests.java index b7207b777c6..44ae4a0299b 100644 --- a/test/langtools/tools/javac/sealed/SealedCompilationTests.java +++ b/test/langtools/tools/javac/sealed/SealedCompilationTests.java @@ -986,7 +986,7 @@ void testDoNotAllowSealedAnnotation() { non-sealed interface I extends A {} """ )) { - assertFail("compiler.err.class.method.or.field.expected", s); + assertFail("compiler.err.illegal.combination.of.modifiers", s); } } diff --git a/test/langtools/tools/javac/valhalla/value-objects/SourceLevelChecks.java b/test/langtools/tools/javac/valhalla/value-objects/SourceLevelChecks.java new file mode 100644 index 00000000000..420c57a6c24 --- /dev/null +++ b/test/langtools/tools/javac/valhalla/value-objects/SourceLevelChecks.java @@ -0,0 +1,377 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8388340 + * @summary Verify source level checks are performed properly + * @library /tools/lib + * @modules jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * jdk.compiler/com.sun.tools.javac.util + * @build toolbox.ToolBox toolbox.JavacTask + * @run junit SourceLevelChecks +*/ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; + +import toolbox.JavacTask; +import toolbox.Task; +import toolbox.ToolBox; + +import static org.junit.jupiter.api.Assertions.*; + +public class SourceLevelChecks { + + private Path base; + private final ToolBox tb = new ToolBox(); + + @Test + public void testValueAsATypeOld() throws Exception { + Path current = base.resolve("."); + Path lib = current.resolve("lib"); + + Path libSrc = lib.resolve("src"); + Path libClasses = lib.resolve("classes"); + tb.writeJavaFiles(libSrc, + """ + class value {} + """); + + Files.createDirectories(libClasses); + + new JavacTask(tb) + .outdir(libClasses) + .files(tb.findJavaFiles(libSrc)) + .run() + .writeAll(); + + Path test = current.resolve("test"); + Path src = test.resolve("src"); + Path classes = test.resolve("classes"); + tb.writeJavaFiles(src, + """ + class Test { + value record; + value value; + value sealed; + value @A1 [] f1; + value f2[]; + value f2 @A1 []; + value @A1 [] m1() {} + value m2()[] {} + value m2() @A1 [] {} + value @A1 abstract sealed @A2 class C1 {} + sealed @A1 value abstract @A2 class C2 {} + non-sealed @A1 value abstract @A2 class C3 {} + } + @interface A1 {} + @interface A2 {} + """); + + Files.createDirectories(classes); + + record TestCase(List options, Task.Expect expected, List expectedOutput) { + public TestCase(List options, Task.Expect expected, String... expectedOutput) { + this(options, expected, List.of(expectedOutput)); + } + } + String currentVersion = Integer.toString(Runtime.version().feature()); + List expectedValueWarnings = new ArrayList<>(List.of( + "Test.java:2:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:3:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:4:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:5:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:6:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:7:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:8:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:9:5: compiler.warn.restricted.type.not.allowed.preview: value, 28", + "Test.java:10:5: compiler.warn.restricted.type.not.allowed.preview: value, 28" + )); + + TestCase[] testCases = new TestCase[] { + new TestCase(List.of("--release", "16"), + Task.Expect.FAIL, + concat(expectedValueWarnings, + "Test.java:11:5: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "Test.java:11:24: compiler.err.feature.not.supported.in.source.plural: (compiler.misc.feature.sealed.classes), 16, 17", + "2 errors", + "9 warnings")), + new TestCase(List.of("--release", "25"), + Task.Expect.FAIL, + concat(expectedValueWarnings, + "Test.java:11:5: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error", + "9 warnings")), + new TestCase(List.of("--release", currentVersion), + Task.Expect.FAIL, + concat(expectedValueWarnings, + "Test.java:11:5: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error", + "9 warnings")), + new TestCase(List.of("--release", currentVersion, "--enable-preview"), + Task.Expect.FAIL, + "Test.java:2:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:3:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:4:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:5:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:6:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:7:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:8:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:9:5: compiler.err.restricted.type.not.allowed.here: value", + "Test.java:10:5: compiler.err.restricted.type.not.allowed.here: value", + "9 errors") + }; + + for (TestCase testCase : testCases) { + List options = new ArrayList<>(); + + options.addAll(testCase.options()); + options.add("-XDrawDiagnostics"); + + var log = + new JavacTask(tb) + .options(options) + .classpath(libClasses) + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(testCase.expected()) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + assertEquals(testCase.expectedOutput(), log); + } + } + + private List concat(List base, String... additional) { + List result = new ArrayList<>(); + + result.addAll(base); + result.addAll(List.of(additional)); + return result; + } + + @Test + public void testValueNonSealedErrorCheck() throws Exception { + Path current = base.resolve("."); + Path lib = current.resolve("lib"); + + Path libSrc = lib.resolve("src"); + Path libClasses = lib.resolve("classes"); + tb.writeJavaFiles(libSrc, + """ + class value {} + """); + + Files.createDirectories(libClasses); + + new JavacTask(tb) + .outdir(libClasses) + .files(tb.findJavaFiles(libSrc)) + .run() + .writeAll(); + + Path test = current.resolve("test"); + Path src = test.resolve("src"); + Path classes = test.resolve("classes"); + tb.writeJavaFiles(src, + """ + class Test { + value non-sealed class C2 extends C1 {} + sealed class C1 {} + } + """); + + Files.createDirectories(classes); + + record TestCase(List options, Task.Expect expected, String... expectedOutput) {} + String currentVersion = Integer.toString(Runtime.version().feature()); + + TestCase[] testCases = new TestCase[] { + new TestCase(List.of("--release", "16"), + Task.Expect.FAIL, + "Test.java:2:5: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "Test.java:2:11: compiler.err.feature.not.supported.in.source.plural: (compiler.misc.feature.sealed.classes), 16, 17", + "2 errors"), + new TestCase(List.of("--release", "25"), + Task.Expect.FAIL, + "Test.java:2:5: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion), + Task.Expect.FAIL, + "Test.java:2:5: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion, "--enable-preview"), + Task.Expect.FAIL, + "Test.java:2:22: compiler.err.non.abstract.value.class.cant.be.sealed.or.non.sealed", + "- compiler.note.preview.filename: Test.java, DEFAULT", + "- compiler.note.preview.recompile", + "1 error") + }; + + for (TestCase testCase : testCases) { + List options = new ArrayList<>(); + + options.addAll(testCase.options()); + options.add("-XDrawDiagnostics"); + + var log = + new JavacTask(tb) + .options(options) + .classpath(libClasses) + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(testCase.expected()) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + assertEquals(List.of(testCase.expectedOutput()), log); + } + } + + @Test + public void testLocalClassValue() throws Exception { + Path current = base.resolve("."); + Path lib = current.resolve("lib"); + + Path libSrc = lib.resolve("src"); + Path libClasses = lib.resolve("classes"); + tb.writeJavaFiles(libSrc, + """ + class value {} + """); + + Files.createDirectories(libClasses); + + new JavacTask(tb) + .outdir(libClasses) + .files(tb.findJavaFiles(libSrc)) + .run() + .writeAll(); + + Path test = current.resolve("test"); + Path src = test.resolve("src"); + Path classes = test.resolve("classes"); + + Files.createDirectories(classes); + + record TestCase(List options, String input, Task.Expect expected, String... expectedOutput) {} + String currentVersion = Integer.toString(Runtime.version().feature()); + + TestCase[] testCases = new TestCase[] { + new TestCase(List.of("--release", "25"), + "value class VC {}", + Task.Expect.FAIL, + "Test.java:3:9: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion), + "value class VC {}", + Task.Expect.FAIL, + "Test.java:3:9: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion, "--enable-preview"), + "value class VC {}", + Task.Expect.SUCCESS, + "- compiler.note.preview.filename: Test.java, DEFAULT", + "- compiler.note.preview.recompile"), + new TestCase(List.of("--release", "25"), + "value sealed class VC {}", + Task.Expect.FAIL, + "Test.java:3:9: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion), + "value sealed class VC {}", + Task.Expect.FAIL, + "Test.java:3:9: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion, "--enable-preview"), + "value sealed class VC {}", + Task.Expect.FAIL, + "Test.java:3:22: compiler.err.non.abstract.value.class.cant.be.sealed.or.non.sealed", + "- compiler.note.preview.filename: Test.java, DEFAULT", + "- compiler.note.preview.recompile", + "1 error"), + new TestCase(List.of("--release", "25"), + "value non-sealed class VC {}", + Task.Expect.FAIL, + "Test.java:3:9: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion), + "value non-sealed class VC {}", + Task.Expect.FAIL, + "Test.java:3:9: compiler.err.preview.feature.disabled.plural: (compiler.misc.feature.value.classes)", + "1 error"), + new TestCase(List.of("--release", currentVersion, "--enable-preview"), + "value non-sealed class VC {}", + Task.Expect.FAIL, + "Test.java:3:26: compiler.err.non.abstract.value.class.cant.be.sealed.or.non.sealed", + "- compiler.note.preview.filename: Test.java, DEFAULT", + "- compiler.note.preview.recompile", + "1 error"), + }; + + String template = """ + class Test { + void test() { + #TEST + } + } + """; + for (TestCase testCase : testCases) { + List options = new ArrayList<>(); + + options.addAll(testCase.options()); + options.add("-XDrawDiagnostics"); + + tb.writeJavaFiles(src, + template.replace("#TEST", testCase.input())); + + var log = + new JavacTask(tb) + .options(options) + .classpath(libClasses) + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(testCase.expected()) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + assertEquals(List.of(testCase.expectedOutput()), log); + } + } + + @BeforeEach + public void setUp(TestInfo info) throws IOException { + base = Path.of(info.getTestMethod().orElseThrow().getName()); + Files.createDirectories(base); + } +} diff --git a/test/langtools/tools/javac/valhalla/value-objects/ValueObjectCompilationTests.java b/test/langtools/tools/javac/valhalla/value-objects/ValueObjectCompilationTests.java index 49208295ad3..b0454745656 100644 --- a/test/langtools/tools/javac/valhalla/value-objects/ValueObjectCompilationTests.java +++ b/test/langtools/tools/javac/valhalla/value-objects/ValueObjectCompilationTests.java @@ -26,7 +26,7 @@ * * @test * @bug 8287136 8292630 8279368 8287136 8287770 8279840 8279672 8292753 8287763 8279901 8287767 8293183 8293120 - * 8329345 8341061 8340984 8334484 8387279 + * 8329345 8341061 8340984 8334484 8387279 8388340 * @summary Negative compilation tests, and positive compilation (smoke) tests for Value Objects * @enablePreview * @library /lib/combo /tools/lib @@ -98,6 +98,74 @@ class Test { value int foo(); } """); + assertFail("compiler.err.mod.not.allowed.here", + """ + class Test { + value String x; + } + """); + assertFail("compiler.err.mod.not.allowed.here", + """ + class Test { + value String foo(); + } + """); + assertFail("compiler.err.mod.not.allowed.here", + """ + class Test { + value java.lang.String x; + } + """); + assertFail("compiler.err.mod.not.allowed.here", + """ + class Test { + value java.lang.String foo(); + } + """); + assertFail("compiler.err.mod.not.allowed.here", + """ + import java.util.List; + class Test { + value List x; + } + """); + assertFail("compiler.err.mod.not.allowed.here", + """ + import java.util.List; + class Test { + value List foo(); + } + """); + assertFail("compiler.err.restricted.type.not.allowed.here", + //better would be: "compiler.err.mod.not.allowed.here", + """ + class Test { + value String[] x; + } + """); + assertFail("compiler.err.restricted.type.not.allowed.here", + //better would be: "compiler.err.mod.not.allowed.here", + """ + class Test { + value String[] foo(); + } + """); + assertFail("compiler.err.restricted.type.not.allowed.here", + //better would be: "compiler.err.mod.not.allowed.here", + """ + class Test { + value String @TA [] x; + } + @interface TA {} + """); + assertFail("compiler.err.restricted.type.not.allowed.here", + //better would be: "compiler.err.mod.not.allowed.here", + """ + class Test { + value String @TA []foo(); + } + @interface TA {} + """); assertFail("compiler.err.mod.not.allowed.here", d -> Assert.check("modifier value not allowed here".equals(d.getMessage(Locale.ROOT))), """ @@ -105,6 +173,29 @@ value enum Enum {} """); } + @Test + void testValueModifier() { + //JDK-8388340: + assertOK(""" + abstract value sealed class A {} + abstract value non-sealed class B extends A {} + """); + assertOK(""" + value @Ann(1) class Test { + } + @interface Ann { + public int value(); + } + """); + assertOK(""" + value @Ann(value = 1) class Test { + } + @interface Ann { + public int value(); + } + """); + } + record TestData(String message, String snippet, String[] compilerOptions, boolean testLocalToo) { TestData(String snippet) { this("", snippet, null, true); diff --git a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.java b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.java index c1a440c0e8a..6fd82aa2b2d 100644 --- a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.java +++ b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.java @@ -3,9 +3,11 @@ * @bug 8198512 8199327 * @summary compiler support for local-variable syntax for lambda parameters * @compile/fail/ref=VarInImplicitLambdaNegTest01.out -XDrawDiagnostics VarInImplicitLambdaNegTest01.java - * @compile/fail/ref=VarInImplicitLambdaNegTest01_source10.out -source 10 -XDrawDiagnostics VarInImplicitLambdaNegTest01.java + * @compile/fail/ref=VarInImplicitLambdaNegTest01_source10.out --release 10 -XDrawDiagnostics VarInImplicitLambdaNegTest01.java */ +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; import java.util.function.*; class VarInImplicitLambdaNegTest01 { @@ -15,8 +17,11 @@ class VarInImplicitLambdaNegTest01 { IntBinaryOperator f4 = (int x, y) -> x + y; // error explicit and implicit BiFunction f5 = (var s1[], var s2) -> s2; // error var and array + BiFunction f6 = (var s1 @TA [], var @TA [] s2) -> s2; // error var and array with annotations // correct use - IntBinaryOperator f6 = (var x, var y) -> x + y; // ok + IntBinaryOperator f7 = (var x, var y) -> x + y; // ok BiFunction, String, String> f = (Function s1, String s2) -> s2; // ok } +@Target(ElementType.TYPE_USE) +@interface TA {} \ No newline at end of file diff --git a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.out b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.out index ac99e2a96ef..79a4607676a 100644 --- a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.out +++ b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01.out @@ -1,6 +1,8 @@ -VarInImplicitLambdaNegTest01.java:12:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.implicit.not.allowed) -VarInImplicitLambdaNegTest01.java:13:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.implicit.not.allowed) -VarInImplicitLambdaNegTest01.java:14:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.explicit.not.allowed) -VarInImplicitLambdaNegTest01.java:15:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.implicit.and.explicit.not.allowed) -VarInImplicitLambdaNegTest01.java:17:52: compiler.err.restricted.type.not.allowed.array: var -5 errors +VarInImplicitLambdaNegTest01.java:14:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.implicit.not.allowed) +VarInImplicitLambdaNegTest01.java:15:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.implicit.not.allowed) +VarInImplicitLambdaNegTest01.java:16:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.var.and.explicit.not.allowed) +VarInImplicitLambdaNegTest01.java:17:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.implicit.and.explicit.not.allowed) +VarInImplicitLambdaNegTest01.java:19:52: compiler.err.restricted.type.not.allowed.array: var +VarInImplicitLambdaNegTest01.java:20:52: compiler.err.restricted.type.not.allowed.array: var +VarInImplicitLambdaNegTest01.java:20:74: compiler.err.restricted.type.not.allowed.array: var +7 errors diff --git a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01_source10.out b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01_source10.out index a7c5bae106b..99f73efcfbf 100644 --- a/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01_source10.out +++ b/test/langtools/tools/javac/var_implicit_lambda/VarInImplicitLambdaNegTest01_source10.out @@ -1,6 +1,6 @@ -- compiler.warn.source.no.system.modules.path: 10, (compiler.misc.source.no.system.modules.path: 10) -VarInImplicitLambdaNegTest01.java:12:36: compiler.err.feature.not.supported.in.source.plural: (compiler.misc.feature.var.syntax.in.implicit.lambda), 10, 11 -VarInImplicitLambdaNegTest01.java:15:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.implicit.and.explicit.not.allowed) -VarInImplicitLambdaNegTest01.java:17:52: compiler.err.restricted.type.not.allowed.here: var -3 errors -1 warning +VarInImplicitLambdaNegTest01.java:14:36: compiler.err.feature.not.supported.in.source.plural: (compiler.misc.feature.var.syntax.in.implicit.lambda), 10, 11 +VarInImplicitLambdaNegTest01.java:17:28: compiler.err.invalid.lambda.parameter.declaration: (compiler.misc.implicit.and.explicit.not.allowed) +VarInImplicitLambdaNegTest01.java:19:52: compiler.err.restricted.type.not.allowed.here: var +VarInImplicitLambdaNegTest01.java:20:52: compiler.err.restricted.type.not.allowed.here: var +VarInImplicitLambdaNegTest01.java:20:74: compiler.err.restricted.type.not.allowed.here: var +5 errors From 6096bdfc8c5f6d606dbfac85b503e5124fb5205f Mon Sep 17 00:00:00 2001 From: Christian Hagedorn Date: Mon, 23 Nov 2026 07:25:43 +0000 Subject: [PATCH 38/95] 8397827: [Valhalla] C2: arraycopy misses to add ZGC barriers when copying flat arrays containing oops Reviewed-by: thartmann, dlong --- src/hotspot/share/opto/arraycopynode.cpp | 2 +- .../TestFlatArraycopyMissingBarriers.java | 100 ++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 test/hotspot/jtreg/compiler/valhalla/valuetypes/TestFlatArraycopyMissingBarriers.java diff --git a/src/hotspot/share/opto/arraycopynode.cpp b/src/hotspot/share/opto/arraycopynode.cpp index 6f86b543212..9ccca57091b 100644 --- a/src/hotspot/share/opto/arraycopynode.cpp +++ b/src/hotspot/share/opto/arraycopynode.cpp @@ -447,7 +447,7 @@ bool ArrayCopyNode::can_use_arraycopy_fast_path(const TypeAryPtr* src_ary, const if (src_ary->elem()->value_klass()->contains_oops()) { BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); bool needs_barriers = bs->array_copy_requires_gc_barriers(is_alloc_tightly_coupled(), T_OBJECT, false, false, - BarrierSetC2::Optimization); + BarrierSetC2::Expansion); // When a flat array contains oops, we require GC barriers which we cannot handle return !needs_barriers; } diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestFlatArraycopyMissingBarriers.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestFlatArraycopyMissingBarriers.java new file mode 100644 index 00000000000..7db4937f791 --- /dev/null +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestFlatArraycopyMissingBarriers.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8397827 + * @summary Test ZGC barriers when C2 copies flat arrays containing oops. + * @requires vm.gc.Z & vm.compiler2.enabled + * @library /test/lib / + * @enablePreview + * @modules java.base/jdk.internal.value + * java.base/jdk.internal.vm.annotation + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:+UseZGC -Xms256m -Xmx256m -Xbatch -XX:-TieredCompilation + * -XX:PerMethodTrapLimit=0 -XX:CompileOnly=${test.main.class}::test + * -XX:CompileCommand=exclude,${test.main.class}::copyWithObj + * ${test.main.class} + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI ${test.main.class} + */ + + +package compiler.valhalla.valuetypes; + +import jdk.internal.value.ValueClass; +import jdk.test.whitebox.WhiteBox; + +public class TestFlatArraycopyMissingBarriers { + private static final int COPY_LENGTH = 64; + private static final int ARRAY_LENGTH = 300_000; + private static final WhiteBox WB = WhiteBox.getWhiteBox(); + + private static final V[] SRC_ARRAY = (V[])ValueClass.newNullRestrictedNonAtomicArray(V.class, ARRAY_LENGTH, new V(null)); + private static final V[] DEST_ARRAY =(V[])ValueClass.newNullRestrictedNonAtomicArray(V.class, ARRAY_LENGTH, new V(null)); + + public static void main(String[] args) throws Exception { + System.gc(); // Moves SRC_ARRAY and DEST_ARRAY to old gen + for (int i = 0; i < 10_000; i++) { + test(); // Compile + } + + // Clear remembered-set state + WB.youngGC(); + + Object obj = new Object(); // Young object + SRC_ARRAY[0] = new V(obj); // SRC_ARRAY[0].obj: young object + + // Copies SRC_ARRAY[0] to DEST_ARRAY[0] = V(obj) but without barriers + // -> DEST_ARRAY[0].obj: young object but not recorded due to missing barriers + test(); + + for (int i = 0; i < 5; i++) { + // Allocate some garbage and do 5 complete GC cycles to ensure that young 'obj' is moved. When this happens + // the young DEST_ARRAY[0].obj is forgotten to be updated. A later old-mark phase then crashes with a + // segfault when treating DEST_ARRAY[0].obj as an oop. + allocateGarbage(); + System.gc(); + } + } + + private static void test() { + System.arraycopy(SRC_ARRAY, 0, DEST_ARRAY, 0, COPY_LENGTH); + } + + private static void allocateGarbage() { + Object[] arr = new Object[100_000]; + for (int i = 0; i < arr.length; i++) { + arr[i] = new Object(); + } + } + + static value class V { + Object obj; + + V(Object obj) { + this.obj = obj; + } + } +} From effef93993b16cc4f0940b3ed92a8444baf79785 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Mon, 23 Nov 2026 07:53:16 +0000 Subject: [PATCH 39/95] 8397699: Http3Connection.sendCancelPush method misses buffer flip operation Reviewed-by: dfuchs, djelinski --- .../internal/net/http/Http3Connection.java | 1 + .../net/httpclient/http3/H3PushCancel.java | 59 +++++++++++++++++++ .../test/lib/common/HttpServerAdapters.java | 8 +++ .../test/lib/http2/Http2TestExchange.java | 7 ++- .../test/lib/http3/Http3ServerConnection.java | 9 ++- .../test/lib/http3/Http3ServerExchange.java | 6 ++ 6 files changed, 88 insertions(+), 2 deletions(-) diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http3Connection.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http3Connection.java index cb7b4889a67..0043e3caaa2 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Http3Connection.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http3Connection.java @@ -1745,6 +1745,7 @@ void sendCancelPush(long pushId, Throwable cause) { assert size <= 3 * VariableLengthEncoder.MAX_INTEGER_LENGTH; ByteBuffer buffer = ByteBuffer.allocate((int) size); cancelPush.writeFrame(buffer); + buffer.flip(); controlStreamPair.localWriter().scheduleForWriting(buffer, false); } catch (IOException io) { debug.log("Failed to cancel pushId: " + pushId); diff --git a/test/jdk/java/net/httpclient/http3/H3PushCancel.java b/test/jdk/java/net/httpclient/http3/H3PushCancel.java index 969297a50ba..b5de2a2b16f 100644 --- a/test/jdk/java/net/httpclient/http3/H3PushCancel.java +++ b/test/jdk/java/net/httpclient/http3/H3PushCancel.java @@ -64,6 +64,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; import java.util.function.Function; import jdk.httpclient.test.lib.common.HttpServerAdapters; @@ -384,6 +385,39 @@ public void applyPushPromise(HttpRequest initiatingRequest, } } + @Test + public void testCancelPushFrameSent() throws Exception { + CompletableFuture cancelReceived = new CompletableFuture<>(); + + try (HttpClient client = newClientBuilderForH3() + .proxy(Builder.NO_PROXY) + .version(Version.HTTP_3) + .sslContext(SimpleSSLContext.findSSLContext()) + .build()) { + + sendHeadRequest(client); + pushHandler.setCancelPushListener(cancelReceived::complete); + + PushPromiseHandler custom = new PushPromiseHandler<>() { + @Override + public void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, + Function, CompletableFuture>> acceptor) { + } + @Override + public void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, PushId pushid, + Function, CompletableFuture>> acceptor) { + } + }; + + client.sendAsync(HttpRequest.newBuilder(uri).header("X-PromiseOnly", "true").build(), + BodyHandlers.ofString(), + custom).join(); + + // fails if sendCancelPush wrote no bytes (missing flip) + long cancelledId = cancelReceived.get(); + assertTrue(cancelledId >= 0, "Server should receive CANCEL_PUSH"); + } + } // --- server push handler --- static class ServerPushHandler implements HttpTestHandler { @@ -391,6 +425,7 @@ static class ServerPushHandler implements HttpTestHandler { private final String mainResponseBody; private final Map promises; private final ReentrantLock lock = new ReentrantLock(); + private volatile Consumer cancelPushListener; public ServerPushHandler(String mainResponseBody, Map promises) @@ -401,6 +436,10 @@ public ServerPushHandler(String mainResponseBody, this.promises = promises; } + void setCancelPushListener(Consumer listener) { + this.cancelPushListener = listener; + } + final AtomicInteger count = new AtomicInteger(); public void handle(HttpTestExchange exchange) throws IOException { long count = -1; @@ -413,6 +452,12 @@ public void handle(HttpTestExchange exchange) throws IOException { is.readAllBytes(); } + Consumer listener = this.cancelPushListener; + if (listener != null) { + exchange.setHttp3CancelPushListener(listener); + this.cancelPushListener = null; + } + if (exchange.serverPushAllowed()) { pushPromises(exchange); } @@ -453,6 +498,20 @@ private void pushPromises(HttpTestExchange exchange) throws IOException { .firstValueAsLong("X-WaitForPushId").orElse(-1); long usePushId = exchange.getRequestHeaders() .firstValueAsLong("X-UsePushId").orElse(-1); + boolean promiseOnly = exchange.getRequestHeaders() + .firstValue("X-PromiseOnly").isPresent(); + if (promiseOnly) { + URI pushUri = requestURI.resolve(promises.keySet().iterator().next()); + HttpHeaders headers = HttpHeaders.of(Collections.emptyMap(), (x, y) -> true); + try { + allowed = exchange.waitForHttp3MaxPushId(0); + } catch (InterruptedException ie) { + ie.printStackTrace(); + } + long pushId = exchange.sendHttp3PushPromiseFrame(-1, pushUri, headers); + System.err.println("Server: Sent promise-only frame: " + pushId); + return; + } if (waitForPushId >= 0) { while (allowed <= waitForPushId) { try { diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java index 58a1ff947d2..e13c229b05e 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java @@ -75,6 +75,7 @@ import java.util.concurrent.ExecutorService; import java.util.function.Supplier; import java.util.function.Predicate; +import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; @@ -474,6 +475,9 @@ public long waitForHttp3MaxPushId(long pushId) throws InterruptedException { throw new UnsupportedOperationException("waitForMaxPushId with " + getExchangeVersion()); } + public void setHttp3CancelPushListener(Consumer listener) { + throw new UnsupportedOperationException("setHttp3CancelPushListener with " + getExchangeVersion()); + } public boolean serverPushAllowed() { return false; } @@ -651,6 +655,10 @@ public long waitForHttp3MaxPushId(long pushId) throws InterruptedException { return exchange.waitForMaxPushId(pushId); } @Override + public void setHttp3CancelPushListener(Consumer listener) { + exchange.setCancelPushListener(listener); + } + @Override public Encoder qpackEncoder() { return exchange.qpackEncoder(); } diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http2/Http2TestExchange.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http2/Http2TestExchange.java index 77c9e831fb0..24a25319e9c 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http2/Http2TestExchange.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http2/Http2TestExchange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,7 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiPredicate; +import java.util.function.Consumer; import javax.net.ssl.SSLSession; import jdk.internal.net.http.common.HttpHeadersBuilder; @@ -222,6 +223,10 @@ default long waitForMaxPushId(long pushId) throws InterruptedException { return VariableLengthEncoder.MAX_ENCODED_INTEGER; } + default void setCancelPushListener(Consumer listener) { + throw new UnsupportedOperationException("setCancelPushListener with " + getExchangeVersion()); + } + default Encoder qpackEncoder() { throw new UnsupportedOperationException("QPack encoder not supported: " + getExchangeVersion()); } diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerConnection.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerConnection.java index 4b0ea351a09..e4a1f1cbfc9 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerConnection.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ import java.nio.ByteBuffer; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -729,8 +730,14 @@ void sendCancelPush(long pushId) throws IOException { afterSettings.thenAccept((s) -> writeControlStream(buf)); } + private volatile Consumer cancelPushListener = (id) -> {}; + + public void setCancelPushListener(Consumer listener) { + this.cancelPushListener = Objects.requireNonNull(listener); + } void cancelPushReceived(long pushId) { + cancelPushListener.accept(pushId); cancelPush(pushId); } diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java index cc38bfa7667..cfd85cab9e7 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java @@ -41,6 +41,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.LongSupplier; @@ -416,6 +417,11 @@ public void cancelPushId(long pushId) throws IOException { serverConn.sendCancelPush(pushId); } + @Override + public void setCancelPushListener(Consumer listener) { + serverConn.setCancelPushListener(listener); + } + @Override public long waitForMaxPushId(long pushId) throws InterruptedException { return serverConn.waitForMaxPushId(pushId); From cd97a5a17767bfcecd175c8fdb377bf27db2c907 Mon Sep 17 00:00:00 2001 From: Thomas Schatzl Date: Mon, 23 Nov 2026 09:49:24 +0000 Subject: [PATCH 40/95] 8396873: G1: Improve region index constants naming Reviewed-by: ayang --- src/hotspot/share/gc/g1/g1CollectedHeap.cpp | 9 ++++----- src/hotspot/share/gc/g1/g1CollectedHeap.hpp | 1 - src/hotspot/share/gc/g1/g1HeapRegion.hpp | 10 +++++++--- src/hotspot/share/gc/g1/g1HeapRegionManager.cpp | 10 +++++----- src/hotspot/share/gc/g1/g1HeapRegionManager.hpp | 6 +++--- src/hotspot/share/gc/g1/g1RegionPinCache.hpp | 2 +- src/hotspot/share/gc/g1/g1RegionPinCache.inline.hpp | 2 +- .../jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java | 2 +- 8 files changed, 22 insertions(+), 20 deletions(-) diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp index ec08b49d2d5..e923cc65789 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp @@ -1443,15 +1443,14 @@ jint G1CollectedHeap::initialize() { Universe::check_alignment(reserved_byte_size, G1HeapRegion::GrainBytes, "g1 heap"); Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap"); - // Ensure that the maximum number of regions (based on the max region index) we allow can fit the reservation. - const size_t max_num_regions_by_index = (1u << (sizeof(RegionIdx_t) * BitsPerByte - 1)); + // Ensure that the maximum number of regions we allow can fit the reservation. size_t num_regions_for_reservation = reserved_byte_size / G1HeapRegion::GrainBytes; - if (num_regions_for_reservation > max_num_regions_by_index) { - vm_exit_during_initialization(err_msg("Requested heap size (%zu%s) would exceed maximum region count %zu at region size %zu. Decrease maximum heap size.", + if (num_regions_for_reservation > G1HeapRegion::MaxNumRegions) { + vm_exit_during_initialization(err_msg("Requested heap size (%zu%s) would exceed maximum number of regions %u at region size %zu. Decrease maximum heap size.", byte_size_in_proper_unit(reserved_byte_size), proper_unit_for_byte_size(reserved_byte_size), - max_num_regions_by_index, + G1HeapRegion::MaxNumRegions, G1HeapRegion::GrainBytes)); } diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp index f330223995b..8520022b749 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp @@ -90,7 +90,6 @@ class WorkerThreads; typedef OverflowTaskQueue G1ScannerTasksQueue; typedef GenericTaskQueueSet G1ScannerTasksQueueSet; -typedef int RegionIdx_t; // needs to hold [ 0..max_num_regions() ) typedef int CardIdx_t; // needs to hold [ 0..CardsPerRegion ) // The G1 STW is alive closure. diff --git a/src/hotspot/share/gc/g1/g1HeapRegion.hpp b/src/hotspot/share/gc/g1/g1HeapRegion.hpp index 28b47d35c96..b25b1129c37 100644 --- a/src/hotspot/share/gc/g1/g1HeapRegion.hpp +++ b/src/hotspot/share/gc/g1/g1HeapRegion.hpp @@ -53,9 +53,6 @@ class nmethod; (_hr_)->get_short_type_str(), \ p2i((_hr_)->bottom()), p2i((_hr_)->top()), p2i((_hr_)->end()) -// sentinel value for hrm_index -#define G1_NO_HRM_INDEX (UINT_MAX) - // A G1HeapRegion is the smallest piece of a G1CollectedHeap that // can be collected independently. @@ -87,6 +84,13 @@ class G1HeapRegion : public CHeapObj { HeapWord* _pre_dummy_top; public: + // Valid region indexes range from 0 .. MaxNumRegions-1. + // We restrict to INT_MAX because we internally need the NoRegionIdx sentinel internally. + // For simplicity, limit to 2^31 regions which allow more than enough maximum heap size. + static const uint MaxNumRegions = 1u << 31; + // Sentinel value for an invalid region index. + static const uint InvalidRegionIdx = UINT_MAX; + HeapWord* bottom() const { return _bottom; } HeapWord* end() const { return _end; } diff --git a/src/hotspot/share/gc/g1/g1HeapRegionManager.cpp b/src/hotspot/share/gc/g1/g1HeapRegionManager.cpp index 160c93cdbc2..7db0733a34a 100644 --- a/src/hotspot/share/gc/g1/g1HeapRegionManager.cpp +++ b/src/hotspot/share/gc/g1/g1HeapRegionManager.cpp @@ -110,7 +110,7 @@ G1HeapRegion* G1HeapRegionManager::allocate_free_region(G1HeapRegionType type, u G1HeapRegion* G1HeapRegionManager::allocate_humongous_from_free_list(uint num_regions) { uint candidate = find_contiguous_in_free_list(num_regions); - if (candidate == G1_NO_HRM_INDEX) { + if (candidate == G1HeapRegion::InvalidRegionIdx) { return nullptr; } return allocate_free_regions_starting_at(candidate, num_regions); @@ -118,7 +118,7 @@ G1HeapRegion* G1HeapRegionManager::allocate_humongous_from_free_list(uint num_re G1HeapRegion* G1HeapRegionManager::allocate_humongous_allow_expand(uint num_regions) { uint candidate = find_contiguous_allow_expand(num_regions); - if (candidate == G1_NO_HRM_INDEX) { + if (candidate == G1HeapRegion::InvalidRegionIdx) { return nullptr; } expand_exact(candidate, num_regions, G1CollectedHeap::heap()->workers()); @@ -459,17 +459,17 @@ uint G1HeapRegionManager::find_contiguous_in_range(uint start, uint end, uint nu } } } - return G1_NO_HRM_INDEX; + return G1HeapRegion::InvalidRegionIdx; } uint G1HeapRegionManager::find_contiguous_in_free_list(uint num_regions) { - uint candidate = G1_NO_HRM_INDEX; + uint candidate = G1HeapRegion::InvalidRegionIdx; G1HeapRegionRange range(0,0); do { range = _committed_map.next_active_range(range.end()); candidate = find_contiguous_in_range(range.start(), range.end(), num_regions); - } while (candidate == G1_NO_HRM_INDEX && range.end() < max_num_regions()); + } while (candidate == G1HeapRegion::InvalidRegionIdx && range.end() < max_num_regions()); return candidate; } diff --git a/src/hotspot/share/gc/g1/g1HeapRegionManager.hpp b/src/hotspot/share/gc/g1/g1HeapRegionManager.hpp index 5764532e75d..caf3308e97f 100644 --- a/src/hotspot/share/gc/g1/g1HeapRegionManager.hpp +++ b/src/hotspot/share/gc/g1/g1HeapRegionManager.hpp @@ -95,14 +95,14 @@ class G1HeapRegionManager: public CHeapObj { void initialize_regions(uint start, uint num_regions); // Find a contiguous set of free active, pending uncommit or uncommitted regions of length num_regions and return - // the index of the first region or G1_NO_HRM_INDEX if the search was unsuccessful. + // the index of the first region or G1HeapRegion::NoRegionIdx if the search was unsuccessful. // Start and end defines the range to seek in, policy is first-fit. uint find_contiguous_in_range(uint start, uint end, uint num_regions); // Find a contiguous set of empty regions of length num_regions. Returns the start index - // of that set, or G1_NO_HRM_INDEX. + // of that set, or G1HeapRegion::NoRegionIdx. uint find_contiguous_in_free_list(uint num_regions); // Find a contiguous set of empty or unavailable regions of length num_regions. Returns the - // start index of that set, or G1_NO_HRM_INDEX. + // start index of that set, or G1HeapRegion::NoRegionIdx. uint find_contiguous_allow_expand(uint num_regions); void assert_contiguous_range(uint start, uint num_regions) NOT_DEBUG_RETURN; diff --git a/src/hotspot/share/gc/g1/g1RegionPinCache.hpp b/src/hotspot/share/gc/g1/g1RegionPinCache.hpp index 1c04936930a..dc2b0e680de 100644 --- a/src/hotspot/share/gc/g1/g1RegionPinCache.hpp +++ b/src/hotspot/share/gc/g1/g1RegionPinCache.hpp @@ -42,7 +42,7 @@ class G1RegionPinCache : public StackObj { void flush_and_set(uint new_region_idx, size_t new_count); public: - G1RegionPinCache() : _region_idx(G1_NO_HRM_INDEX), _count(0) { } + G1RegionPinCache() : _region_idx(G1HeapRegion::InvalidRegionIdx), _count(0) { } #ifdef ASSERT size_t count() const { return _count; } diff --git a/src/hotspot/share/gc/g1/g1RegionPinCache.inline.hpp b/src/hotspot/share/gc/g1/g1RegionPinCache.inline.hpp index 7df81d208f1..557315fc06c 100644 --- a/src/hotspot/share/gc/g1/g1RegionPinCache.inline.hpp +++ b/src/hotspot/share/gc/g1/g1RegionPinCache.inline.hpp @@ -54,7 +54,7 @@ inline void G1RegionPinCache::flush_and_set(uint new_region_idx, size_t new_coun } inline void G1RegionPinCache::flush() { - flush_and_set(G1_NO_HRM_INDEX, 0); + flush_and_set(G1HeapRegion::InvalidRegionIdx, 0); } #endif /* SHARE_GC_G1_G1REGIONPINCACHE_INLINE_HPP */ diff --git a/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java b/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java index e11d6d85ba4..6be5dedf608 100644 --- a/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java +++ b/test/hotspot/jtreg/gc/g1/TestRegionIdxExceedsRepresentable.java @@ -56,7 +56,7 @@ public static void runTest(long heapsize) throws Exception { output.shouldNotHaveExitValue(0); - String pattern = "would exceed maximum region count 2147483648"; + String pattern = "would exceed maximum number of regions 2147483648"; output.shouldContain(pattern); } From 18b49cd0045c3251ebe4e5f9c2ebff6285b1eec0 Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Mon, 23 Nov 2026 13:32:14 +0000 Subject: [PATCH 41/95] 8397538: test/jdk/java/net/httpclient/http2/H2GoAwayPromptConnectionClose.java should accept WINDOW_UPDATE while waiting for headers Reviewed-by: djelinski --- .../http2/H2GoAwayPromptConnectionClose.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/test/jdk/java/net/httpclient/http2/H2GoAwayPromptConnectionClose.java b/test/jdk/java/net/httpclient/http2/H2GoAwayPromptConnectionClose.java index 960115f2dd3..8f7f34ba69f 100644 --- a/test/jdk/java/net/httpclient/http2/H2GoAwayPromptConnectionClose.java +++ b/test/jdk/java/net/httpclient/http2/H2GoAwayPromptConnectionClose.java @@ -60,6 +60,7 @@ import jdk.internal.net.http.frame.HeadersFrame; import jdk.internal.net.http.frame.Http2Frame; import jdk.internal.net.http.frame.SettingsFrame; +import jdk.internal.net.http.frame.WindowUpdateFrame; import jdk.internal.net.http.hpack.Decoder; import jdk.internal.net.http.hpack.Encoder; import jdk.test.lib.RandomFactory; @@ -632,13 +633,19 @@ private Map> parseHeadersFrame(final byte[] frame) throws I private static byte[] expectFrame(final InputStream in, final int expectedFrameType) throws IOException { - final byte[] frame = readHTTP2Frame(in); - final int frameType = frameType(frame); - if (frameType != expectedFrameType) { - throw new IOException("unexpected frame, got type " + frameType - + ", expected " + expectedFrameType); - } - return frame; + do { + final byte[] frame = readHTTP2Frame(in); + final int frameType = frameType(frame); + if (frameType == WindowUpdateFrame.TYPE && expectedFrameType == HeadersFrame.TYPE) { + // skip this frame + continue; + } + if (frameType != expectedFrameType) { + throw new IOException("unexpected frame, got type " + frameType + + ", expected " + expectedFrameType); + } + return frame; + } while (true); } private static byte[] readHTTP2Frame(final InputStream in) From 53479c3cd0eb06cefcbef6d1ee8a7300d928d022 Mon Sep 17 00:00:00 2001 From: Christian Hagedorn Date: Mon, 23 Nov 2026 14:10:55 +0000 Subject: [PATCH 42/95] 8388434: [IR Framework] Introduce a skip attribute in @IR to skip failing IR rules instead of commenting them out Reviewed-by: mchevalier, epeter --- .../c2/cmove/TestConditionalMove.java | 364 ++++++++++-------- .../TestScalarConditionalMoveCmpObj.java | 23 +- .../TestVectorizationMismatchedAccess.java | 44 ++- .../gcbarriers/TestZGCBarrierElision.java | 2 +- .../compiler/igvn/IntegerDivValueTests.java | 12 +- .../jtreg/compiler/lib/ir_framework/IR.java | 12 + .../jtreg/compiler/lib/ir_framework/README.md | 4 + .../report/FailureMessageBuilder.java | 3 +- .../test/ApplicableIRRulesPrinter.java | 16 +- .../superword/TestMemorySegmentAliasing.java | 76 ++-- .../valhalla/valuetypes/TestArrays.java | 60 +-- .../valuetypes/TestBasicFunctionality.java | 33 +- .../valhalla/valuetypes/TestLWorld.java | 10 +- .../valuetypes/TestLWorldProfiling.java | 48 +-- .../valuetypes/TestNullableArrays.java | 3 +- .../valuetypes/TestNullableValueTypes.java | 63 ++- .../runner/ArrayInvariantFillTest.java | 7 +- .../ir_framework/examples/IRExample.java | 14 +- .../ir_framework/tests/TestSkipIR.java | 188 +++++++++ 19 files changed, 665 insertions(+), 317 deletions(-) create mode 100644 test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestSkipIR.java diff --git a/test/hotspot/jtreg/compiler/c2/cmove/TestConditionalMove.java b/test/hotspot/jtreg/compiler/c2/cmove/TestConditionalMove.java index ad4781848fb..c73687d5d40 100644 --- a/test/hotspot/jtreg/compiler/c2/cmove/TestConditionalMove.java +++ b/test/hotspot/jtreg/compiler/c2/cmove/TestConditionalMove.java @@ -1171,9 +1171,10 @@ private static void testCMoveDXXforDConstH2(double[] a, double[] b, double[] c) // I fo I @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveIEQforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1185,9 +1186,10 @@ private static void testCMoveIEQforI(int[] a, int[] b, int[] c, int[] d, int[] r @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveINEforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1199,9 +1201,10 @@ private static void testCMoveINEforI(int[] a, int[] b, int[] c, int[] d, int[] r @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveIGTforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1213,9 +1216,10 @@ private static void testCMoveIGTforI(int[] a, int[] b, int[] c, int[] d, int[] r @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveIGEforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1227,9 +1231,10 @@ private static void testCMoveIGEforI(int[] a, int[] b, int[] c, int[] d, int[] r @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveILTforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1241,9 +1246,10 @@ private static void testCMoveILTforI(int[] a, int[] b, int[] c, int[] d, int[] r @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveILEforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1256,9 +1262,10 @@ private static void testCMoveILEforI(int[] a, int[] b, int[] c, int[] d, int[] r // I fo L @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveIEQforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1270,9 +1277,10 @@ private static void testCMoveIEQforL(int[] a, int[] b, long[] c, long[] d, long[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveINEforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1284,9 +1292,10 @@ private static void testCMoveINEforL(int[] a, int[] b, long[] c, long[] d, long[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveIGTforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1298,9 +1307,10 @@ private static void testCMoveIGTforL(int[] a, int[] b, long[] c, long[] d, long[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveIGEforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1312,9 +1322,10 @@ private static void testCMoveIGEforL(int[] a, int[] b, long[] c, long[] d, long[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveILTforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1326,9 +1337,10 @@ private static void testCMoveILTforL(int[] a, int[] b, long[] c, long[] d, long[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_I, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveILEforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1559,9 +1571,10 @@ private static void testCMoveILEforD(int[] a, int[] b, double[] c, double[] d, d // L fo I @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLEQforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1573,9 +1586,10 @@ private static void testCMoveLEQforI(long[] a, long[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLNEforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1587,9 +1601,10 @@ private static void testCMoveLNEforI(long[] a, long[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLGTforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1601,9 +1616,10 @@ private static void testCMoveLGTforI(long[] a, long[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLGEforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1615,9 +1631,10 @@ private static void testCMoveLGEforI(long[] a, long[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLLTforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1629,9 +1646,10 @@ private static void testCMoveLLTforI(long[] a, long[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLLEforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1644,9 +1662,10 @@ private static void testCMoveLLEforI(long[] a, long[] b, int[] c, int[] d, int[] // L fo L @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLEQforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1658,9 +1677,10 @@ private static void testCMoveLEQforL(long[] a, long[] b, long[] c, long[] d, lon @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLNEforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1672,9 +1692,10 @@ private static void testCMoveLNEforL(long[] a, long[] b, long[] c, long[] d, lon @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLGTforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1686,9 +1707,10 @@ private static void testCMoveLGTforL(long[] a, long[] b, long[] c, long[] d, lon @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLGEforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1700,9 +1722,10 @@ private static void testCMoveLGEforL(long[] a, long[] b, long[] c, long[] d, lon @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLLTforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1714,9 +1737,10 @@ private static void testCMoveLLTforL(long[] a, long[] b, long[] c, long[] d, lon @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_L, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveLLEforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -1954,9 +1978,10 @@ private static void testCMoveLLEforD(long[] a, long[] b, double[] c, double[] d, // I fo I @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUIEQforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1968,9 +1993,10 @@ private static void testCMoveUIEQforI(int[] a, int[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUINEforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1982,9 +2008,10 @@ private static void testCMoveUINEforI(int[] a, int[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUIGTforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -1996,9 +2023,10 @@ private static void testCMoveUIGTforI(int[] a, int[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUIGEforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2010,9 +2038,10 @@ private static void testCMoveUIGEforI(int[] a, int[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUILTforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2024,9 +2053,10 @@ private static void testCMoveUILTforI(int[] a, int[] b, int[] c, int[] d, int[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUILEforI(int[] a, int[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2039,9 +2069,10 @@ private static void testCMoveUILEforI(int[] a, int[] b, int[] c, int[] d, int[] // I fo L @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUIEQforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2053,9 +2084,10 @@ private static void testCMoveUIEQforL(int[] a, int[] b, long[] c, long[] d, long @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUINEforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2067,9 +2099,10 @@ private static void testCMoveUINEforL(int[] a, int[] b, long[] c, long[] d, long @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUIGTforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2081,9 +2114,10 @@ private static void testCMoveUIGTforL(int[] a, int[] b, long[] c, long[] d, long @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUIGEforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2095,9 +2129,10 @@ private static void testCMoveUIGEforL(int[] a, int[] b, long[] c, long[] d, long @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUILTforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2109,9 +2144,10 @@ private static void testCMoveUILTforL(int[] a, int[] b, long[] c, long[] d, long @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_U, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveUILEforL(int[] a, int[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2342,9 +2378,10 @@ private static void testCMoveUILEforD(int[] a, int[] b, double[] c, double[] d, // L fo I @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULEQforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2356,9 +2393,10 @@ private static void testCMoveULEQforI(long[] a, long[] b, int[] c, int[] d, int[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULNEforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2370,9 +2408,10 @@ private static void testCMoveULNEforI(long[] a, long[] b, int[] c, int[] d, int[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULGTforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2384,9 +2423,10 @@ private static void testCMoveULGTforI(long[] a, long[] b, int[] c, int[] d, int[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULGEforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2398,9 +2438,10 @@ private static void testCMoveULGEforI(long[] a, long[] b, int[] c, int[] d, int[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULLTforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2412,9 +2453,10 @@ private static void testCMoveULLTforI(long[] a, long[] b, int[] c, int[] d, int[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULLEforI(long[] a, long[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2427,9 +2469,10 @@ private static void testCMoveULLEforI(long[] a, long[] b, int[] c, int[] d, int[ // L fo L @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULEQforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2441,9 +2484,10 @@ private static void testCMoveULEQforL(long[] a, long[] b, long[] c, long[] d, lo @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULNEforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2455,9 +2499,10 @@ private static void testCMoveULNEforL(long[] a, long[] b, long[] c, long[] d, lo @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULGTforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2469,9 +2514,10 @@ private static void testCMoveULGTforL(long[] a, long[] b, long[] c, long[] d, lo @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULGEforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2483,9 +2529,10 @@ private static void testCMoveULGEforL(long[] a, long[] b, long[] c, long[] d, lo @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULLTforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2497,9 +2544,10 @@ private static void testCMoveULLTforL(long[] a, long[] b, long[] c, long[] d, lo @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_UL, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveULLEforL(long[] a, long[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2735,9 +2783,10 @@ private static void testCMoveULLEforD(long[] a, long[] b, double[] c, double[] d @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_F, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_F, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveFGTforI(float[] a, float[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2749,9 +2798,10 @@ private static void testCMoveFGTforI(float[] a, float[] b, int[] c, int[] d, int @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_F, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_F, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveFGTforL(float[] a, float[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -2798,9 +2848,10 @@ private static void testCMoveFGTforD(float[] a, float[] b, double[] c, double[] @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_D, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_I, ">0", IRNode.CMP_D, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveDGTforI(double[] a, double[] b, int[] c, int[] d, int[] r, int[] r2) { for (int i = 0; i < a.length; i++) { int cc = c[i]; @@ -2812,9 +2863,10 @@ private static void testCMoveDGTforI(double[] a, double[] b, int[] c, int[] d, i @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_D, ">0"}, - // applyIf = {"UseVectorCmov", "false"}, - // applyIfPlatform = {"riscv64", "true"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_D, ">0"}, + applyIf = {"UseVectorCmov", "false"}, + applyIfPlatform = {"riscv64", "true"}) private static void testCMoveDGTforL(double[] a, double[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; diff --git a/test/hotspot/jtreg/compiler/c2/cmove/TestScalarConditionalMoveCmpObj.java b/test/hotspot/jtreg/compiler/c2/cmove/TestScalarConditionalMoveCmpObj.java index 309cf50fb9c..7389bb9566e 100644 --- a/test/hotspot/jtreg/compiler/c2/cmove/TestScalarConditionalMoveCmpObj.java +++ b/test/hotspot/jtreg/compiler/c2/cmove/TestScalarConditionalMoveCmpObj.java @@ -128,14 +128,16 @@ private static void testCMoveONEforI(NotValue[] a, NotValue[] b, int[] c, int[] } // So far, CMoveL is not guaranteed to be generated, so @IR not verify CMOVE_L. - // TODO: enable CMOVE_L verification when it's guaranteed to generate CMOVE_L. // @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_P, ">0"}, - // applyIf = {"UseCompressedOops", "false"}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_N, ">0"}, - // applyIf = {"UseCompressedOops", "true"}) + // TODO: enable CMOVE_L verification when it's guaranteed to generate CMOVE_L. + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_P, ">0"}, + applyIf = {"UseCompressedOops", "false"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_N, ">0"}, + applyIf = {"UseCompressedOops", "true"}) private static void testCMoveOEQforL(NotValue[] a, NotValue[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; @@ -147,10 +149,13 @@ private static void testCMoveOEQforL(NotValue[] a, NotValue[] b, long[] c, long[ @Test @IR(failOn = {IRNode.STORE_VECTOR}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_P, ">0"}, - // applyIf = {"UseCompressedOops", "false"}) - // @IR(counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_N, ">0"}, - // applyIf = {"UseCompressedOops", "true"}) + // TODO: enable CMOVE_L verification when it's guaranteed to generate CMOVE_L. + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_P, ">0"}, + applyIf = {"UseCompressedOops", "false"}) + @IR(skip = true, + counts = {IRNode.CMOVE_L, ">0", IRNode.CMP_N, ">0"}, + applyIf = {"UseCompressedOops", "true"}) private static void testCMoveONEforL(NotValue[] a, NotValue[] b, long[] c, long[] d, long[] r, long[] r2) { for (int i = 0; i < a.length; i++) { long cc = c[i]; diff --git a/test/hotspot/jtreg/compiler/c2/irTests/TestVectorizationMismatchedAccess.java b/test/hotspot/jtreg/compiler/c2/irTests/TestVectorizationMismatchedAccess.java index 9556fce988d..368f7b4bbde 100644 --- a/test/hotspot/jtreg/compiler/c2/irTests/TestVectorizationMismatchedAccess.java +++ b/test/hotspot/jtreg/compiler/c2/irTests/TestVectorizationMismatchedAccess.java @@ -592,8 +592,9 @@ public static void testByteByte5_runner() { @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) - // FAILS: adr is CastX2P(dest + 8 * (i + int_con)) + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) + // TODO: FAILS: adr is CastX2P(dest + 8 * (i + int_con)) // See: JDK-8331576 public static void testOffHeapLong1a(long dest, long[] src) { for (int i = 0; i < src.length; i++) { @@ -603,8 +604,9 @@ public static void testOffHeapLong1a(long dest, long[] src) { @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) - // FAILS: adr is CastX2P(dest + 8L * (i + int_con)) + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) + // TODO: FAILS: adr is CastX2P(dest + 8L * (i + int_con)) // See: JDK-8331576 public static void testOffHeapLong1b(long dest, long[] src) { for (int i = 0; i < src.length; i++) { @@ -620,8 +622,9 @@ public static void testOffHeapLong1_runner() { @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) - // FAILS: adr is CastX2P + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) + // TODO: FAILS: adr is CastX2P // See: JDK-8331576 public static void testOffHeapLong2a(long dest, long[] src) { for (int i = 1; i < src.length; i++) { @@ -631,8 +634,9 @@ public static void testOffHeapLong2a(long dest, long[] src) { @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) - // FAILS: adr is CastX2P + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) + // TODO: FAILS: adr is CastX2P // See: JDK-8331576 public static void testOffHeapLong2b(long dest, long[] src) { for (int i = 1; i < src.length; i++) { @@ -648,8 +652,9 @@ public static void testOffHeapLong2_runner() { @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) - // FAILS: adr is CastX2P + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) + // TODO: FAILS: adr is CastX2P // See: JDK-8331576 public static void testOffHeapLong3a(long dest, long[] src) { for (int i = 0; i < src.length - 1; i++) { @@ -659,8 +664,9 @@ public static void testOffHeapLong3a(long dest, long[] src) { @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) - // FAILS: adr is CastX2P + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }) + // TODO: FAILS: adr is CastX2P // See: JDK-8331576 public static void testOffHeapLong3b(long dest, long[] src) { for (int i = 0; i < src.length - 1; i++) { @@ -676,9 +682,10 @@ public static void testOffHeapLong3_runner() { @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }, - // applyIf = {"AlignVector", "false"}) - // FAILS: adr is CastX2P + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }, + applyIf = {"AlignVector", "false"}) + // TODO: FAILS: adr is CastX2P // See: JDK-8331576 // AlignVector cannot guarantee that invar is aligned. public static void testOffHeapLong4a(long dest, long[] src, int start, int stop) { @@ -689,9 +696,10 @@ public static void testOffHeapLong4a(long dest, long[] src, int start, int stop) @Test @IR(counts = { IRNode.LOAD_VECTOR_L, "=0", IRNode.STORE_VECTOR, "=0" }) // temporary - // @IR(counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }, - // applyIf = {"AlignVector", "false"}) - // FAILS: adr is CastX2P + @IR(skip = true, + counts = { IRNode.LOAD_VECTOR_L, ">=1", IRNode.STORE_VECTOR, ">=1" }, + applyIf = {"AlignVector", "false"}) + // TODO: FAILS: adr is CastX2P // See: JDK-8331576 // AlignVector cannot guarantee that invar is aligned. public static void testOffHeapLong4b(long dest, long[] src, int start, int stop) { diff --git a/test/hotspot/jtreg/compiler/gcbarriers/TestZGCBarrierElision.java b/test/hotspot/jtreg/compiler/gcbarriers/TestZGCBarrierElision.java index 7f35790c57a..c79ac7ad98e 100644 --- a/test/hotspot/jtreg/compiler/gcbarriers/TestZGCBarrierElision.java +++ b/test/hotspot/jtreg/compiler/gcbarriers/TestZGCBarrierElision.java @@ -412,7 +412,7 @@ static void testAtomicThenStore(Outer o, Inner i) { @Test @IR(counts = { IRNode.Z_COMPARE_AND_SWAP_P_WITH_BARRIER_FLAG, Common.REMAINING, "1" }, phase = CompilePhase.FINAL_CODE) - //@IR(counts = { IRNode.Z_COMPARE_AND_SWAP_P_WITH_BARRIER_FLAG, Common.ELIDED, "1" }, phase = CompilePhase.FINAL_CODE) + @IR(counts = { IRNode.Z_COMPARE_AND_SWAP_P_WITH_BARRIER_FLAG, Common.ELIDED, "1" }, phase = CompilePhase.FINAL_CODE) static void testAtomicThenAtomic(Outer o, Inner i) { Common.field1VarHandle.getAndSet(o, i); Common.field1VarHandle.getAndSet(o, i); diff --git a/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java b/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java index 2abeffb0c41..ac5ab0dbaae 100644 --- a/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java +++ b/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -282,8 +282,9 @@ private long getLongConstant(long value) { private static final long LONG_CONST_2 = LONGS.next(); @Test - //@IR(failOn = {IRNode.DIV, IRNode.URSHIFT, IRNode.RSHIFT, IRNode.MUL, IRNode.ADD, IRNode.SUB, IRNode.AND}) - // This results in a series of nodes due to DivLNode::Ideal and in particular transform_long_divide, which operates on non-constant divisors. + @IR(skip = true, + failOn = {IRNode.DIV, IRNode.URSHIFT, IRNode.RSHIFT, IRNode.MUL, IRNode.ADD, IRNode.SUB, IRNode.AND}) + // TODO: This results in a series of nodes due to DivLNode::Ideal and in particular transform_long_divide, which operates on non-constant divisors. // transform_long_divide splits up the division into multiple other nodes, such as MulHiLNode, which does not have a good Value() implemantion. // When JDK-8366815 is fixed, these rules should be reenabled // Alternatively, a better MulHiLNode::Value() implemantion should also lead to constant folding @@ -300,8 +301,9 @@ public long testLongConstantFoldingSpecialCase() { } @Test - //@IR(failOn = {IRNode.DIV, IRNode.URSHIFT, IRNode.RSHIFT, IRNode.MUL, IRNode.ADD, IRNode.SUB, IRNode.AND}) - // This results in a series of nodes due to DivLNode::Ideal and in particular transform_long_divide, which operates on non-constant divisors. + @IR(skip = true, + failOn = {IRNode.DIV, IRNode.URSHIFT, IRNode.RSHIFT, IRNode.MUL, IRNode.ADD, IRNode.SUB, IRNode.AND}) + // TODO: This results in a series of nodes due to DivLNode::Ideal and in particular transform_long_divide, which operates on non-constant divisors. // transform_long_divide splits up the division into multiple other nodes, such as MulHiLNode, which does not have a good Value() implemantion. // When JDK-8366815 is fixed, these rules should be reenabled // Alternatively, a better MulHiLNode::Value() implemantion should also lead to constant folding diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/IR.java b/test/hotspot/jtreg/compiler/lib/ir_framework/IR.java index 3545c33820b..2517e7866bb 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/IR.java +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/IR.java @@ -177,4 +177,16 @@ * IR verifications checks are enforced if any of the specified feature constraint is met. */ String[] applyIfCPUFeatureOr() default {}; + + /** + * Skip IR matching of this IR rule. This is useful when the {@link Test @Test}-method causes the VM to emit an + * unexpected graph shape with no immediately available fix. Note that this only restricts the IR matching and not + * the execution of the {@link Test @Test}-method itself. To skip the entire {@link Test @Test}-method execution, + * use the {@link Skip @Skip} annotation instead. + *

+ * It is preferable to use this attribute over commenting an IR rule out because one can enable IR matching of the + * skipped IR rule by passing the property flag {@code -DIgnoreSkipIR=true}. This can be useful when trying to + * quickly verify if a disabled IR rule is still failing or not. + */ + boolean skip() default false; } diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/README.md b/test/hotspot/jtreg/compiler/lib/ir_framework/README.md index a6010e99733..b46e3054c24 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/README.md +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/README.md @@ -136,6 +136,9 @@ If a `@Test` annotated method has multiple preconditions (for example `applyIf` Platform attributes are evaluated as a logical conjunction, and take precedence over VM Flag attributes. An example with both `applyIfPlatformXXX` and `applyIfXXX` can be found in [TestPreconditions](../../../testlibrary_tests/ir_framework/tests/TestPreconditions.java) (internal framework test). +#### Disable IR Rules Due to Compiler Problems +If an IR rule is failing due to compiler problems (e.g. not emitting the expected shape, compile phase wrongly skipped etc.) without having an immediate fix, it is preferred to additionally specify the `skip` attribute of [@IR](./IR.java): `@IR(skip = true, ...)` to disable IR matching of that particular IR rule over commenting it out. This allows to still perform IR matching for skipped IR rules on demand by passing the property flag `-DIgnoreSkipIR=true`. This can be useful when trying to quickly verify if a disabled IR rule is still failing or not. + #### Implicitly Skipping IR Verification An IR verification cannot always be performed. Certain VM flags explicitly disable IR verification, change the IR shape in unexpected ways letting IR rules fail or even make IR verification impossible: @@ -193,6 +196,7 @@ The framework provides various stress and debug flags. They should mainly be use - `-DIgnoreCompilerControls=true`: Ignore all compiler controls applied in the framework. This includes any compiler control annotations (`@DontCompile`, `@DontInline`, `@ForceCompile`, `@ForceInline`, `@ForceCompileStaticInitializer`), the exclusion of `@Run` and `@Check` methods from compilation, and the directive to not inline `@Test` annotated methods. - `-DPreferCommandLineFlags=true`: Prefer flags set via the command line over flags specified by the tests. - `-DIgnoreSkip=true`: Additionally run all skipped tests (i.e. tests with a `@Skip` annotation). +- `-DIgnoreSkipIR=true`: Additionally perform IR matching of all skipped `@IR` rules (i.e. `@IR` rules with `@IR(skip = true, ...)`). ## 3. Test Framework Execution This section gives an overview of how the framework is executing a JTreg test that calls the framework from within its `main()` method. diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/driver/irmatching/report/FailureMessageBuilder.java b/test/hotspot/jtreg/compiler/lib/ir_framework/driver/irmatching/report/FailureMessageBuilder.java index e4dd98959a0..30e07c44398 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/driver/irmatching/report/FailureMessageBuilder.java +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/driver/irmatching/report/FailureMessageBuilder.java @@ -111,7 +111,8 @@ public void visitLeaf(NotCompilableIRMethodMatchResult result) { @Override public void enter(IRRuleMatchResult result) { indentation.add(); - msg.append(indentation).append("* @IR rule ").append(result.irRuleId()).append(": \"") + String skippedPrefix = result.irAnno().skip() ? "* [Marked as skip] " : "* "; + msg.append(indentation).append(skippedPrefix).append("@IR rule ").append(result.irRuleId()).append(": \"") .append(result.irAnno()).append("\"").append(System.lineSeparator()); } diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java b/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java index 87ed6fbe8e6..4c7b7a2b664 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/test/ApplicableIRRulesPrinter.java @@ -47,6 +47,8 @@ * termination of the Test VM. IR rule indices start at 1. */ public class ApplicableIRRulesPrinter { + private static final boolean IGNORE_SKIP_IR = Boolean.parseBoolean(System.getProperty("IgnoreSkipIR", "false")); + public static final String NO_RULES = ""; private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox(); @@ -167,8 +169,13 @@ public void emitApplicableIRRules(Method m) { } private void printDisableReason(String method, String reason, String[] apply, int ruleIndex, int ruleMax) { + reason = reason + ": " + String.join(", ", apply); + printDisableReason(method, reason, ruleIndex, ruleMax); + } + + private void printDisableReason(String method, String reason, int ruleIndex, int ruleMax) { TestVmSocket.send("Disabling IR matching for rule " + ruleIndex + " of " + ruleMax + " in " + method + ": " + - reason + ": " + String.join(", ", apply)); + reason); } private boolean shouldApplyIrRule(IR irAnno, String m, int ruleIndex, int ruleMax) { @@ -202,6 +209,9 @@ private boolean shouldApplyIrRule(IR irAnno, String m, int ruleIndex, int ruleMa } else if (irAnno.applyIfOr().length != 0 && hasNoRequiredFlags(irAnno.applyIfOr(), "applyIfOr")) { printDisableReason(m, "None of the flag constraints met (applyIfOr)", irAnno.applyIfOr(), ruleIndex, ruleMax); return false; + } else if (shouldSkipIRRule(irAnno)) { + printDisableReason(m, "Defined @IR(skip = true, ...)", ruleIndex, ruleMax); + return false; } else { // All preconditions satisfied: apply rule. return true; @@ -513,6 +523,10 @@ private String failAt() { return " in @IR rule " + ruleIndex + " at " + method; } + private boolean shouldSkipIRRule(IR irAnno) { + return irAnno.skip() && !IGNORE_SKIP_IR; + } + public void emit() { if (output.isEmpty()) { output.append(NO_RULES).append(System.lineSeparator()); diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestMemorySegmentAliasing.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestMemorySegmentAliasing.java index c956ac9a0d4..58bf90d4c01 100644 --- a/test/hotspot/jtreg/compiler/loopopts/superword/TestMemorySegmentAliasing.java +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestMemorySegmentAliasing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -747,12 +747,13 @@ static void test_int_to_long_noaliasing(MemorySegment a, MemorySegment b) { } @Test - // @IR(counts = {IRNode.STORE_VECTOR, "> 0", - // ".*multiversion.*", "> 0"}, // AutoVectorization Predicate FAILS - // phase = CompilePhase.PRINT_IDEAL, - // applyIfPlatform = {"64-bit", "true"}, - // applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, - // applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(skip = true, + counts = {IRNode.STORE_VECTOR, "> 0", + ".*multiversion.*", "> 0"}, // AutoVectorization Predicate FAILS + phase = CompilePhase.PRINT_IDEAL, + applyIfPlatform = {"64-bit", "true"}, + applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // // FAILS: but only on "native" and "byte-buffer-direct" // The issue is that one of the VPointers is invalid. @@ -772,12 +773,13 @@ static void reference_fill_byte_sameMS_alias(MemorySegment a, MemorySegment b, l } @Test - // @IR(counts = {IRNode.STORE_VECTOR, "> 0", - // ".*multiversion.*", "= 0"}, // AutoVectorization Predicate SUFFICES - // phase = CompilePhase.PRINT_IDEAL, - // applyIfPlatform = {"64-bit", "true"}, - // applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, - // applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(skip = true, + counts = {IRNode.STORE_VECTOR, "> 0", + ".*multiversion.*", "= 0"}, // AutoVectorization Predicate SUFFICES + phase = CompilePhase.PRINT_IDEAL, + applyIfPlatform = {"64-bit", "true"}, + applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // // FAILS: but only on "native" and "byte-buffer-direct" // The issue is that one of the VPointers is invalid. @@ -804,11 +806,12 @@ static void reference_fill_byte_sameMS_noalias(MemorySegment a, MemorySegment b, } @Test - // @IR(counts = {IRNode.STORE_VECTOR, "> 0"}, - // phase = CompilePhase.PRINT_IDEAL, - // applyIfPlatform = {"64-bit", "true"}, - // applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, - // applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(skip = true, + counts = {IRNode.STORE_VECTOR, "> 0"}, + phase = CompilePhase.PRINT_IDEAL, + applyIfPlatform = {"64-bit", "true"}, + applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // // FAILS: but only on "native" and "byte-buffer-direct" // The issue is that one of the VPointers is invalid. @@ -830,12 +833,13 @@ static void reference_fill_byte_sameMS_maybeAlias(MemorySegment a, MemorySegment } @Test - // @IR(counts = {IRNode.STORE_VECTOR, "> 0", - // ".*multiversion.*", "> 0"}, // AutoVectorization Predicate FAILS - // phase = CompilePhase.PRINT_IDEAL, - // applyIfPlatform = {"64-bit", "true"}, - // applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, - // applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(skip = true, + counts = {IRNode.STORE_VECTOR, "> 0", + ".*multiversion.*", "> 0"}, // AutoVectorization Predicate FAILS + phase = CompilePhase.PRINT_IDEAL, + applyIfPlatform = {"64-bit", "true"}, + applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // // FAILS: but only on "native" and "byte-buffer-direct" // The issue is that one of the VPointers is invalid. @@ -855,12 +859,13 @@ static void reference_fill_int_sameMS_alias(MemorySegment a, MemorySegment b, lo } @Test - // @IR(counts = {IRNode.STORE_VECTOR, "> 0", - // ".*multiversion.*", "= 0"}, // AutoVectorization Predicate SUFFICES - // phase = CompilePhase.PRINT_IDEAL, - // applyIfPlatform = {"64-bit", "true"}, - // applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, - // applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(skip = true, + counts = {IRNode.STORE_VECTOR, "> 0", + ".*multiversion.*", "= 0"}, // AutoVectorization Predicate SUFFICES + phase = CompilePhase.PRINT_IDEAL, + applyIfPlatform = {"64-bit", "true"}, + applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // // FAILS: but only on "native" and "byte-buffer-direct" // The issue is that one of the VPointers is invalid. @@ -887,11 +892,12 @@ static void reference_fill_int_sameMS_noalias(MemorySegment a, MemorySegment b, } @Test - // @IR(counts = {IRNode.STORE_VECTOR, "> 0"}, - // phase = CompilePhase.PRINT_IDEAL, - // applyIfPlatform = {"64-bit", "true"}, - // applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, - // applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(skip = true, + counts = {IRNode.STORE_VECTOR, "> 0"}, + phase = CompilePhase.PRINT_IDEAL, + applyIfPlatform = {"64-bit", "true"}, + applyIfAnd = {"AlignVector", "false", "UseAutoVectorizationSpeculativeAliasingChecks", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // // FAILS: but only on "native" and "byte-buffer-direct" // The issue is that one of the VPointers is invalid. diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrays.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrays.java index 5369756ac94..fa4c500a539 100644 --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrays.java +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestArrays.java @@ -797,8 +797,9 @@ public void test27_verifier() { // TODO 8252027: Make sure this is optimized with ZGC // TODO 8350865: Support flat arrays in LoadNode::find_previous_arraycopy @Test - // @IR(applyIf = {"UseZGC", "false"}, - // failOn = {ALLOC_ARRAY_OF_MYVALUE_KLASS, LOOP, LOAD_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) + @IR(skip = true, + applyIf = {"UseZGC", "false"}, + failOn = {ALLOC_ARRAY_OF_MYVALUE_KLASS, LOOP, LOAD_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public MyValue2 test28() { MyValue2[] src = (MyValue2[])ValueClass.newNullRestrictedNonAtomicArray(MyValue2.class, 10, MyValue2.DEFAULT); src[0] = MyValue2.createWithFieldsInline(rI, rD); @@ -2783,7 +2784,8 @@ public void test102_verifier() { // Same as test102 but with MyValue2[] dst @Test // TODO 8350865 Re-enable - // @IR(failOn = INTRINSIC_SLOW_PATH) + @IR(skip = true, + failOn = INTRINSIC_TRAP) public void test103() { System.arraycopy(val_src, 0, val_dst, 0, 8); } @@ -2912,10 +2914,12 @@ public void test109_null_verifier() { // Arrays.copyOf with constant source and destination arrays @Test // TODO 8251971 Re-enable - // @IR(applyIf = {"UseArrayFlattening", "true"}, - // counts = {INTRINSIC_TRAP, "= 1"}) - // @IR(applyIf = {"UseArrayFlattening", "false"}, - // failOn = {INTRINSIC_TRAP, CLASS_CHECK_TRAP}) + @IR(skip = true, + applyIf = {"UseArrayFlattening", "true"}, + counts = {INTRINSIC_TRAP, "= 1"}) + @IR(skip = true, + applyIf = {"UseArrayFlattening", "false"}, + failOn = {INTRINSIC_TRAP, CLASS_CHECK_TRAP}) public Object[] test110() { return Arrays.copyOf(val_src, 8, Object[].class); } @@ -2983,10 +2987,12 @@ public void test113_null_verifier() { @Test // TODO 8251971 Re-enable - // @IR(applyIf = {"UseArrayFlattening", "true"}, - // counts = {INTRINSIC_TRAP, "= 1"}) - // @IR(applyIf = {"UseArrayFlattening", "false"}, - // failOn = {INTRINSIC_TRAP, CLASS_CHECK_TRAP}) + @IR(skip = true, + applyIf = {"UseArrayFlattening", "true"}, + counts = {INTRINSIC_TRAP, "= 1"}) + @IR(skip = true, + applyIf = {"UseArrayFlattening", "false"}, + failOn = {INTRINSIC_TRAP, CLASS_CHECK_TRAP}) public Object[] test114() { return Arrays.copyOf((Object[])get_val_src(), 8, get_obj_class()); } @@ -3001,8 +3007,9 @@ public void test114_verifier() { // at parse time it looks as if src could be flat and dst could be not flat @Test // TODO 8251971 Re-enable - // @IR(applyIf = {"UseArrayFlattening", "false"}, - // failOn = {INTRINSIC_TRAP, CLASS_CHECK_TRAP}) + @IR(skip = true, + applyIf = {"UseArrayFlattening", "false"}, + failOn = {INTRINSIC_TRAP, CLASS_CHECK_TRAP}) public Object[] test115() { return Arrays.copyOf((Object[])get_val_src(), 8, get_val_class()); } @@ -3301,9 +3308,10 @@ static void verifyTest127a(Object[] src, Object[] dst, int len, int offset) { // Verify that copyOf with known source and unknown destination class is optimized @Test // TODO 8251971 Re-enable - //@IR(applyIf = {"UseArrayFlattening", "true"}, - // counts = {JLONG_ARRAYCOPY, "= 1"}, - // failOn = CHECKCAST_ARRAYCOPY) + @IR(skip = true, + applyIf = {"UseArrayFlattening", "true"}, + counts = {JLONG_ARRAYCOPY, "= 1"}, + failOn = CHECKCAST_ARRAYCOPY) public Object[] test128(Class klass) { return Arrays.copyOf(val_src, 8, klass); } @@ -3615,7 +3623,8 @@ public void test140_verifier() { // Test load from array that is only known to be not a value class array after parsing // TODO 8255938 @Test - // @IR(failOn = {ALLOC_G, ALLOC_ARRAY, LOOP, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP, LOAD_UNKNOWN_VALUE, STORE_UNKNOWN_VALUE, INLINE_ARRAY_NULL_GUARD}) + @IR(skip = true, + failOn = {ALLOC, ALLOC_ARRAY, LOOP, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP, LOAD_UNKNOWN_VALUE, STORE_UNKNOWN_VALUE, INLINE_ARRAY_NULL_GUARD}) public Object test141() { Object[] array = null; Object[] oarray = new NonValueClass[1]; @@ -3636,7 +3645,8 @@ public void test141_verifier() { // Test store to array that is only known to be not a value class array after parsing // TODO 8255938 @Test - // @IR(failOn = {ALLOC_ARRAY_OF_MYVALUE_KLASS, ALLOC_G, LOOP, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP, LOAD_UNKNOWN_VALUE, STORE_UNKNOWN_VALUE, INLINE_ARRAY_NULL_GUARD}) + @IR(skip = true, + failOn = {ALLOC_ARRAY_OF_MYVALUE_KLASS, ALLOC, LOOP, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP, LOAD_UNKNOWN_VALUE, STORE_UNKNOWN_VALUE, INLINE_ARRAY_NULL_GUARD}) public Object[] test142(Object val) { Object[] array = null; Object[] oarray = new NonValueClass[1]; @@ -3899,8 +3909,9 @@ static value class MyValue152 { // Test that EA works for null-free arrays @Test // TODO 8350865 Scalar replacement does not work well for flat arrays - //@IR(applyIf = {"ValueTypeReturnedAsFields", "true"}, - // failOn = {ALLOC, ALLOCA}) + @IR(skip = true, + applyIf = {"ValueTypeReturnedAsFields", "true"}, + failOn = {ALLOC_OF_MYVALUE_KLASS, ALLOC_ARRAY_OF_MYVALUE_KLASS}) public MyValue152 test152() { MyValue152[] array = (MyValue152[])ValueClass.newNullRestrictedNonAtomicArray(MyValue152.class, 1, new MyValue152()); return array[0]; @@ -3920,8 +3931,9 @@ static value class MyValue153 { // Same as test152 but triggers a slightly different asserts @Test // TODO 8350865 Scalar replacement does not work well for flat arrays - //@IR(applyIf = {"ValueTypeReturnedAsFields", "true"}, - // failOn = {ALLOC, ALLOCA}) + @IR(skip = true, + applyIf = {"ValueTypeReturnedAsFields", "true"}, + failOn = {ALLOC_OF_MYVALUE_KLASS, ALLOC_ARRAY_OF_MYVALUE_KLASS}) public MyValue153 test153() { MyValue153[] array = (MyValue153[])ValueClass.newNullRestrictedNonAtomicArray(MyValue153.class, 1, new MyValue153()); return array[0]; @@ -3935,7 +3947,9 @@ public void test153_verifier() { // Same as test152 but triggers an incorrect result @Test // TODO 8350865 Scalar replacement does not work well for flat arrays - //@IR(failOn = {ALLOC, ALLOCA_G, LOAD, STORE, TRAP}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, ALLOC_ARRAY, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS, PREDICATE_TRAP, + UNSTABLE_IF_TRAP}) public double test154() { MyValue152[] array = (MyValue152[])ValueClass.newNullRestrictedNonAtomicArray(MyValue152.class, 1, new MyValue152()); return array[0].d; diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestBasicFunctionality.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestBasicFunctionality.java index 17d7eb0fa98..88d0285f3bb 100644 --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestBasicFunctionality.java +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestBasicFunctionality.java @@ -281,7 +281,8 @@ public void test7_verifier() { // Merge value objects created from two branches @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}, phase = CompilePhase.BEFORE_MACRO_EXPANSION) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}, phase = CompilePhase.BEFORE_MACRO_EXPANSION) public long test8(boolean b) { MyValue1 v; if (b) { @@ -302,12 +303,14 @@ public void test8_verifier() { // Merge value objects created from two branches @Test // TODO 8380875, 8384979 - // @IR(applyIf = {"ValueTypePassFieldsAsArgs", "true"}, - // counts = {ALLOC_OF_MYVALUE_KLASS, "= 1", LOAD_OF_ANY_KLASS, "= 19", STORE_OF_ANY_KLASS, "= 3"}, - // failOn = {UNSTABLE_IF_TRAP, PREDICATE_TRAP}) - // @IR(applyIf = {"ValueTypePassFieldsAsArgs", "false"}, - // counts = {ALLOC_OF_MYVALUE_KLASS, "= 2", STORE_OF_ANY_KLASS, "= 19"}, - // failOn = {LOAD_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) + @IR(skip = true, + applyIf = {"ValueTypePassFieldsAsArgs", "true"}, + counts = {ALLOC_OF_MYVALUE_KLASS, "= 1", LOAD_OF_ANY_KLASS, "= 19", STORE_OF_ANY_KLASS, "= 3"}, + failOn = {UNSTABLE_IF_TRAP, PREDICATE_TRAP}) + @IR(skip = true, + applyIf = {"ValueTypePassFieldsAsArgs", "false"}, + counts = {ALLOC_OF_MYVALUE_KLASS, "= 2", STORE_OF_ANY_KLASS, "= 19"}, + failOn = {LOAD_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public MyValue1 test9(boolean b, int localrI, long localrL) { MyValue1 v; if (b) { @@ -886,8 +889,6 @@ public void test33_verifier() { // C2 code should load and use the all-zero oop from the java mirror. @Test // The concept of a pre-allocated "all-zero value" was removed. - // @IR(applyIf = {"UseArrayFlattening", "true"}, - // failOn = {ALLOC_OF_MYVALUE_KLASS, ALLOC_ARRAY_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS, LOOP, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public MyValue3 test34() { // Explicitly create all-zero value MyValue3 vt = MyValue3.createDefault(); @@ -921,8 +922,6 @@ public void test34_verifier() { // Same as above but manually initialize value class fields to all-zero. @Test // The concept of a pre-allocated "all-zero value" was removed. - // @IR(applyIf = {"UseArrayFlattening", "true"}, - // failOn = {ALLOC_OF_MYVALUE_KLASS, ALLOC_ARRAY_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS, LOOP, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public MyValue3 test35(MyValue3 vt) { vt = MyValue3.setC(vt, (char)0); vt = MyValue3.setBB(vt, (byte)0); @@ -961,7 +960,8 @@ private Object test36_helper(Object v) { @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public long test36(boolean b) { Object o; if (b) { @@ -1243,7 +1243,8 @@ static class MyValue45Holder { @Test // TODO 8357580 more aggressive flattening - // @IR(applyIfAnd = {"UseFieldFlattening", "true", "UseNullableAtomicValueFlattening", "true"}, counts = {IRNode.LOAD_I, "1", IRNode.LOAD_B, "1"}) + @IR(skip = true, + applyIfAnd = {"UseFieldFlattening", "true", "UseNullableAtomicValueFlattening", "true"}, counts = {IRNode.LOAD_I, "1", IRNode.LOAD_B, "1"}) public Integer test45(Object arg) { return ((MyValue45ValueHolder) arg).v.v; } @@ -1258,8 +1259,10 @@ public void test45_verifier() { @Test // TODO 8357580 more aggressive flattening - // @IR(applyIfAnd = {"UseFieldFlattening", "true", "UseNullableAtomicValueFlattening", "true"}, counts = {IRNode.LOAD_L, "1"}) - // @IR(applyIfAnd = {"UseFieldFlattening", "true", "UseNullableAtomicValueFlattening", "true"}, failOn = {IRNode.LOAD_I, IRNode.LOAD_B}) + @IR(skip = true, + applyIfAnd = {"UseFieldFlattening", "true", "UseNullableAtomicValueFlattening", "true"}, counts = {IRNode.LOAD_L, "1"}) + @IR(skip = true, + applyIfAnd = {"UseFieldFlattening", "true", "UseNullableAtomicValueFlattening", "true"}, failOn = {IRNode.LOAD_I, IRNode.LOAD_B}) public Integer test46(Object arg) { return ((MyValue45Holder) arg).v.v; } diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorld.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorld.java index 88ecba77713..29da4934089 100644 --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorld.java +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorld.java @@ -58,6 +58,7 @@ import static compiler.lib.ir_framework.IRNode.NULL_CHECK_TRAP; import static compiler.lib.ir_framework.IRNode.PREDICATE_TRAP; import static compiler.lib.ir_framework.IRNode.STATIC_CALL_OF_METHOD; +import static compiler.lib.ir_framework.IRNode.STORE; import static compiler.lib.ir_framework.IRNode.STORE_OF_ANY_KLASS; import static compiler.lib.ir_framework.IRNode.STORE_UNKNOWN_VALUE; import static compiler.lib.ir_framework.IRNode.UNSTABLE_IF_TRAP; @@ -5382,7 +5383,8 @@ public String toString() { // Test acmp with deep nesting of flat fields @Test(allowNotCompilable = true) // TODO 8378943: reason should be "failed spill-split-recycle sanity check" // TODO 8384979 - // @IR(failOn = {ALLOC, STORE_OF_ANY_KLASS, STATIC_CALL_OF_METHOD, "isSubstitutable.*"}) + @IR(skip = true, + failOn = {ALLOC, STORE_OF_ANY_KLASS, STATIC_CALL_OF_METHOD, "isSubstitutable.*"}) public boolean test178(Value178 x, Value178 y) { return getter(x) == getter(y); } @@ -5415,7 +5417,8 @@ public void test178_verifier(RunInfo info) { // Same as test178 but with object argument @Test(allowNotCompilable = true) // TODO 8378943: reason should be "failed spill-split-recycle sanity check" // TODO 8384979 - // @IR(failOn = {ALLOC, STORE_OF_ANY_KLASS, STATIC_CALL_OF_METHOD, "isSubstitutable.*"}) + @IR(skip = true, + failOn = {ALLOC, STORE_OF_ANY_KLASS, STATIC_CALL_OF_METHOD, "isSubstitutable.*"}) public boolean test179(Value178 x, Object y) { return getter(x) == getter(y); } @@ -5453,7 +5456,8 @@ public void test179_verifier(RunInfo info) { // Test constant folding @Test // TODO 8384979 - // @IR(failOn = {ALLOC, LOAD, STORE, STATIC_CALL_OF_METHOD, "isSubstitutable.*"}) + @IR(skip = true, + failOn = {ALLOC, LOAD, STORE, STATIC_CALL_OF_METHOD, "isSubstitutable.*"}) public boolean test180() { Object val1 = null; Object val2 = null; diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorldProfiling.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorldProfiling.java index 24e51297666..95c83dcf3c2 100644 --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorldProfiling.java +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestLWorldProfiling.java @@ -1221,14 +1221,14 @@ public void test42_verifier() { @Test // TODO 8384979 - // @IR(applyIfOr = {"UseACmpProfile", "true", "TypeProfileLevel", "= 222"}, - // failOn = {STATIC_CALL_OF_METHOD, "isSubstitutable.*"}, - // counts = {LOAD_OF_CLASS, "MyValue1", "> 30"} // Loading all the fields, there are many. - // ) - // @IR(applyIfAnd = {"UseACmpProfile", "false", "TypeProfileLevel", "!= 222"}, - // failOn = {LOAD_OF_CLASS, "MyValue1"}, - // counts = {STATIC_CALL_OF_METHOD, "isSubstitutable.*", ">= 1"} - // ) + @IR(skip = true, + applyIfOr = {"UseACmpProfile", "true", "TypeProfileLevel", "= 222"}, + failOn = {STATIC_CALL_OF_METHOD, "isSubstitutable.*"}, + counts = {LOAD_OF_CLASS, "MyValue1", "> 30"}) // Loading all the fields, there are many. + @IR(skip = true, + applyIfAnd = {"UseACmpProfile", "false", "TypeProfileLevel", "!= 222"}, + failOn = {LOAD_OF_CLASS, "MyValue1"}, + counts = {STATIC_CALL_OF_METHOD, "isSubstitutable.*", ">= 1"}) public static boolean test43(Object a, Object b) { return a == b; } @@ -1243,14 +1243,14 @@ public void test43_verifier() { @Test // TODO 8384979 - // @IR(applyIfOr = {"UseACmpProfile", "true", "TypeProfileLevel", "= 222"}, - // failOn = {STATIC_CALL_OF_METHOD, "isSubstitutable.*"}, - // counts = {LOAD_OF_CLASS, "MyValue1", "> 30"} // Loading all the fields, there are many. - // ) - // @IR(applyIfAnd = {"UseACmpProfile", "false", "TypeProfileLevel", "!= 222"}, - // failOn = {LOAD_OF_CLASS, "MyValue1"}, - // counts = {STATIC_CALL_OF_METHOD, "isSubstitutable.*", ">= 1"} - // ) + @IR(skip = true, + applyIfOr = {"UseACmpProfile", "true", "TypeProfileLevel", "= 222"}, + failOn = {STATIC_CALL_OF_METHOD, "isSubstitutable.*"}, + counts = {LOAD_OF_CLASS, "MyValue1", "> 30"}) // Loading all the fields, there are many. + @IR(skip = true, + applyIfAnd = {"UseACmpProfile", "false", "TypeProfileLevel", "!= 222"}, + failOn = {LOAD_OF_CLASS, "MyValue1"}, + counts = {STATIC_CALL_OF_METHOD, "isSubstitutable.*", ">= 1"}) public static boolean test44(Object a, Object b) { return a == b; } @@ -1266,14 +1266,14 @@ public void test44_verifier() { @Test // TODO 8384979 - // @IR(applyIfOr = {"UseACmpProfile", "true", "TypeProfileLevel", "= 222"}, - // failOn = {STATIC_CALL_OF_METHOD, "isSubstitutable.*"}, - // counts = {LOAD_OF_CLASS, "MyValue1", "> 30"} // Loading all the fields, there are many. - // ) - // @IR(applyIfAnd = {"UseACmpProfile", "false", "TypeProfileLevel", "!= 222"}, - // failOn = {LOAD_OF_CLASS, "MyValue1"}, - // counts = {STATIC_CALL_OF_METHOD, "isSubstitutable.*", ">= 1"} - // ) + @IR(skip = true, + applyIfOr = {"UseACmpProfile", "true", "TypeProfileLevel", "= 222"}, + failOn = {STATIC_CALL_OF_METHOD, "isSubstitutable.*"}, + counts = {LOAD_OF_CLASS, "MyValue1", "> 30"}) // Loading all the fields, there are many. + @IR(skip = true, + applyIfAnd = {"UseACmpProfile", "false", "TypeProfileLevel", "!= 222"}, + failOn = {LOAD_OF_CLASS, "MyValue1"}, + counts = {STATIC_CALL_OF_METHOD, "isSubstitutable.*", ">= 1"}) public static boolean test45(Object a, Object b) { return a == b; } diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableArrays.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableArrays.java index 0e6e8de6b0b..1a10f325e37 100644 --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableArrays.java +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableArrays.java @@ -3017,7 +3017,8 @@ public void test112_verifier(RunInfo info) { // Same as test112 but with call to hash() @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public long test113(boolean b) { MyValue1 val = MyValue1.createWithFieldsInline(rI, rL); if (b) { diff --git a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableValueTypes.java b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableValueTypes.java index 61e168ae1cc..f9e324c5cd6 100644 --- a/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableValueTypes.java +++ b/test/hotspot/jtreg/compiler/valhalla/valuetypes/TestNullableValueTypes.java @@ -1188,7 +1188,8 @@ public void test41_verifier(RunInfo info) { // Same as test41 but with call to hash() @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public long test42(boolean b) { MyValue1 val = MyValue1.createWithFieldsInline(rI, rL); if (b) { @@ -1237,7 +1238,8 @@ public void test43_verifier(RunInfo info) { // Test scalarization when .ref is referenced in safepoint debug info @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public int test44(boolean b1, boolean b2, Method m) { MyValue1 val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -1517,7 +1519,8 @@ public void test55_verifier(RunInfo info) { @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS, UNSTABLE_IF_TRAP, PREDICATE_TRAP}) public long test56(boolean b) { MyValue1 val = MyValue1.createWithFieldsInline(rI, rL); MyValue1Wrapper w = new MyValue1Wrapper(val); @@ -1568,7 +1571,8 @@ public void test57_verifier(RunInfo info) { // Test scalarization when .ref is referenced in safepoint debug info @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public int test58(boolean b1, boolean b2, Method m) { MyValue1 val = MyValue1.createWithFieldsInline(rI, rL); MyValue1Wrapper w = new MyValue1Wrapper(val); @@ -1803,7 +1807,8 @@ public Object test67_helper2() { // Test that .ref return does not block scalarization @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public long test67(boolean b1, boolean b2, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -1845,7 +1850,8 @@ public Object test68_helper(Object arg) { // Test that scalarization enabled by cast is applied to parsing map @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public int test68(boolean b1, boolean b2, Object arg, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -1885,7 +1891,8 @@ public Object test69_helper(Object arg) { // Same as test68 but with ClassCastException @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public int test69(boolean b1, boolean b2, Object arg, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -1932,7 +1939,8 @@ public Object test70_helper(Object arg) { // Same as test68 but with ClassCastException and frequent NullPointerException @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public int test70(boolean b1, boolean b2, Object arg, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -1979,7 +1987,8 @@ public Object test71_helper(Object arg) { // Same as test68 but with .ref cast @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public int test71(boolean b1, boolean b2, Object arg, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -2019,7 +2028,8 @@ public Object test72_helper(Object arg) { // Same as test71 but with ClassCastException and hash() call @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public long test72(boolean b1, boolean b2, Object arg, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -2066,7 +2076,8 @@ public Object test73_helper(Object arg) { // Same as test71 but with ClassCastException and frequent NullPointerException @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public int test73(boolean b1, boolean b2, Object arg, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -2112,7 +2123,8 @@ public Object test74_helper(Object arg) { // Same as test73 but result of cast is used and hash() is called @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, STORE_OF_ANY_KLASS}) public long test74(boolean b1, boolean b2, Object arg, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -2178,7 +2190,8 @@ public Object test76_helper() { // Test that constant null field does not block scalarization @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test76(boolean b1, boolean b2, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -2222,7 +2235,8 @@ public Object test77_helper() { // Test that constant object field with value class content does not block scalarization @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test77(boolean b1, boolean b2, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -2253,7 +2267,8 @@ public Object test78_helper() { // Test that constant null does not block scalarization @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test78(boolean b1, boolean b2, Method m) { Object val = MyValue1.createWithFieldsInline(rI, rL); if (b1) { @@ -2295,7 +2310,8 @@ public Object test79_helper() { // Same as test78 but will trigger different order of PhiNode inputs @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test79(boolean b1, boolean b2, Method m) { Object val = test79_helper(); if (b1) { @@ -2369,7 +2385,8 @@ public Object test81_helper(Object obj, int i) { // Test nested loops @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test81() { Object val = null; for (int i = 0; i < 10; ++i) { @@ -2405,7 +2422,8 @@ public Object test82_helper(Object obj, int i) { // Test loops with casts @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test82() { Object val = null; for (int i = 0; i < 10; ++i) { @@ -2443,7 +2461,8 @@ public Object test83_helper(boolean b) { // Test that CastPP does not block scalarization in safepoints @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test83(boolean b, Method m) { Object val = test83_helper(b); if (val != null) { @@ -2473,7 +2492,8 @@ public Object test84_helper(Object obj, int i) { // Same as test80 but with wrapper @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test84() { Object val = new MyValue1Wrapper(MyValue1.createWithFieldsInline(rI, rL)); for (int i = 0; i < 100; ++i) { @@ -2503,7 +2523,8 @@ public Object test85_helper(Object obj, int i) { // Same as test81 but with wrapper @Test // TODO 8384979 - // @IR(failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) + @IR(skip = true, + failOn = {ALLOC_OF_MYVALUE_KLASS, LOAD_OF_ANY_KLASS, STORE_OF_ANY_KLASS}) public long test85() { Object val = new MyValue1Wrapper(null); for (int i = 0; i < 10; ++i) { diff --git a/test/hotspot/jtreg/compiler/vectorization/runner/ArrayInvariantFillTest.java b/test/hotspot/jtreg/compiler/vectorization/runner/ArrayInvariantFillTest.java index 90e4955bee3..fc79a6728ed 100644 --- a/test/hotspot/jtreg/compiler/vectorization/runner/ArrayInvariantFillTest.java +++ b/test/hotspot/jtreg/compiler/vectorization/runner/ArrayInvariantFillTest.java @@ -69,9 +69,10 @@ protected String[] testVMFlags(String[] args) { // ---------------- Simple Fill ---------------- @Test // TODO 8387402 - //@IR(applyIfCPUFeatureOr = {"asimd", "true", "sse2", "true", "rvv", "true"}, - // applyIf = {"OptimizeFill", "false"}, - // counts = {IRNode.REPLICATE_B, ">0"}) + @IR(skip = true, + applyIfCPUFeatureOr = {"asimd", "true", "sse2", "true", "rvv", "true"}, + applyIf = {"OptimizeFill", "false"}, + counts = {IRNode.REPLICATE_B, ">0"}) @IR(applyIfCPUFeatureOr = {"asimd", "true", "sse2", "true", "rvv", "true"}, applyIf = {"OptimizeFill", "true"}, counts = {IRNode.REPLICATE_B, "0"}) diff --git a/test/hotspot/jtreg/testlibrary_tests/ir_framework/examples/IRExample.java b/test/hotspot/jtreg/testlibrary_tests/ir_framework/examples/IRExample.java index 3a6339da160..f3c253d3320 100644 --- a/test/hotspot/jtreg/testlibrary_tests/ir_framework/examples/IRExample.java +++ b/test/hotspot/jtreg/testlibrary_tests/ir_framework/examples/IRExample.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -222,6 +222,18 @@ static float[] testVectorNodeSizeMinClause() { } return a; } + + // If IR matching is currently failing and there is no fix available, we can use the @IR(skip = true) attribute + // instead of commenting the rule out to disable IR matching. This approach still allows us to perform IR matching + // on demand with -DIgnoreSkipIR=true to quickly check if an IR rule is still failing or not. + // + // Note: If there is also a problem executing the entire test, consider using @Skip instead. + @Test + @IR(skip = true, // Skip this IR rule to avoid the (obvious) IR rule matching failure + failOn = IRNode.STORE_I) // Normally skipped but could still be checked on demand by using -DIgnoreSkipIR=true + void testDisableIRMatching() { + iFld = 34; + } } class FailingExamples { diff --git a/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestSkipIR.java b/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestSkipIR.java new file mode 100644 index 00000000000..197edd20fc0 --- /dev/null +++ b/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestSkipIR.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package ir_framework.tests; + +import compiler.lib.ir_framework.*; +import compiler.lib.ir_framework.driver.irmatching.IRViolationException; +import jdk.test.lib.Asserts; + +import java.util.regex.Pattern; + +/* + * @test + * @requires vm.debug == true & vm.compMode != "Xint" & vm.compiler1.enabled & vm.compiler2.enabled & vm.flagless + * @summary Test skipping IR rules with IR skip attribute + * @library /test/lib /testlibrary_tests / + * @run driver ${test.main.class} + */ + +public class TestSkipIR { + public static void main(String[] args) { + runGood(); + runIgnoreSkipIR(); + runIgnoreSkipAndSkipIR(); + runNotCompiledTest(); + runNotCompilable(); + } + + private static void runGood() { + TestFramework.run(); + TestFramework.runWithFlags("-DIgnoreSkip=true"); // IR rules still skipped + TestFramework.run(NotCompiledSkippedIR.class); // IR rules still skipped + } + + private static void runIgnoreSkipIR() { + try { + TestFramework.runWithFlags("-DIgnoreSkipIR=true"); + Asserts.fail("should fail IR matching"); + } catch (IRViolationException e) { + String message = e.getExceptionInfo(); + checkHeader(message, 4, 3); + checkTestMethods(message, "testNoSkip"); + assertIrRuleCount(message, 1, 3); + assertIrRuleCount(message, 3, 1); + } + } + + private static void runIgnoreSkipAndSkipIR() { + try { + TestFramework.runWithFlags("-DIgnoreSkip=true", "-DIgnoreSkipIR=true"); + Asserts.fail("should fail IR matching"); + } catch (IRViolationException e) { + String message = e.getExceptionInfo(); + checkHeader(message, 8, 6); + checkTestMethods(message, "testNoSkip"); + checkTestMethods(message, "testYesSkip"); + assertIrRuleCount(message, 1, 6); + assertIrRuleCount(message, 3, 2); + } + } + + private static void runNotCompiledTest() { + try { + new TestFramework(NotCompiledSkippedIR.class) + .addFlags("-DIgnoreSkipIR=true") + .start(); + Asserts.fail("should fail IR matching"); + } catch (IRViolationException e) { + String message = e.getExceptionInfo(); + checkHeader(message, 1, 1); + Asserts.assertTrue(message.contains("test\" - [Failed IR rules: 1]")); + Asserts.assertTrue(message.contains("Method was not compiled. Did you specify a @Run method in STANDALONE mode")); + } + } + + private static void runNotCompilable() { + new TestFramework(NotCompilableSkippedIR.class) + .addFlags("-XX:CompileCommand=compileonly,*NotCompilableSkippedIR::test,0111") + .start(); + new TestFramework(NotCompilableSkippedIR.class) + .addFlags("-DIgnoreSkipIR=true", + "-XX:CompileCommand=compileonly,*NotCompilableSkippedIR::test,0111") + .start(); + } + + private static void checkHeader(String message, int irRuleCount, int methodCount) { + Asserts.assertTrue(message.contains("Failed IR Rules (" + irRuleCount + ") of Methods (" + methodCount + ")")); + + } + + private static void checkTestMethods(String message, String methodPrefix) { + Asserts.assertTrue(message.contains(methodPrefix + "1\" - [Failed IR rules: 1]")); + Asserts.assertTrue(message.contains(methodPrefix + "2\" - [Failed IR rules: 1]")); + Asserts.assertTrue(message.contains(methodPrefix + "3\" - [Failed IR rules: 2]")); + } + + private static void assertIrRuleCount(String message, int ruleIndex, int expectedCount) { + Asserts.assertEQ(expectedCount, message.split(Pattern.quote("[Marked as skip] @IR rule " + ruleIndex), -1).length - 1); + } + + @Test + @IR(skip = true, + counts = {IRNode.CALL, "2"}) // normally fails + public static void testNoSkip1() {} + + @Test + @IR(skip = true, + counts = {IRNode.CALL, "2"}) // normally fails + @IR(failOn = IRNode.CALL) + public static void testNoSkip2() {} + + @Test + @IR(skip = true, + counts = {IRNode.CALL, "2"}) // normally fails + @IR(failOn = IRNode.CALL) + @IR(skip = true, + counts = {IRNode.CALL, "1"}) // normally fails + public static void testNoSkip3() {} + + @Test + @Skip + @IR(skip = true, + counts = {IRNode.CALL, "2"}) // normally fails + public static void testYesSkip1() {} + + @Test + @Skip + @IR(skip = true, + counts = {IRNode.CALL, "2"}) // normally fails + @IR(failOn = IRNode.CALL) + public static void testYesSkip2() {} + + @Test + @Skip + @IR(skip = true, + counts = {IRNode.CALL, "2"}) // normally fails + @IR(failOn = IRNode.CALL) + @IR(skip = true, + counts = {IRNode.CALL, "1"}) // normally fails + public static void testYesSkip3() {} +} + +class NotCompiledSkippedIR { + static int iFld; + + @Test + @IR(skip = true, + failOn = IRNode.STORE_I) + public static void test() { + iFld = 34; + } + + @Run(test = "test", mode = RunMode.STANDALONE) + public static void run() { + test(); // Only invoke once, not enough to trigger C2 compilation + } +} + +class NotCompilableSkippedIR { + static int iFld; + + @Test(allowNotCompilable = true) // We disable compilation for C2 for this method + @IR(skip = true, + failOn = IRNode.STORE_I) + public static void test() { + iFld = 34; + } +} From 4626910fd91422e039a28dfa9e5ffe9283f3668e Mon Sep 17 00:00:00 2001 From: Andrew Haley Date: Mon, 23 Nov 2026 14:22:12 +0000 Subject: [PATCH 43/95] 8396508: AArch64: Clean up atomic stubs Reviewed-by: adinn, jsikstro, fbredberg --- src/hotspot/cpu/aarch64/atomic_aarch64.hpp | 65 ++- .../cpu/aarch64/stubDeclarations_aarch64.hpp | 45 --- .../cpu/aarch64/stubGenerator_aarch64.cpp | 308 +-------------- .../cpu/aarch64/vm_version_aarch64.cpp | 18 + .../linux_aarch64/atomic_linux_aarch64.S | 369 ++++-------------- .../linux_aarch64/atomic_linux_aarch64.s.inc | 217 ++++++++++ 6 files changed, 366 insertions(+), 656 deletions(-) create mode 100644 src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.s.inc diff --git a/src/hotspot/cpu/aarch64/atomic_aarch64.hpp b/src/hotspot/cpu/aarch64/atomic_aarch64.hpp index be06f0c4adc..5ebb818a1df 100644 --- a/src/hotspot/cpu/aarch64/atomic_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/atomic_aarch64.hpp @@ -1,4 +1,5 @@ /* Copyright (c) 2021, Red Hat Inc. All rights reserved. + * Copyright (c) 2026, IBM Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +25,26 @@ #ifndef CPU_AARCH64_ATOMIC_AARCH64_HPP #define CPU_AARCH64_ATOMIC_AARCH64_HPP +#ifdef __cplusplus + +#define DEFAULT_ATOMIC_OP(OPNAME, SIZE, MEMORDER) \ + extern "C" aarch64_atomic_stub_t aarch64_atomic_ ## OPNAME ## _ ## SIZE ## MEMORDER ## _impl; + +typedef uint64_t (*aarch64_atomic_stub_t)(volatile void *ptr, uint64_t arg1, uint64_t arg2); + +#define ATOMIC_OPS_START \ + extern address aarch64_atomic_ops[], lse_aarch64_atomic_ops[]; +#define ATOMIC_OPS_END \ + extern address aarch64_atomic_ops_end[], lse_aarch64_atomic_ops_end[]; + +#elif defined(__ASSEMBLER__) + +#else + +#error One of these must be defined + +#endif + // Atomic stub implementation. // Default implementations are in atomic_linux_aarch64.S // @@ -32,25 +53,33 @@ // x1: arg1 // x2: arg2 (optional) // x3, x8, x9: scratch -typedef uint64_t (*aarch64_atomic_stub_t)(volatile void *ptr, uint64_t arg1, uint64_t arg2); + +// DEFAULT_ATOMIC_OP(name, bytesize, memory_order) +// memory_order is blank (i.e. conservative), _acquire, _release, _acq_rel, _seq_cst // Pointers to stubs -extern aarch64_atomic_stub_t aarch64_atomic_fetch_add_4_impl; -extern aarch64_atomic_stub_t aarch64_atomic_fetch_add_8_impl; -extern aarch64_atomic_stub_t aarch64_atomic_fetch_add_4_relaxed_impl; -extern aarch64_atomic_stub_t aarch64_atomic_fetch_add_8_relaxed_impl; -extern aarch64_atomic_stub_t aarch64_atomic_xchg_1_impl; -extern aarch64_atomic_stub_t aarch64_atomic_xchg_4_impl; -extern aarch64_atomic_stub_t aarch64_atomic_xchg_8_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_1_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_4_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_8_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_1_relaxed_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_4_relaxed_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_8_relaxed_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_4_release_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_8_release_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_4_seq_cst_impl; -extern aarch64_atomic_stub_t aarch64_atomic_cmpxchg_8_seq_cst_impl; + +#define DO_ATOMIC_STUBS \ +DEFAULT_ATOMIC_OP(fetch_add, 4, ) \ +DEFAULT_ATOMIC_OP(fetch_add, 8, ) \ +DEFAULT_ATOMIC_OP(fetch_add, 4, _relaxed) \ +DEFAULT_ATOMIC_OP(fetch_add, 8, _relaxed) \ +DEFAULT_ATOMIC_OP(xchg, 1, ) \ +DEFAULT_ATOMIC_OP(xchg, 4, ) \ +DEFAULT_ATOMIC_OP(xchg, 8, ) \ +DEFAULT_ATOMIC_OP(cmpxchg, 1, ) \ +DEFAULT_ATOMIC_OP(cmpxchg, 4, ) \ +DEFAULT_ATOMIC_OP(cmpxchg, 8, ) \ +DEFAULT_ATOMIC_OP(cmpxchg, 1, _relaxed) \ +DEFAULT_ATOMIC_OP(cmpxchg, 4, _relaxed) \ +DEFAULT_ATOMIC_OP(cmpxchg, 8, _relaxed) \ +DEFAULT_ATOMIC_OP(cmpxchg, 4, _release) \ +DEFAULT_ATOMIC_OP(cmpxchg, 8, _release) \ +DEFAULT_ATOMIC_OP(cmpxchg, 4, _seq_cst) \ +DEFAULT_ATOMIC_OP(cmpxchg, 8, _seq_cst) + +ATOMIC_OPS_START +DO_ATOMIC_STUBS +ATOMIC_OPS_END #endif // CPU_AARCH64_ATOMIC_AARCH64_HPP diff --git a/src/hotspot/cpu/aarch64/stubDeclarations_aarch64.hpp b/src/hotspot/cpu/aarch64/stubDeclarations_aarch64.hpp index 77c6b47eed2..cbd438024b3 100644 --- a/src/hotspot/cpu/aarch64/stubDeclarations_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/stubDeclarations_aarch64.hpp @@ -147,51 +147,6 @@ do_stub(final, spin_wait) \ do_arch_entry_init(aarch64, final, spin_wait, spin_wait, \ spin_wait, empty_spin_wait) \ - /* n.b. these are not the same as the generic atomic stubs */ \ - do_stub(final, atomic_entry_points) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_fetch_add_4_impl, atomic_fetch_add_4_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_fetch_add_8_impl, atomic_fetch_add_8_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_fetch_add_4_relaxed_impl, \ - atomic_fetch_add_4_relaxed_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_fetch_add_8_relaxed_impl, \ - atomic_fetch_add_8_relaxed_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_xchg_1_impl, atomic_xchg_1_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_xchg_4_impl, atomic_xchg_4_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_xchg_8_impl, atomic_xchg_8_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_1_impl, atomic_cmpxchg_1_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_4_impl, atomic_cmpxchg_4_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_8_impl, atomic_cmpxchg_8_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_1_relaxed_impl, \ - atomic_cmpxchg_1_relaxed_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_4_relaxed_impl, \ - atomic_cmpxchg_4_relaxed_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_8_relaxed_impl, \ - atomic_cmpxchg_8_relaxed_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_4_release_impl, \ - atomic_cmpxchg_4_release_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_8_release_impl, \ - atomic_cmpxchg_8_release_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_4_seq_cst_impl, \ - atomic_cmpxchg_4_seq_cst_impl) \ - do_arch_entry(aarch64, final, atomic_entry_points, \ - atomic_cmpxchg_8_seq_cst_impl, \ - atomic_cmpxchg_8_seq_cst_impl) \ #endif // CPU_AARCH64_STUBDECLARATIONS_AARCH64_HPP diff --git a/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp b/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp index 01072bec15a..53e0fab7c82 100644 --- a/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, 2025, Red Hat Inc. All rights reserved. + * Copyright (c) 2026, IBM Inc. All rights reserved. * Copyright 2026 Arm Limited and/or its affiliates. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -12272,275 +12273,6 @@ class StubGenerator: public StubCodeGenerator { return start; } -#if defined (LINUX) && !defined (__ARM_FEATURE_ATOMICS) - - // ARMv8.1 LSE versions of the atomic stubs used by AtomicAccess::PlatformXX. - // - // If LSE is in use, generate LSE versions of all the stubs. The - // non-LSE versions are in atomic_aarch64.S. - - // class AtomicStubMark records the entry point of a stub and the - // stub pointer which will point to it. The stub pointer is set to - // the entry point when ~AtomicStubMark() is called, which must be - // after ICache::invalidate_range. This ensures safe publication of - // the generated code. - class AtomicStubMark { - address _entry_point; - aarch64_atomic_stub_t *_stub; - MacroAssembler *_masm; - public: - AtomicStubMark(MacroAssembler *masm, aarch64_atomic_stub_t *stub) { - _masm = masm; - __ align(32); - _entry_point = __ pc(); - _stub = stub; - } - ~AtomicStubMark() { - *_stub = (aarch64_atomic_stub_t)_entry_point; - } - }; - - // NB: For memory_order_conservative we need a trailing membar after - // LSE atomic operations but not a leading membar. - // - // We don't need a leading membar because a clause in the Arm ARM - // says: - // - // Barrier-ordered-before - // - // Barrier instructions order prior Memory effects before subsequent - // Memory effects generated by the same Observer. A read or a write - // RW1 is Barrier-ordered-before a read or a write RW 2 from the same - // Observer if and only if RW1 appears in program order before RW 2 - // and [ ... ] at least one of RW 1 and RW 2 is generated by an atomic - // instruction with both Acquire and Release semantics. - // - // All the atomic instructions {ldaddal, swapal, casal} have Acquire - // and Release semantics, therefore we don't need a leading - // barrier. However, there is no corresponding Barrier-ordered-after - // relationship, therefore we need a trailing membar to prevent a - // later store or load from being reordered with the store in an - // atomic instruction. - // - // This was checked by using the herd7 consistency model simulator - // (http://diy.inria.fr/) with this test case: - // - // AArch64 LseCas - // { 0:X1=x; 0:X2=y; 1:X1=x; 1:X2=y; } - // P0 | P1; - // LDR W4, [X2] | MOV W3, #0; - // DMB LD | MOV W4, #1; - // LDR W3, [X1] | CASAL W3, W4, [X1]; - // | DMB ISH; - // | STR W4, [X2]; - // exists - // (0:X3=0 /\ 0:X4=1) - // - // If X3 == 0 && X4 == 1, the store to y in P1 has been reordered - // with the store to x in P1. Without the DMB in P1 this may happen. - // - // At the time of writing we don't know of any AArch64 hardware that - // reorders stores in this way, but the Reference Manual permits it. - - void gen_cas_entry(Assembler::operand_size size, - atomic_memory_order order) { - Register prev = r3, ptr = c_rarg0, compare_val = c_rarg1, - exchange_val = c_rarg2; - bool acquire, release; - switch (order) { - case memory_order_relaxed: - acquire = false; - release = false; - break; - case memory_order_release: - acquire = false; - release = true; - break; - default: - acquire = true; - release = true; - break; - } - __ mov(prev, compare_val); - __ lse_cas(prev, exchange_val, ptr, size, acquire, release, /*not_pair*/true); - if (order == memory_order_conservative) { - __ membar(Assembler::StoreStore|Assembler::StoreLoad); - } - if (size == Assembler::xword) { - __ mov(r0, prev); - } else { - __ movw(r0, prev); - } - __ ret(lr); - } - - void gen_ldadd_entry(Assembler::operand_size size, atomic_memory_order order) { - Register prev = r2, addr = c_rarg0, incr = c_rarg1; - // If not relaxed, then default to conservative. Relaxed is the only - // case we use enough to be worth specializing. - if (order == memory_order_relaxed) { - __ ldadd(size, incr, prev, addr); - } else { - __ ldaddal(size, incr, prev, addr); - __ membar(Assembler::StoreStore|Assembler::StoreLoad); - } - if (size == Assembler::xword) { - __ mov(r0, prev); - } else { - __ movw(r0, prev); - } - __ ret(lr); - } - - void gen_swpal_entry(Assembler::operand_size size) { - Register prev = r2, addr = c_rarg0, incr = c_rarg1; - __ swpal(size, incr, prev, addr); - __ membar(Assembler::StoreStore|Assembler::StoreLoad); - if (size == Assembler::xword) { - __ mov(r0, prev); - } else { - __ movw(r0, prev); - } - __ ret(lr); - } - - void generate_atomic_entry_points() { - if (! UseLSE) { - return; - } - StubId stub_id = StubId::stubgen_atomic_entry_points_id; - GrowableArray

entries; - int entry_count = StubInfo::entry_count(stub_id); - address start = load_archive_data(stub_id, &entries); - if (start != nullptr) { - assert(entries.length() == entry_count - 1, - "unexpected extra entry count %d", entries.length()); - aarch64_atomic_fetch_add_4_impl = (aarch64_atomic_stub_t)start; - int idx = 0; - aarch64_atomic_fetch_add_8_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_fetch_add_4_relaxed_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_fetch_add_8_relaxed_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_xchg_1_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_xchg_4_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_xchg_8_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_1_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_4_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_8_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_1_relaxed_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_4_relaxed_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_8_relaxed_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_4_release_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_8_release_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_4_seq_cst_impl = (aarch64_atomic_stub_t)entries.at(idx++); - aarch64_atomic_cmpxchg_8_seq_cst_impl = (aarch64_atomic_stub_t)entries.at(idx++); - assert(idx == entries.length(), "sanity!"); - return; - } - - __ align(CodeEntryAlignment); - StubCodeMark mark(this, stub_id); - start = __ pc(); - address end; - { - // ADD, memory_order_conservative - AtomicStubMark mark_fetch_add_4(_masm, &aarch64_atomic_fetch_add_4_impl); - gen_ldadd_entry(Assembler::word, memory_order_conservative); - - AtomicStubMark mark_fetch_add_8(_masm, &aarch64_atomic_fetch_add_8_impl); - gen_ldadd_entry(Assembler::xword, memory_order_conservative); - - // ADD, memory_order_relaxed - AtomicStubMark mark_fetch_add_4_relaxed - (_masm, &aarch64_atomic_fetch_add_4_relaxed_impl); - gen_ldadd_entry(Assembler::word, memory_order_relaxed); - - AtomicStubMark mark_fetch_add_8_relaxed - (_masm, &aarch64_atomic_fetch_add_8_relaxed_impl); - gen_ldadd_entry(Assembler::xword, memory_order_relaxed); - - // XCHG, memory_order_conservative - AtomicStubMark mark_xchg_1(_masm, &aarch64_atomic_xchg_1_impl); - gen_swpal_entry(Assembler::byte); - - AtomicStubMark mark_xchg_4(_masm, &aarch64_atomic_xchg_4_impl); - gen_swpal_entry(Assembler::word); - - AtomicStubMark mark_xchg_8(_masm, &aarch64_atomic_xchg_8_impl); - gen_swpal_entry(Assembler::xword); - - // CAS, memory_order_conservative - AtomicStubMark mark_cmpxchg_1(_masm, &aarch64_atomic_cmpxchg_1_impl); - gen_cas_entry(Assembler::byte, memory_order_conservative); - - AtomicStubMark mark_cmpxchg_4(_masm, &aarch64_atomic_cmpxchg_4_impl); - gen_cas_entry(Assembler::word, memory_order_conservative); - - AtomicStubMark mark_cmpxchg_8(_masm, &aarch64_atomic_cmpxchg_8_impl); - gen_cas_entry(Assembler::xword, memory_order_conservative); - - // CAS, memory_order_relaxed - AtomicStubMark mark_cmpxchg_1_relaxed - (_masm, &aarch64_atomic_cmpxchg_1_relaxed_impl); - gen_cas_entry(Assembler::byte, memory_order_relaxed); - - AtomicStubMark mark_cmpxchg_4_relaxed - (_masm, &aarch64_atomic_cmpxchg_4_relaxed_impl); - gen_cas_entry(Assembler::word, memory_order_relaxed); - - AtomicStubMark mark_cmpxchg_8_relaxed - (_masm, &aarch64_atomic_cmpxchg_8_relaxed_impl); - gen_cas_entry(Assembler::xword, memory_order_relaxed); - - AtomicStubMark mark_cmpxchg_4_release - (_masm, &aarch64_atomic_cmpxchg_4_release_impl); - gen_cas_entry(Assembler::word, memory_order_release); - - AtomicStubMark mark_cmpxchg_8_release - (_masm, &aarch64_atomic_cmpxchg_8_release_impl); - gen_cas_entry(Assembler::xword, memory_order_release); - - AtomicStubMark mark_cmpxchg_4_seq_cst - (_masm, &aarch64_atomic_cmpxchg_4_seq_cst_impl); - gen_cas_entry(Assembler::word, memory_order_seq_cst); - - AtomicStubMark mark_cmpxchg_8_seq_cst - (_masm, &aarch64_atomic_cmpxchg_8_seq_cst_impl); - gen_cas_entry(Assembler::xword, memory_order_seq_cst); - - end = __ pc(); - - ICache::invalidate_range(start, end - start); - // exit block to force update of AtomicStubMark targets - } - - assert(start == (address)aarch64_atomic_fetch_add_4_impl, - "atomic stub should be at start of buffer"); - // record the stub start and end plus all the entries saved by the - // AtomicStubMark destructor - entries.append((address)aarch64_atomic_fetch_add_8_impl); - entries.append((address)aarch64_atomic_fetch_add_4_relaxed_impl); - entries.append((address)aarch64_atomic_fetch_add_8_relaxed_impl); - entries.append((address)aarch64_atomic_xchg_1_impl); - entries.append((address)aarch64_atomic_xchg_4_impl); - entries.append((address)aarch64_atomic_xchg_8_impl); - entries.append((address)aarch64_atomic_cmpxchg_1_impl); - entries.append((address)aarch64_atomic_cmpxchg_4_impl); - entries.append((address)aarch64_atomic_cmpxchg_8_impl); - entries.append((address)aarch64_atomic_cmpxchg_1_relaxed_impl); - entries.append((address)aarch64_atomic_cmpxchg_4_relaxed_impl); - entries.append((address)aarch64_atomic_cmpxchg_8_relaxed_impl); - entries.append((address)aarch64_atomic_cmpxchg_4_release_impl); - entries.append((address)aarch64_atomic_cmpxchg_8_release_impl); - entries.append((address)aarch64_atomic_cmpxchg_4_seq_cst_impl); - entries.append((address)aarch64_atomic_cmpxchg_8_seq_cst_impl); - - assert(entries.length() == entry_count - 1, - "unexpected extra entry count %d", entries.length()); - - store_archive_data(stub_id, start, end, &entries); - } -#endif // LINUX - static void save_return_registers(MacroAssembler* masm) { if (ValueTypeReturnedAsFields) { masm->push(RegSet::range(r0, r7), sp); @@ -13894,12 +13626,6 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_upcall_stub_exception_handler = generate_upcall_stub_exception_handler(); StubRoutines::_upcall_stub_load_target = generate_upcall_stub_load_target(); -#if defined (LINUX) && !defined (__ARM_FEATURE_ATOMICS) - - generate_atomic_entry_points(); - -#endif // LINUX - #ifdef COMPILER2 if (UseSecondarySupersTable) { StubRoutines::_lookup_secondary_supers_table_slow_path_stub = generate_lookup_secondary_supers_table_slow_path_stub(); @@ -14165,35 +13891,3 @@ void StubGenerator_init_AOTAddressTable(GrowableArray
& addresses) { } #endif // INCLUDE_CDS -#if defined (LINUX) - -// Define pointers to atomic stubs and initialize them to point to the -// code in atomic_aarch64.S. - -#define DEFAULT_ATOMIC_OP(OPNAME, SIZE, RELAXED) \ - extern "C" uint64_t aarch64_atomic_ ## OPNAME ## _ ## SIZE ## RELAXED ## _default_impl \ - (volatile void *ptr, uint64_t arg1, uint64_t arg2); \ - aarch64_atomic_stub_t aarch64_atomic_ ## OPNAME ## _ ## SIZE ## RELAXED ## _impl \ - = aarch64_atomic_ ## OPNAME ## _ ## SIZE ## RELAXED ## _default_impl; - -DEFAULT_ATOMIC_OP(fetch_add, 4, ) -DEFAULT_ATOMIC_OP(fetch_add, 8, ) -DEFAULT_ATOMIC_OP(fetch_add, 4, _relaxed) -DEFAULT_ATOMIC_OP(fetch_add, 8, _relaxed) -DEFAULT_ATOMIC_OP(xchg, 1, ) -DEFAULT_ATOMIC_OP(xchg, 4, ) -DEFAULT_ATOMIC_OP(xchg, 8, ) -DEFAULT_ATOMIC_OP(cmpxchg, 1, ) -DEFAULT_ATOMIC_OP(cmpxchg, 4, ) -DEFAULT_ATOMIC_OP(cmpxchg, 8, ) -DEFAULT_ATOMIC_OP(cmpxchg, 1, _relaxed) -DEFAULT_ATOMIC_OP(cmpxchg, 4, _relaxed) -DEFAULT_ATOMIC_OP(cmpxchg, 8, _relaxed) -DEFAULT_ATOMIC_OP(cmpxchg, 4, _release) -DEFAULT_ATOMIC_OP(cmpxchg, 8, _release) -DEFAULT_ATOMIC_OP(cmpxchg, 4, _seq_cst) -DEFAULT_ATOMIC_OP(cmpxchg, 8, _seq_cst) - -#undef DEFAULT_ATOMIC_OP - -#endif // LINUX diff --git a/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp b/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp index 26d75b94bf2..895356d3d27 100644 --- a/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp @@ -106,6 +106,20 @@ static bool has_neoverse_n1_errata_1542419() { (major_rev_num == 4 && minor_rev_num == 0))); } +static void install_atomic_entry_points() { + if (! UseLSE) { + return; + } + +#if defined (LINUX) && !defined (__ARM_FEATURE_ATOMICS) + ptrdiff_t count = aarch64_atomic_ops_end - aarch64_atomic_ops; + for (ptrdiff_t i = 0; i < count; i++) { + AtomicAccess::store(&aarch64_atomic_ops[i], lse_aarch64_atomic_ops[i]); + } +#endif +} + + void VM_Version::apply_aot_cache_cpu_features() { uint64_t* archived_cpu_features = (uint64_t*)get_aot_cache_cpu_features(); if (archived_cpu_features != nullptr) { @@ -346,6 +360,10 @@ void VM_Version::initialize() { CHECK_CPU_FEATURE(UseLSE, LSE, supports_lse(), "LSE" MULTI_INST_WARNING_MSG); CHECK_CPU_FEATURE(UseAES, AES, supports_aes(), "AES" MULTI_INST_WARNING_MSG); + // Once we know if UseLSE is enabled, immediately install the LSE + // entries. + install_atomic_entry_points(); + if (_cpu == CPU_ARM && model_is_in({ CPU_MODEL_ARM_NEOVERSE_V1, CPU_MODEL_ARM_NEOVERSE_V2, CPU_MODEL_ARM_NEOVERSE_V3, CPU_MODEL_ARM_NEOVERSE_V3AE })) { diff --git a/src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.S b/src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.S index cc8e536ed18..e5578efce46 100644 --- a/src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.S +++ b/src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.S @@ -1,4 +1,5 @@ // Copyright (c) 2021, Red Hat Inc. All rights reserved. +// Copyright (c) 2026, IBM Inc. All rights reserved. // Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. // @@ -22,292 +23,88 @@ #include "defs.S.inc" - .text - - .align 5 -DECLARE_FUNC(aarch64_atomic_fetch_add_8_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - ldaddal x1, x2, [x0] -#else - prfm pstl1strm, [x0] -0: ldaxr x2, [x0] - add x8, x2, x1 - stlxr w9, x8, [x0] - cbnz w9, 0b -#endif - dmb ish - mov x0, x2 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_fetch_add_4_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - ldaddal w1, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldaxr w2, [x0] - add w8, w2, w1 - stlxr w9, w8, [x0] - cbnz w9, 0b -#endif - dmb ish - mov w0, w2 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_fetch_add_8_relaxed_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - ldadd x1, x2, [x0] -#else - prfm pstl1strm, [x0] -0: ldxr x2, [x0] - add x8, x2, x1 - stxr w9, x8, [x0] - cbnz w9, 0b -#endif - mov x0, x2 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_fetch_add_4_relaxed_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - ldadd w1, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldxr w2, [x0] - add w8, w2, w1 - stxr w9, w8, [x0] - cbnz w9, 0b -#endif - mov w0, w2 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_xchg_1_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - swpalb w1, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldaxrb w2, [x0] - stlxrb w8, w1, [x0] - cbnz w8, 0b -#endif - dmb ish - mov w0, w2 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_xchg_4_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - swpal w1, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldaxr w2, [x0] - stlxr w8, w1, [x0] - cbnz w8, 0b -#endif - dmb ish - mov w0, w2 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_xchg_8_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - swpal x1, x2, [x0] -#else - prfm pstl1strm, [x0] -0: ldaxr x2, [x0] - stlxr w8, x1, [x0] - cbnz w8, 0b -#endif - dmb ish - mov x0, x2 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_1_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casalb w3, w2, [x0] -#else - dmb ish - prfm pstl1strm, [x0] -0: ldxrb w3, [x0] - eor w8, w3, w1 - tst x8, #0xff - b.ne 1f - stxrb w8, w2, [x0] - cbnz w8, 0b -#endif -1: dmb ish - mov w0, w3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_4_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casal w3, w2, [x0] -#else - dmb ish - prfm pstl1strm, [x0] -0: ldxr w3, [x0] - cmp w3, w1 - b.ne 1f - stxr w8, w2, [x0] - cbnz w8, 0b -#endif -1: dmb ish - mov w0, w3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_8_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casal x3, x2, [x0] -#else - dmb ish - prfm pstl1strm, [x0] -0: ldxr x3, [x0] - cmp x3, x1 - b.ne 1f - stxr w8, x2, [x0] - cbnz w8, 0b -#endif -1: dmb ish - mov x0, x3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_4_release_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casl w3, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldxr w3, [x0] - cmp w3, w1 - b.ne 1f - stlxr w8, w2, [x0] - cbnz w8, 0b -#endif -1: mov w0, w3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_8_release_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casl x3, x2, [x0] -#else - prfm pstl1strm, [x0] -0: ldxr x3, [x0] - cmp x3, x1 - b.ne 1f - stlxr w8, x2, [x0] - cbnz w8, 0b -#endif -1: mov x0, x3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_4_seq_cst_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casal w3, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldaxr w3, [x0] - cmp w3, w1 - b.ne 1f - stlxr w8, w2, [x0] - cbnz w8, 0b -#endif -1: mov w0, w3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_8_seq_cst_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casal x3, x2, [x0] -#else - prfm pstl1strm, [x0] -0: ldaxr x3, [x0] - cmp x3, x1 - b.ne 1f - stlxr w8, x2, [x0] - cbnz w8, 0b -#endif -1: mov x0, x3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_1_relaxed_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - casb w3, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldxrb w3, [x0] - eor w8, w3, w1 - tst x8, #0xff - b.ne 1f - stxrb w8, w2, [x0] - cbnz w8, 0b -#endif -1: mov w0, w3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_4_relaxed_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - cas w3, w2, [x0] -#else - prfm pstl1strm, [x0] -0: ldxr w3, [x0] - cmp w3, w1 - b.ne 1f - stxr w8, w2, [x0] - cbnz w8, 0b -#endif -1: mov w0, w3 - ret - - .align 5 -DECLARE_FUNC(aarch64_atomic_cmpxchg_8_relaxed_default_impl): - hint #0x22 // bti c -#ifdef __ARM_FEATURE_ATOMICS - mov x3, x1 - cas x3, x2, [x0] -#else - prfm pstl1strm, [x0] -0: ldxr x3, [x0] - cmp x3, x1 - b.ne 1f - stxr w8, x2, [x0] - cbnz w8, 0b -#endif -1: mov x0, x3 - ret +#define DECLARE_LOCAL_FUNC(func) \ + .local func ; \ + .type func, %function ; \ + func + +#define DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER) \ +aarch64_atomic_ ## OPNAME ## _ ## SIZE ## MEMORDER ## _impl + +#define DEFAULT_ATOMIC_OP(OPNAME, SIZE, MEMORDER) \ + .align 3; \ + .globl DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER); \ + .hidden DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER); \ + .type DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER), %object; \ + .size DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER), 8; \ +DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER): \ + .xword aarch64_atomic_ ## OPNAME ## _ ## SIZE ## MEMORDER ## _default_impl; + +#define ATOMIC_OPS_START \ + .data; \ + .align 3; \ + .global aarch64_atomic_ops; \ + .type aarch64_atomic_ops, %object; \ +aarch64_atomic_ops:; + +#define ATOMIC_OPS_END \ + .data; \ + .global aarch64_atomic_ops_end; \ + .type aarch64_atomic_ops_end, %object; \ +aarch64_atomic_ops_end:; + +#include "../../cpu/aarch64/atomic_aarch64.hpp" + +#include "atomic_linux_aarch64.s.inc" + +#ifndef __ARM_FEATURE_ATOMICS + +#define __ARM_FEATURE_ATOMICS + +#undef ATOMIC_OPS_START +#undef ATOMIC_OPS_END + +#define ATOMIC_OPS_START \ + .section ".rodata"; \ + .align 3; \ + .global lse_aarch64_atomic_ops; \ + .type lse_aarch64_atomic_ops, %object; \ +lse_aarch64_atomic_ops:; + +#define ATOMIC_OPS_END \ + .section ".rodata"; \ + .global lse_aarch64_atomic_ops_end; \ + .type lse_aarch64_atomic_ops_end, %object; \ +lse_aarch64_atomic_ops_end:; + +#undef DEFAULT_ATOMIC_OP_NAME +#define DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER) \ +lse_aarch64_atomic_ ## OPNAME ## _ ## SIZE ## MEMORDER ## _impl + +#undef DEFAULT_ATOMIC_OP +#define DEFAULT_ATOMIC_OP(OPNAME, SIZE, MEMORDER) \ + .align 3; \ + .globl DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER); \ + .hidden DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER); \ + .type DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER), %object; \ + .size DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER), 8; \ +DEFAULT_ATOMIC_OP_NAME(OPNAME, SIZE, MEMORDER): \ + .xword lse_aarch64_atomic_ ## OPNAME ## _ ## SIZE ## MEMORDER ## _default_impl; + +#undef DECLARE_LOCAL_FUNC +#define DECLARE_LOCAL_FUNC(func) \ + .local lse_ ## func ; \ + .type lse_ ## func, %function ; \ + lse_ ##func + + .arch armv8.1-a + +#undef CPU_AARCH64_ATOMIC_AARCH64_HPP +#include "../../cpu/aarch64/atomic_aarch64.hpp" + +#include "atomic_linux_aarch64.s.inc" + +#endif // __ARM_FEATURE_ATOMICS /* Emit .note.gnu.property section in case of PAC or BTI being enabled. * For more details see "ELF for the Arm(R) 64-bit Architecture (AArch64)". diff --git a/src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.s.inc b/src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.s.inc new file mode 100644 index 00000000000..497d966952d --- /dev/null +++ b/src/hotspot/os_cpu/linux_aarch64/atomic_linux_aarch64.s.inc @@ -0,0 +1,217 @@ +// Copyright (c) 2021, Red Hat Inc. All rights reserved. +// Copyright (c) 2026, IBM Inc. All rights reserved. +// Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. +// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +// +// This code is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License version 2 only, as +// published by the Free Software Foundation. +// +// This code is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// version 2 for more details (a copy is included in the LICENSE file that +// accompanied this code). +// +// You should have received a copy of the GNU General Public License version +// 2 along with this work; if not, write to the Free Software Foundation, +// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +// +// Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +// or visit www.oracle.com if you need additional information or have any +// questions. + +// LSE and non-LSE versions of the atomic routines used by +// AtomicAccess::PlatformXX. +// This file contains source for both. Define __ARM_FEATURE_ATOMICS if +// you want to generate LSE versions. +// "LSE" here refers to FEAT_LSE, Large System Extensions, which are +// optional for Armv8.0 and mandatory for Armv8.1 onwards. + +// +// +// NB: For memory_order_conservative we need a trailing membar after +// LSE atomic operations but not a leading membar. +// +// We don't need a leading membar because a clause in the Arm ARM +// says: +// +// Barrier-ordered-before +// +// Barrier instructions order prior Memory effects before subsequent +// Memory effects generated by the same Observer. A read or a write +// RW1 is Barrier-ordered-before a read or a write RW 2 from the same +// Observer if and only if RW1 appears in program order before RW 2 +// and [ ... ] at least one of RW 1 and RW 2 is generated by an atomic +// instruction with both Acquire and Release semantics. +// +// All the atomic instructions {ldaddal, swapal, casal} have Acquire +// and Release semantics, therefore we don't need a leading +// barrier. However, there is no corresponding Barrier-ordered-after +// relationship, therefore we need a trailing membar to prevent a +// later store or load from being reordered with the store in an +// atomic instruction. +// +// This was checked by using the herd7 consistency model simulator +// (http://diy.inria.fr/) with this test case: +// +// AArch64 LseCas +// { 0:X1=x; 0:X2=y; 1:X1=x; 1:X2=y; } +// P0 | P1; +// LDR W4, [X2] | MOV W3, #0; +// DMB LD | MOV W4, #1; +// LDR W3, [X1] | CASAL W3, W4, [X1]; +// | DMB ISH; +// | STR W4, [X2]; +// exists +// (0:X3=0 /\ 0:X4=1) +// +// If X3 == 0 && X4 == 1, the store to y in P1 has been reordered +// with the store to x in P1. Without the DMB in P1 this may happen. + +#include "defs.S.inc" + + .text + +#undef ATOMIC_OP + +#ifdef __ARM_FEATURE_ATOMICS +#define ATOMIC_OP(LOAD, OP, STORE, SZ, MEMBAR, LSEOP) \ + hint #0x22 /* bti c */ ;\ + LSEOP SZ ## 1, SZ ## 2, [x0] ;\ + MEMBAR ;\ + mov SZ ## 0, SZ ## 2 ;\ + ret +#else +#define ATOMIC_OP(LOAD, OP, STORE, SZ, MEMBAR, LSEOP) \ + hint #0x22 /* bti c */ ;\ + prfm pstl1strm, [x0] ;\ +0: LOAD SZ ## 2, [x0] ;\ + OP SZ ## 8, SZ ## 2, SZ ## 1 ;\ + STORE w9, SZ ## 8, [x0] ;\ + cbnz w9, 0b ;\ + MEMBAR ;\ + mov SZ ## 0, SZ ## 2 ;\ + ret +#endif + +#define DMB ;\ + dmb ish ; + + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_fetch_add_8_default_impl): + ATOMIC_OP(ldaxr, add, stlxr, x, DMB, ldaddal) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_fetch_add_4_default_impl): + ATOMIC_OP(ldaxr, add, stlxr, w, DMB, ldaddal) + + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_fetch_add_8_relaxed_default_impl): + ATOMIC_OP(ldxr, add, stxr, x, , ldadd) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_fetch_add_4_relaxed_default_impl): + ATOMIC_OP(ldxr, add, stxr, w, , ldadd) + + +#undef ATOMIC_OP + +#ifdef __ARM_FEATURE_ATOMICS +#define ATOMIC_OP(LOAD, STORE, SZ, LSEOP) \ + hint #0x22 /* bti c */ ;\ + LSEOP SZ ## 1, SZ ## 2, [x0] ;\ + dmb ish ;\ + mov SZ ## 0, SZ ## 2 ;\ + ret +#else +#define ATOMIC_OP(LOAD, STORE, SZ, LSEOP) \ + hint #0x22 /* bti c */ ;\ + prfm pstl1strm, [x0] ;\ +0: LOAD SZ ## 2, [x0] ;\ + STORE w8, SZ ## 1, [x0] ;\ + cbnz w8, 0b ;\ + dmb ish ;\ + mov SZ ## 0, SZ ## 2 ;\ + ret +#endif + + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_xchg_1_default_impl): + ATOMIC_OP(ldaxrb, stlxrb, w, swpalb) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_xchg_4_default_impl): + ATOMIC_OP(ldaxr, stlxr, w, swpal) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_xchg_8_default_impl): + ATOMIC_OP(ldaxr, stlxr, x, swpal) + +#undef ATOMIC_OP +#ifdef __ARM_FEATURE_ATOMICS +#define ATOMIC_OP(LOAD, STORE, SZ, CMP, MEMBAR, LSEOP) \ + hint #0x22 /* bti c */ ;\ + mov SZ ## 3, SZ ## 1 ;\ + LSEOP SZ ## 3, SZ ## 2, [x0] ;\ + MEMBAR ;\ + mov SZ ## 0, SZ ## 3 ;\ + ret +#else +#define ATOMIC_OP(LOAD, STORE, SZ, CMP, MEMBAR, LSEOP) \ + hint #0x22 /* bti c */ ;\ + MEMBAR ;\ + prfm pstl1strm, [x0] ;\ +0: LOAD SZ ## 3, [x0] ;\ + CMP ;\ + STORE w8, SZ ## 2, [x0] ;\ + cbnz w8, 0b ;\ +1: MEMBAR ;\ + mov SZ ## 0, SZ ## 3 ;\ + ret +#endif + +#define CMPB \ + eor w8, w3, w1 ;\ + tst x8, #0xff ;\ + b.ne 1f ; +#define CMPW ;\ + cmp w3, w1 ;\ + b.ne 1f ; +#define CMPX ;\ + cmp x3, x1 ;\ + b.ne 1f + + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_1_default_impl): + ATOMIC_OP(ldxrb, stxrb, w, CMPB, DMB, casalb) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_4_default_impl): + ATOMIC_OP(ldxr, stxr, w, CMPW, DMB, casal) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_8_default_impl): + ATOMIC_OP(ldxr, stxr, x, CMPX, DMB, casal) + + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_4_release_default_impl): + ATOMIC_OP(ldxr, stlxr, w, CMPW, , casl) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_8_release_default_impl): + ATOMIC_OP(ldxr, stlxr, x, CMPX, , casl) + + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_4_seq_cst_default_impl): + ATOMIC_OP(ldaxr, stlxr, w, CMPW, , casal) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_8_seq_cst_default_impl): + ATOMIC_OP(ldaxr, stlxr, x, CMPX, , casal) + + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_1_relaxed_default_impl): + ATOMIC_OP(ldxrb, stxrb, w, CMPB, , casb) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_4_relaxed_default_impl): + ATOMIC_OP(ldxr, stxr, w, CMPW, , cas) + .align 5 +DECLARE_LOCAL_FUNC(aarch64_atomic_cmpxchg_8_relaxed_default_impl): + ATOMIC_OP(ldxr, stxr, x, CMPX, , cas) + +// ;; Local Variables: +// ;; mode: asm +// ;; End: From 7617939fec1d1fcdb322ee651b2848cea9432d1f Mon Sep 17 00:00:00 2001 From: Derek White Date: Mon, 23 Nov 2026 15:30:21 +0000 Subject: [PATCH 44/95] 8397011: x86: Optimize simple uses of LEA to MOV instructions Reviewed-by: sviswanathan, sparasa, jbhateja, qamai --- src/hotspot/cpu/x86/assembler_x86.cpp | 4 ---- src/hotspot/cpu/x86/assembler_x86.hpp | 2 -- src/hotspot/cpu/x86/macroAssembler_x86.cpp | 20 ++++++++++++++++++++ src/hotspot/cpu/x86/macroAssembler_x86.hpp | 5 +++-- 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/hotspot/cpu/x86/assembler_x86.cpp b/src/hotspot/cpu/x86/assembler_x86.cpp index f4ca57c6d36..91e20c98579 100644 --- a/src/hotspot/cpu/x86/assembler_x86.cpp +++ b/src/hotspot/cpu/x86/assembler_x86.cpp @@ -15645,10 +15645,6 @@ void Assembler::eincq(Register dst, Address src, bool no_flags) { emit_operand(rax, src, 0); } -void Assembler::lea(Register dst, Address src) { - leaq(dst, src); -} - void Assembler::leaq(Register dst, Address src) { InstructionMark im(this); emit_prefix_and_int8(get_prefixq(src, dst), (unsigned char)0x8D); diff --git a/src/hotspot/cpu/x86/assembler_x86.hpp b/src/hotspot/cpu/x86/assembler_x86.hpp index 4b6f2a3eaf5..e1fc2cdaa82 100644 --- a/src/hotspot/cpu/x86/assembler_x86.hpp +++ b/src/hotspot/cpu/x86/assembler_x86.hpp @@ -1017,8 +1017,6 @@ class Assembler : public AbstractAssembler { void init_attributes(void); void clear_attributes(void) { _attributes = nullptr; } - void lea(Register dst, Address src); - void mov(Register dst, Register src); // support caching the result of some routines diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.cpp b/src/hotspot/cpu/x86/macroAssembler_x86.cpp index 2755a705870..88793061928 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp @@ -267,6 +267,26 @@ void MacroAssembler::lea(Address dst, AddressLiteral adr, Register rscratch) { movptr(dst, rscratch); } +void MacroAssembler::leal(Register dst, Address src) { + if ((src.base() != noreg) && (src.index() == noreg) && + (src.disp() == 0) && (src.reloc() == relocInfo::none)) { + // base-only lea, use move (other simple cases not seen). + movl(dst, src.base()); + } else { + Assembler::leal(dst, src); + } +} + +void MacroAssembler::leaq(Register dst, Address src) { + if ((src.base() != noreg) && (src.index() == noreg) && + (src.disp() == 0) && (src.reloc() == relocInfo::none)) { + // base-only lea, use move (other simple cases not seen). + movq(dst, src.base()); + } else { + Assembler::leaq(dst, src); + } +} + void MacroAssembler::leave() { // %%% is this really better? Why not on 32bit too? emit_int8((unsigned char)0xC9); // LEAVE diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.hpp b/src/hotspot/cpu/x86/macroAssembler_x86.hpp index 50c0bee3a8b..4c3a1431e6f 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.hpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.hpp @@ -889,10 +889,11 @@ class MacroAssembler: public Assembler { void atomic_incptr(Address counter_addr) { atomic_incq(counter_addr); } using Assembler::lea; + void lea(Register dst, Address src) { leaq(dst, src); } void lea(Register dst, AddressLiteral adr); void lea(Address dst, AddressLiteral adr, Register rscratch); - - void leal32(Register dst, Address src) { leal(dst, src); } + void leaq(Register dst, Address src); + void leal(Register dst, Address src); // Import other testl() methods from the parent class or else // they will be hidden by the following overriding declaration. From c35f74179474524a5fa013f6f425691fea3e0cf6 Mon Sep 17 00:00:00 2001 From: Lawrence Andrews Date: Mon, 23 Nov 2026 16:00:40 +0000 Subject: [PATCH 45/95] 8398008: ProblemList java/awt/dnd/DragOverDropTargetPerformanceTest.java due to the JDK-8398009 for MacOS 27 Reviewed-by: kizune, prr --- test/jdk/ProblemList.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index 3f29d253a11..4efaeb4e52f 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -128,6 +128,7 @@ java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java 8171510 macosx-a java/awt/dnd/MissingDragExitEventTest/MissingDragExitEventTest.java 8288839 windows-x64,macosx-all java/awt/dnd/DragExitBeforeDropTest.java 8242805 macosx-all java/awt/dnd/DragThresholdTest.java 8076299 macosx-all +java/awt/dnd/DragOverDropTargetPerformanceTest.java 8398009 macosx-aarch64 java/awt/dnd/CustomDragCursorTest.java 8242805 macosx-all java/awt/dnd/Button2DragTest/Button2DragTest.java 8393735 macosx-aarch64 java/awt/Focus/ClearLwQueueBreakTest/ClearLwQueueBreakTest.java 8198618 macosx-all From 65d809fee3a8631cd3b75683ce32a00ce506a605 Mon Sep 17 00:00:00 2001 From: Justin Lu Date: Mon, 23 Nov 2026 17:27:32 +0000 Subject: [PATCH 46/95] 8397717: Explicitly define and clarify general number formatting for CompactNumberFormat Reviewed-by: naoto --- .../java/text/CompactNumberFormat.java | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/java.base/share/classes/java/text/CompactNumberFormat.java b/src/java.base/share/classes/java/text/CompactNumberFormat.java index b29a92f9843..bf5f63709c0 100644 --- a/src/java.base/share/classes/java/text/CompactNumberFormat.java +++ b/src/java.base/share/classes/java/text/CompactNumberFormat.java @@ -97,17 +97,26 @@ * } * *

Formatting

- * Formatting that uses the special pattern "0", either explicitly or when the empty string compact pattern + * + * {@code CompactNumberFormat} utilizes both compact number formatting and general number formatting. For example, + * using the following patterns {@code {"", "", "", "0K", ...}} with the {@link Locale#US US locale} and a + * minimum of 1 fractional digit, {@code 55.5} is formatted as "56" through general number formatting, and + * {@code 5500} is formatted as "5.5K" through compact number formatting. + * + *

General Number Formatting

+ * Formatting that uses the special compact pattern "0", either explicitly or when the empty string compact pattern * falls back to it, is referred to as general number formatting. This uses the formatting provided by {@link - * DecimalFormat}. Such formatting never produces fractional digits, even if the underlying decimal pattern - * has been composed to use fractional digits. Only formatting that does not use the special pattern can produce - * output with fractional digits. However, the default compact pattern behavior supports no fractional - * digits. This is why the patterns provided for formatting contain only the minimum - * integer digits, prefix and/or suffix, but no fractional part. If needed, users can use - * {@link #setMinimumFractionDigits(int)} to support fractional digits for compact number formatting. - * For example, using the following patterns {@code {"", "", "", "0K", ...}} with the {@link - * Locale#US US locale} and a minimum of 1 fractional digit, {@code 55.5} is formatted as - * "56", and {@code 5500} is formatted as "5.5K". + * DecimalFormat} with the {@code decimalPattern} provided to the {@code CompactNumberFormat}. Such formatting + * never produces fractional digits, even if the underlying decimal pattern has been composed to use fractional digits. + * Changes to the {@code CompactNumberFormat}, such as calling {@link #setGroupingUsed(boolean) + * setGroupingUsed(true)}, will not change the behavior for general number formatting. + * + *

Compact Number Formatting

+ * The default compact number formatting behavior does not produce fractional digits. + * This is why the compact patterns are expected to contain only the minimum + * integer digits, prefix and/or suffix, but no fractional part, such as {@code "00M"}. + * However, users can use {@link #setMinimumFractionDigits(int)} to support fractional digits + * for compact number formatting if needed. * *

Rounding

* {@code CompactNumberFormat} provides rounding modes defined in From 563431b2f69b384a6fdd692c8eeea13255a10a23 Mon Sep 17 00:00:00 2001 From: Srinivas Vamsi Parasa Date: Mon, 23 Nov 2026 18:16:14 +0000 Subject: [PATCH 47/95] 8397858: Clean up APX NDD instruction rules for x86_64 Reviewed-by: sviswanathan, qamai, drwhite --- src/hotspot/cpu/x86/x86.ad | 33 +++------------------------------ 1 file changed, 3 insertions(+), 30 deletions(-) diff --git a/src/hotspot/cpu/x86/x86.ad b/src/hotspot/cpu/x86/x86.ad index 899cda62514..b9e65b942f5 100644 --- a/src/hotspot/cpu/x86/x86.ad +++ b/src/hotspot/cpu/x86/x86.ad @@ -13040,19 +13040,6 @@ instruct orI_rReg_rReg_imm_ndd(rRegI dst, rRegI src1, immI src2, rFlagsReg cr) ins_pipe(ialu_reg); %} -instruct orI_rReg_imm_rReg_ndd(rRegI dst, immI src1, rRegI src2, rFlagsReg cr) -%{ - predicate(UseAPX); - match(Set dst (OrI src1 src2)); - effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); - - format %{ "eorl $dst, $src2, $src1\t# int ndd" %} - ins_encode %{ - __ eorl($dst$$Register, $src2$$Register, $src1$$constant, false); - %} - ins_pipe(ialu_reg); -%} // Or Register with Memory instruct orI_rReg_mem(rRegI dst, memory src, rFlagsReg cr) @@ -13586,7 +13573,7 @@ instruct orL_rReg_castP2X_ndd(rRegL dst, rRegL src1, any_RegP src2, rFlagsReg cr predicate(UseAPX); match(Set dst (OrL src1 (CastP2X src2))); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "eorq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -13624,20 +13611,6 @@ instruct orL_rReg_rReg_imm_ndd(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr) ins_pipe(ialu_reg); %} -instruct orL_rReg_imm_rReg_ndd(rRegL dst, immL32 src1, rRegL src2, rFlagsReg cr) -%{ - predicate(UseAPX); - match(Set dst (OrL src1 src2)); - effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); - - format %{ "eorq $dst, $src2, $src1\t# long ndd" %} - ins_encode %{ - __ eorq($dst$$Register, $src2$$Register, $src1$$constant, false); - %} - ins_pipe(ialu_reg); -%} - // Or Register with Memory instruct orL_rReg_mem(rRegL dst, memory src, rFlagsReg cr) %{ @@ -13744,7 +13717,7 @@ instruct xorL_rReg_im1(rRegL dst, immL_M1 imm) ins_pipe(ialu_reg); %} -instruct xorL_rReg_im1_ndd(rRegL dst,rRegL src, immL_M1 imm) +instruct xorL_rReg_im1_ndd(rRegL dst, rRegL src, immL_M1 imm) %{ predicate(UseAPX); match(Set dst (XorL src imm)); @@ -13773,7 +13746,7 @@ instruct xorL_rReg_imm(rRegL dst, immL32 src, rFlagsReg cr) ins_pipe(ialu_reg); %} -instruct xorL_rReg_rReg_imm(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr) +instruct xorL_rReg_rReg_imm_ndd(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr) %{ // Strict predicate check to make selection of xorL_rReg_im1_ndd cost agnostic if immL32 src2 is -1. predicate(UseAPX && n->in(2)->bottom_type()->as_long()->get_con() != -1L); From 2db927a97f0d6052ef1d78146fc452ff22f841c3 Mon Sep 17 00:00:00 2001 From: Alexander Zvegintsev Date: Mon, 23 Nov 2026 18:37:35 +0000 Subject: [PATCH 48/95] 8395861: Update PipeWire to 1.6.11 Reviewed-by: prr, kizune --- src/java.desktop/unix/legal/pipewire.md | 27 +- .../libpipewire/include/pipewire/context.h | 9 +- .../libpipewire/include/pipewire/core.h | 8 +- .../libpipewire/include/pipewire/keys.h | 16 +- .../libpipewire/include/pipewire/loop.h | 44 +- .../libpipewire/include/pipewire/port.h | 8 +- .../libpipewire/include/pipewire/properties.h | 8 +- .../libpipewire/include/pipewire/protocol.h | 4 +- .../libpipewire/include/pipewire/proxy.h | 4 +- .../libpipewire/include/pipewire/stream.h | 50 +- .../libpipewire/include/pipewire/type.h | 4 +- .../libpipewire/include/pipewire/utils.h | 17 +- .../libpipewire/include/spa/buffer/buffer.h | 17 +- .../libpipewire/include/spa/buffer/meta.h | 20 +- .../include/spa/buffer/type-info.h | 8 +- .../libpipewire/include/spa/control/control.h | 6 +- .../include/spa/control/type-info.h | 8 +- .../libpipewire/include/spa/debug/types.h | 8 +- .../libpipewire/include/spa/monitor/event.h | 4 +- .../include/spa/monitor/type-info.h | 8 +- .../libpipewire/include/spa/node/command.h | 16 +- .../libpipewire/include/spa/node/event.h | 10 +- .../native/libpipewire/include/spa/node/io.h | 68 +- .../libpipewire/include/spa/node/type-info.h | 24 +- .../include/spa/param/audio/aac-types.h | 6 +- .../libpipewire/include/spa/param/audio/aac.h | 18 +- .../include/spa/param/audio/amr-types.h | 6 +- .../libpipewire/include/spa/param/audio/amr.h | 4 +- .../include/spa/param/audio/dts-types.h | 39 + .../libpipewire/include/spa/param/audio/dts.h | 51 ++ .../include/spa/param/audio/iec958-types.h | 6 +- .../include/spa/param/audio/iec958.h | 2 +- .../include/spa/param/audio/layout-types.h | 118 +++ .../include/spa/param/audio/layout.h | 174 +++++ .../include/spa/param/audio/mp3-types.h | 6 +- .../libpipewire/include/spa/param/audio/mp3.h | 19 +- .../include/spa/param/audio/raw-types.h | 45 +- .../libpipewire/include/spa/param/audio/raw.h | 100 +-- .../include/spa/param/audio/type-info.h | 2 + .../include/spa/param/audio/wma-types.h | 6 +- .../libpipewire/include/spa/param/audio/wma.h | 4 +- .../include/spa/param/bluetooth/audio.h | 1 + .../include/spa/param/bluetooth/type-info.h | 5 +- .../include/spa/param/buffers-types.h | 10 +- .../libpipewire/include/spa/param/buffers.h | 5 +- .../include/spa/param/dict-types.h | 38 + .../libpipewire/include/spa/param/dict.h | 42 ++ .../include/spa/param/format-types.h | 45 +- .../include/spa/param/format-utils.h | 6 +- .../libpipewire/include/spa/param/format.h | 17 +- .../include/spa/param/latency-types.h | 8 +- .../libpipewire/include/spa/param/latency.h | 8 +- .../include/spa/param/param-types.h | 11 +- .../libpipewire/include/spa/param/param.h | 9 +- .../include/spa/param/peer-types.h | 38 + .../libpipewire/include/spa/param/peer.h | 37 + .../include/spa/param/port-config-types.h | 8 +- .../include/spa/param/port-config.h | 4 +- .../include/spa/param/profile-types.h | 8 +- .../libpipewire/include/spa/param/profile.h | 4 +- .../include/spa/param/profiler-types.h | 6 +- .../libpipewire/include/spa/param/profiler.h | 7 +- .../include/spa/param/props-types.h | 19 +- .../libpipewire/include/spa/param/props.h | 7 +- .../include/spa/param/route-types.h | 10 +- .../libpipewire/include/spa/param/route.h | 4 +- .../libpipewire/include/spa/param/tag-types.h | 8 +- .../libpipewire/include/spa/param/tag.h | 4 +- .../libpipewire/include/spa/param/type-info.h | 2 + .../include/spa/param/video/color-types.h | 79 ++ .../include/spa/param/video/color.h | 24 +- .../include/spa/param/video/dsp-utils.h | 9 +- .../include/spa/param/video/format-utils.h | 9 +- .../include/spa/param/video/format.h | 10 +- .../include/spa/param/video/h264-utils.h | 8 +- .../include/spa/param/video/h264.h | 4 +- .../include/spa/param/video/h265-utils.h | 79 ++ .../include/spa/param/video/h265.h | 49 ++ .../include/spa/param/video/mjpg-utils.h | 8 +- .../include/spa/param/video/mjpg.h | 4 +- .../include/spa/param/video/raw-types.h | 5 +- .../include/spa/param/video/raw-utils.h | 59 +- .../libpipewire/include/spa/param/video/raw.h | 10 +- .../include/spa/param/video/type-info.h | 1 + .../native/libpipewire/include/spa/pod/body.h | 465 ++++++++++++ .../libpipewire/include/spa/pod/builder.h | 178 +++-- .../libpipewire/include/spa/pod/command.h | 6 +- .../libpipewire/include/spa/pod/event.h | 4 +- .../native/libpipewire/include/spa/pod/iter.h | 281 ++------ .../libpipewire/include/spa/pod/parser.h | 681 +++++++++++++----- .../native/libpipewire/include/spa/pod/pod.h | 36 +- .../libpipewire/include/spa/pod/vararg.h | 21 +- .../libpipewire/include/spa/support/loop.h | 157 +++- .../libpipewire/include/spa/support/system.h | 12 +- .../libpipewire/include/spa/utils/atomic.h | 37 + .../libpipewire/include/spa/utils/cleanup.h | 8 +- .../libpipewire/include/spa/utils/defs.h | 23 +- .../libpipewire/include/spa/utils/dict.h | 8 +- .../include/spa/utils/enum-types.h | 6 +- .../libpipewire/include/spa/utils/hook.h | 6 +- .../libpipewire/include/spa/utils/list.h | 4 +- .../libpipewire/include/spa/utils/string.h | 9 +- .../libpipewire/include/spa/utils/type-info.h | 23 +- .../libpipewire/include/spa/utils/type.h | 8 +- 104 files changed, 2865 insertions(+), 839 deletions(-) create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts-types.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout-types.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/dict-types.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/dict.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/peer-types.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/peer.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/video/color-types.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265-utils.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/pod/body.h create mode 100644 src/java.desktop/unix/native/libpipewire/include/spa/utils/atomic.h diff --git a/src/java.desktop/unix/legal/pipewire.md b/src/java.desktop/unix/legal/pipewire.md index 8275928e271..9860fb85618 100644 --- a/src/java.desktop/unix/legal/pipewire.md +++ b/src/java.desktop/unix/legal/pipewire.md @@ -1,4 +1,4 @@ -## PipeWire 1.3.81 +## PipeWire 1.6.11 ### PipeWire license: @@ -6,7 +6,7 @@ All PipeWire header files are licensed under the MIT License:
-Copyright © 2018-2023 Wim Taymans
+Copyright © 2018-2025 Wim Taymans
 
 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
@@ -30,17 +30,30 @@ DEALINGS IN THE SOFTWARE.
 
 The below copyright applies to the following files:
 
-spa/include/spa/monitor/type-info.h
+spa/monitor/type-info.h
 ```
 Copyright © 2021 Collabora Ltd.
 ```
 
-spa/include/spa/utils/string.h
+spa/param/audio/dts-types.h
+spa/param/audio/dts.h
 ```
-Copyright © 2021 Red Hat, Inc.
+Copyright © 2025 Carlos Rafael Giani
+```
+
+spa/param/video/color-types.h
+spa/utils/cleanup.h
+```
+Copyright © 2023-2025 PipeWire authors
 ```
 
-spa/utils/cleanup.h:
+spa/param/video/h265-utils.h
+spa/param/video/h265.h
 ```
-Copyright © 2023 PipeWire authors
+Copyright © 2025 Arun Raghavan
+```
+
+spa/utils/string.h
+```
+Copyright © 2021 Red Hat, Inc.
 ```
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/context.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/context.h
index 7e1a2b29b94..b5790ef5122 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/context.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/context.h
@@ -5,13 +5,13 @@
 #ifndef PIPEWIRE_CONTEXT_H
 #define PIPEWIRE_CONTEXT_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /** \defgroup pw_context Context
  *
  * \brief The PipeWire context object manages all locally available
@@ -144,6 +144,9 @@ void pw_context_release_loop(struct pw_context *context, struct pw_loop *loop);
 /** Get the work queue from the context: Since 0.3.26 */
 struct pw_work_queue *pw_context_get_work_queue(struct pw_context *context);
 
+/** Get the timer queue from the context: Since 1.6.0 */
+struct pw_timer_queue *pw_context_get_timer_queue(struct pw_context *context);
+
 /** Get the memory pool from the context: Since 0.3.74 */
 struct pw_mempool *pw_context_get_mempool(struct pw_context *context);
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/core.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/core.h
index 1acfded4b07..1550c6aa79c 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/core.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/core.h
@@ -5,10 +5,6 @@
 #ifndef PIPEWIRE_CORE_H
 #define PIPEWIRE_CORE_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 #include 
 
@@ -16,6 +12,10 @@ extern "C" {
 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /** \defgroup pw_core Core
  *
  * \brief The core global object.
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/keys.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/keys.h
index 67ea3f9cce2..d1983ad6f31 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/keys.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/keys.h
@@ -5,11 +5,12 @@
 #ifndef PIPEWIRE_KEYS_H
 #define PIPEWIRE_KEYS_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
 /**
  * \defgroup pw_keys Key Names
  *
@@ -104,9 +105,11 @@ extern "C" {
                                   *  default pipewire-0, overwritten by
                                   *  env(PIPEWIRE_REMOTE). May also be
                                   *  a SPA-JSON array of sockets, to be tried
-                                  *  in order. */
+                                  *  in order. The "internal" remote name and
+                                  *  "generic" intention connects to the local
+                                  *  PipeWire instance. */
 #define PW_KEY_REMOTE_INTENTION        "remote.intention"    /**< The intention of the remote connection,
-                                  *  "generic", "screencast" */
+                                  *  "generic", "screencast", "manager" */
 
 /** application keys */
 #define PW_KEY_APP_NAME            "application.name"    /**< application name. Ex: "Totem Music Player" */
@@ -226,6 +229,11 @@ extern "C" {
                                       *  playback or disable the prefix
                                       *  completely if an empty string
                                       *  is provided */
+#define PW_KEY_NODE_PHYSICAL        "node.physical"        /**< ports from the node are physical */
+#define PW_KEY_NODE_TERMINAL        "node.terminal"        /**< ports from the node are terminal */
+
+#define PW_KEY_NODE_RELIABLE        "node.reliable"        /**< node uses reliable transport 1.6.0 */
+
 /** Port keys */
 #define PW_KEY_PORT_ID            "port.id"        /**< port id */
 #define PW_KEY_PORT_NAME        "port.name"        /**< port name */
@@ -242,6 +250,8 @@ extern "C" {
 #define PW_KEY_PORT_PASSIVE        "port.passive"        /**< the ports wants passive links, since 0.3.67 */
 #define PW_KEY_PORT_IGNORE_LATENCY    "port.ignore-latency"    /**< latency ignored by peers, since 0.3.71 */
 #define PW_KEY_PORT_GROUP        "port.group"        /**< the port group of the port 1.2.0 */
+#define PW_KEY_PORT_EXCLUSIVE        "port.exclusive"    /**< link port only once 1.6.0 */
+#define PW_KEY_PORT_RELIABLE        "port.reliable"        /**< port uses reliable transport 1.6.0 */
 
 /** link properties */
 #define PW_KEY_LINK_ID            "link.id"        /**< a link id */
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/loop.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/loop.h
index 94b2dc2780b..b5243b189f5 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/loop.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/loop.h
@@ -5,13 +5,13 @@
 #ifndef PIPEWIRE_LOOP_H
 #define PIPEWIRE_LOOP_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /** \defgroup pw_loop Loop
  *
  * PipeWire loop object provides an implementation of
@@ -64,6 +64,12 @@ PW_API_LOOP_IMPL int pw_loop_invoke(struct pw_loop *object,
 {
     return spa_loop_invoke(object->loop, func, seq, data, size, block, user_data);
 }
+PW_API_LOOP_IMPL int pw_loop_locked(struct pw_loop *object,
+                spa_invoke_func_t func, uint32_t seq, const void *data,
+                size_t size, void *user_data)
+{
+    return spa_loop_locked(object->loop, func, seq, data, size, user_data);
+}
 
 PW_API_LOOP_IMPL int pw_loop_get_fd(struct pw_loop *object)
 {
@@ -88,6 +94,36 @@ PW_API_LOOP_IMPL int pw_loop_iterate(struct pw_loop *object,
 {
     return spa_loop_control_iterate_fast(object->control, timeout);
 }
+PW_API_LOOP_IMPL int pw_loop_check(struct pw_loop *object)
+{
+    return spa_loop_control_check(object->control);
+}
+PW_API_LOOP_IMPL int pw_loop_lock(struct pw_loop *object)
+{
+    return spa_loop_control_lock(object->control);
+}
+PW_API_LOOP_IMPL int pw_loop_unlock(struct pw_loop *object)
+{
+    return spa_loop_control_unlock(object->control);
+}
+PW_API_LOOP_IMPL int pw_loop_get_time(struct pw_loop *object, struct timespec *abstime, int64_t timeout)
+{
+    return spa_loop_control_get_time(object->control, abstime, timeout);
+}
+PW_API_LOOP_IMPL int pw_loop_wait(struct pw_loop *object, const struct timespec *abstime)
+{
+    return spa_loop_control_wait(object->control, abstime);
+}
+PW_API_LOOP_IMPL int pw_loop_signal(struct pw_loop *object, bool wait_for_accept)
+{
+    return spa_loop_control_signal(object->control, wait_for_accept);
+}
+PW_API_LOOP_IMPL int pw_loop_accept(struct pw_loop *object)
+{
+    return spa_loop_control_accept(object->control);
+}
+
+
 
 PW_API_LOOP_IMPL struct spa_source *
 pw_loop_add_io(struct pw_loop *object, int fd, uint32_t mask,
@@ -141,7 +177,7 @@ pw_loop_add_signal(struct pw_loop *object, int signal_number,
 PW_API_LOOP_IMPL void pw_loop_destroy_source(struct pw_loop *object,
                 struct spa_source *source)
 {
-    return spa_loop_utils_destroy_source(object->utils, source);
+    spa_loop_utils_destroy_source(object->utils, source);
 }
 
 /**
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/port.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/port.h
index ef48c67c004..75b067412fa 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/port.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/port.h
@@ -5,10 +5,6 @@
 #ifndef PIPEWIRE_PORT_H
 #define PIPEWIRE_PORT_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 #include 
 
@@ -18,6 +14,10 @@ extern "C" {
 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /** \defgroup pw_port Port
  * Port interface
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/properties.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/properties.h
index de67f33a501..0268f1871f3 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/properties.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/properties.h
@@ -5,16 +5,16 @@
 #ifndef PIPEWIRE_PROPERTIES_H
 #define PIPEWIRE_PROPERTIES_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 
 #include 
 #include 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #ifndef PW_API_PROPERTIES
 #define PW_API_PROPERTIES static inline
 #endif
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/protocol.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/protocol.h
index f306979877a..cf945b7ec2e 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/protocol.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/protocol.h
@@ -5,12 +5,12 @@
 #ifndef PIPEWIRE_PROTOCOL_H
 #define PIPEWIRE_PROTOCOL_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /** \defgroup pw_protocol Protocol
  *
  * \brief Manages protocols and their implementation
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/proxy.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/proxy.h
index ca7f324c285..9013f0594ea 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/proxy.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/proxy.h
@@ -5,12 +5,12 @@
 #ifndef PIPEWIRE_PROXY_H
 #define PIPEWIRE_PROXY_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /** \page page_proxy Proxy
  *
  * \see \ref pw_proxy
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/stream.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/stream.h
index dca13d22669..982b1084560 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/stream.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/stream.h
@@ -167,6 +167,12 @@ extern "C" {
  * Buffers that are queued after the process event completes will be delayed
  * to the next processing cycle.
  *
+ * \section sec_stream_timing Obtaining timing information
+ *
+ * With \ref pw_stream_get_time_n() and pw_stream_get_nsec() on can get accurate
+ * timing information of the data and the graph in the \ref pw_time. See
+ * the documentation of these functions.
+ *
  * \section sec_stream_driving Driving the graph
  *
  * Starting in 0.3.34, it is possible for a stream to drive the graph.
@@ -263,11 +269,11 @@ struct pw_buffer {
                       *  suggested amount of data to provide. For audio
                       *  streams this will be the amount of frames
                       *  required by the resampler. This field is 0
-                      *  when no suggestion is provided. Since 0.3.49 */
+                      *  when no suggestion is provided. Since 0.3.50 */
     uint64_t time;            /**< For capture streams, this field contains the
                       *  cycle time in nanoseconds when this buffer was
                       *  queued in the stream. It can be compared against
-                      *  the pw_time values or pw_stream_get_nsec()
+                      *  the \ref pw_time values or pw_stream_get_nsec()
                       *  Since 1.0.5 */
 };
 
@@ -287,10 +293,11 @@ struct pw_stream_control {
  * Use pw_stream_get_time_n() to get an updated time snapshot of the stream.
  * The time snapshot can give information about the time in the driver of the
  * graph, the delay to the edge of the graph and the internal queuing in the
- * stream.
+ * stream. This function should only be called in the STREAMING state and will
+ * return an error when called in any other state.
  *
  * pw_time.ticks gives a monotonic increasing counter of the time in the graph
- * driver. I can be used to generate a timetime to schedule samples as well
+ * driver. I can be used to generate a timeline to schedule samples as well
  * as detect discontinuities in the timeline caused by xruns.
  *
  * pw_time.delay is expressed as pw_time.rate, the time domain of the graph. This
@@ -305,15 +312,20 @@ struct pw_stream_control {
  *
  * pw_time.delay contains the total delay that a signal will travel through the
  * graph. This includes the delay caused by filters in the graph as well as delays
- * caused by the hardware. The delay is usually quite stable and should only change when
- * the topology, quantum or samplerate of the graph changes.
+ * caused by the hardware and extra delay offsets added to this. The delay is usually
+ * quite stable and should only change when the topology, quantum or samplerate of
+ * the graph changes.
  *
- * The delay requires the application to send the stream early relative to other synchronized
- * streams in order to arrive at the edge of the graph in time. This is usually done by
- * delaying the other streams with the given delay.
+ * The (positive) delay requires the application to send the stream early relative to other
+ * synchronized streams in order to arrive at the edge of the graph in time. This is usually
+ * done by delaying the other streams with the given delay.
  *
- * Note that the delay can be negative. A negative delay means that this stream should be
- * delayed with the (positive) delay relative to other streams.
+ * A delay offset is sometimes added (by the user) to improve synchronization of the streams
+ * when the reported latency is incorrect in some way. This means that with a large enough
+ * negative offset, the delay can become negative as well. A negative delay in this context
+ * means that the user would like this stream to be delayed with the (positive) delay amount
+ * in order to synchronize it with other streams. Streams are in general not expected to be
+ * able to delay themselves and it is acceptable to clamp negative delays to 0.
  *
  * pw_time.queued and pw_time.buffered is expressed in the time domain of the stream,
  * or the format that is used for the buffers of this stream.
@@ -379,10 +391,11 @@ struct pw_time {
                       *  the playback device or the time a sample traveled
                       *  from the capture device. This delay includes the
                       *  delay introduced by all filters on the path between
-                      *  the stream and the device. The delay is normally
-                      *  constant in a graph and can change when the topology
-                      *  of the graph or the quantum changes. This delay does
-                      *  not include the delay caused by queued buffers. */
+                      *  the stream and the device and extra delay offsets. The
+                      *  delay is normally constant in a graph and can change when
+                      *  the topology of the graph or the quantum changes. This delay
+                      *  does not include the delay caused by queued buffers.
+                      *  The delay can be negative, see \ref pw_time . */
     uint64_t queued;        /**< data queued in the stream, this is the sum
                       *  of the size fields in the pw_buffer that are
                       *  currently queued */
@@ -406,7 +419,8 @@ struct pw_stream_events {
     uint32_t version;
 
     void (*destroy) (void *data);
-    /** when the stream state changes */
+    /** when the stream state changes. Since 1.4 this also sets errno when the
+     * new state is PW_STREAM_STATE_ERROR */
     void (*state_changed) (void *data, enum pw_stream_state old,
                 enum pw_stream_state state, const char *error);
 
@@ -511,6 +525,8 @@ void pw_stream_add_listener(struct pw_stream *stream,
                 const struct pw_stream_events *events,
                 void *data);
 
+/** Get the current stream state. Since 1.4 this also sets errno when the
+ * state is PW_STREAM_STATE_ERROR */
 enum pw_stream_state pw_stream_get_state(struct pw_stream *stream, const char **error);
 
 const char *pw_stream_get_name(struct pw_stream *stream);
@@ -579,7 +595,7 @@ const struct pw_stream_control *pw_stream_get_control(struct pw_stream *stream,
 /** Set control values */
 int pw_stream_set_control(struct pw_stream *stream, uint32_t id, uint32_t n_values, float *values, ...);
 
-/** Query the time on the stream, RT safe */
+/** Query the time on the stream. Returns an error when the stream is not running. RT safe */
 int pw_stream_get_time_n(struct pw_stream *stream, struct pw_time *time, size_t size);
 
 /** Get the current time in nanoseconds. This value can be compared with
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/type.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/type.h
index 2035811666e..2692f3e6636 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/type.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/type.h
@@ -5,12 +5,12 @@
 #ifndef PIPEWIRE_TYPE_H
 #define PIPEWIRE_TYPE_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /** \defgroup pw_type Type info
  * Type information
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/pipewire/utils.h b/src/java.desktop/unix/native/libpipewire/include/pipewire/utils.h
index c5843204875..b9a78b1bce9 100644
--- a/src/java.desktop/unix/native/libpipewire/include/pipewire/utils.h
+++ b/src/java.desktop/unix/native/libpipewire/include/pipewire/utils.h
@@ -5,10 +5,6 @@
 #ifndef PIPEWIRE_UTILS_H
 #define PIPEWIRE_UTILS_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 #include 
 #include 
@@ -16,15 +12,20 @@ extern "C" {
 # include 
 #endif
 #include 
-
-#ifndef ENODATA
-#define ENODATA 9919
-#endif
+#include 
 
 #include 
 #include 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef ENODATA
+#define ENODATA 9919
+#endif
+
 /** \defgroup pw_utils Utilities
  *
  * Various utility functions
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/buffer/buffer.h b/src/java.desktop/unix/native/libpipewire/include/spa/buffer/buffer.h
index b287a76dec1..099852ff8ed 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/buffer/buffer.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/buffer/buffer.h
@@ -5,13 +5,13 @@
 #ifndef SPA_BUFFER_H
 #define SPA_BUFFER_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 #ifndef SPA_API_BUFFER
  #ifdef SPA_API_IMPL
   #define SPA_API_BUFFER SPA_API_IMPL
@@ -118,6 +118,17 @@ SPA_API_BUFFER void *spa_buffer_find_meta_data(const struct spa_buffer *b, uint3
     return NULL;
 }
 
+SPA_API_BUFFER bool spa_buffer_has_meta_features(const struct spa_buffer *b, uint32_t type, uint32_t features)
+{
+    uint32_t i;
+    for (i = 0; i < b->n_metas; i++) {
+        uint32_t t = b->metas[i].type;
+        if ((t >> 16) == type && (t & features) == features)
+            return true;
+    }
+    return false;
+}
+
 /**
  * \}
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/buffer/meta.h b/src/java.desktop/unix/native/libpipewire/include/spa/buffer/meta.h
index dbb452b56d7..ead00add039 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/buffer/meta.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/buffer/meta.h
@@ -5,13 +5,13 @@
 #ifndef SPA_META_H
 #define SPA_META_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 #ifndef SPA_API_META
  #ifdef SPA_API_IMPL
   #define SPA_API_META SPA_API_IMPL
@@ -37,10 +37,17 @@ enum spa_meta_type {
     SPA_META_Busy,            /**< don't write to buffer when count > 0 */
     SPA_META_VideoTransform,    /**< struct spa_meta_transform */
     SPA_META_SyncTimeline,        /**< struct spa_meta_sync_timeline */
-
     _SPA_META_LAST,            /**< not part of ABI/API */
+
+    SPA_META_START_custom        = 0x200,
+
+    SPA_META_START_features        = 0x10000,    /* features start, these have 0 size, the
+                             * type in the upper 16 bits and a bitmask in
+                             * the lower 16 bits with type specific features. */
 };
 
+#define SPA_META_TYPE_FEATURES(type,features)    (((type)<<16)|(features))
+
 /**
  * A metadata element.
  *
@@ -183,7 +190,12 @@ struct spa_meta_videotransform {
  * this metadata as SPA_PARAM_BUFFERS_metaType when negotiating a buffer
  * layout with 2 extra fds.
  */
+#define SPA_META_FEATURE_SYNC_TIMELINE_RELEASE    (1<<0)    /**< metadata supports RELEASE */
+
 struct spa_meta_sync_timeline {
+#define SPA_META_SYNC_TIMELINE_UNSCHEDULED_RELEASE    (1<<0)    /**< this flag is set by the producer and cleared
+                                  *  by the consumer when it promises to signal
+                                  *  the release point */
     uint32_t flags;
     uint32_t padding;
     uint64_t acquire_point;            /**< the timeline acquire point, this is when the data
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/buffer/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/buffer/type-info.h
index 2a9c43c3a42..8de4aa104a8 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/buffer/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/buffer/type-info.h
@@ -5,6 +5,10 @@
 #ifndef SPA_BUFFER_TYPES_H
 #define SPA_BUFFER_TYPES_H
 
+#include 
+#include 
+#include 
+
 /**
  * \addtogroup spa_buffer
  * \{
@@ -14,10 +18,6 @@
 extern "C" {
 #endif
 
-#include 
-#include 
-#include 
-
 #define SPA_TYPE_INFO_Buffer            SPA_TYPE_INFO_POINTER_BASE "Buffer"
 #define SPA_TYPE_INFO_BUFFER_BASE        SPA_TYPE_INFO_Buffer ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/control/control.h b/src/java.desktop/unix/native/libpipewire/include/spa/control/control.h
index 43877eef9cc..ccd4819c36b 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/control/control.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/control/control.h
@@ -5,13 +5,13 @@
 #ifndef SPA_CONTROL_H
 #define SPA_CONTROL_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /** \defgroup spa_control Control
  * Control type declarations
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/control/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/control/type-info.h
index 3db937ec616..8b2b8183c0f 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/control/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/control/type-info.h
@@ -5,6 +5,10 @@
 #ifndef SPA_CONTROL_TYPES_H
 #define SPA_CONTROL_TYPES_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 /* base for parameter object enumerations */
 #define SPA_TYPE_INFO_Control        SPA_TYPE_INFO_ENUM_BASE "Control"
 #define SPA_TYPE_INFO_CONTROL_BASE        SPA_TYPE_INFO_Control ":"
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/debug/types.h b/src/java.desktop/unix/native/libpipewire/include/spa/debug/types.h
index b32fd28ed9c..a968eedcaa1 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/debug/types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/debug/types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_DEBUG_TYPES_H
 #define SPA_DEBUG_TYPES_H
 
+#include 
+
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
-#include 
-
 #ifndef SPA_API_DEBUG_TYPES
  #ifdef SPA_API_IMPL
   #define SPA_API_DEBUG_TYPES SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/monitor/event.h b/src/java.desktop/unix/native/libpipewire/include/spa/monitor/event.h
index 423127e6120..79d61fc8866 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/monitor/event.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/monitor/event.h
@@ -5,12 +5,12 @@
 #ifndef SPA_EVENT_DEVICE_H
 #define SPA_EVENT_DEVICE_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /**
  * \addtogroup spa_device
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/monitor/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/monitor/type-info.h
index f5920c20600..aa6422f7b60 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/monitor/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/monitor/type-info.h
@@ -5,14 +5,14 @@
 #ifndef SPA_DEVICE_TYPE_INFO_H
 #define SPA_DEVICE_TYPE_INFO_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
  * \addtogroup spa_device
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/node/command.h b/src/java.desktop/unix/native/libpipewire/include/spa/node/command.h
index 0915fca6cee..25c24f323a1 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/node/command.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/node/command.h
@@ -5,6 +5,8 @@
 #ifndef SPA_COMMAND_NODE_H
 #define SPA_COMMAND_NODE_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /* object id of SPA_TYPE_COMMAND_Node */
 enum spa_node_command {
     SPA_NODE_COMMAND_Suspend,    /**< suspend a node, this removes all configured
@@ -36,12 +36,24 @@ enum spa_node_command {
     SPA_NODE_COMMAND_ParamEnd,    /**< end a transaction */
     SPA_NODE_COMMAND_RequestProcess,/**< Sent to a driver when some other node emitted
                       *  the RequestProcess event. */
+    SPA_NODE_COMMAND_User,        /**< User defined command */
 };
 
 #define SPA_NODE_COMMAND_ID(cmd)    SPA_COMMAND_ID(cmd, SPA_TYPE_COMMAND_Node)
 #define SPA_NODE_COMMAND_INIT(id)    SPA_COMMAND_INIT(SPA_TYPE_COMMAND_Node, id)
 
 
+/* properties for SPA_TYPE_COMMAND_Node */
+enum spa_command_node {
+    SPA_COMMAND_NODE_START,
+
+    SPA_COMMAND_NODE_START_User         = 0x1000,
+    SPA_COMMAND_NODE_extra,            /** extra info (String) */
+
+    SPA_COMMAND_NODE_START_CUSTOM       = 0x1000000,
+};
+
+
 /**
  * \}
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/node/event.h b/src/java.desktop/unix/native/libpipewire/include/spa/node/event.h
index 94c2ef1316a..1a58b1be96e 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/node/event.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/node/event.h
@@ -5,6 +5,8 @@
 #ifndef SPA_EVENT_NODE_H
 #define SPA_EVENT_NODE_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /* object id of SPA_TYPE_EVENT_Node */
 enum spa_node_event {
     SPA_NODE_EVENT_Error,
@@ -23,6 +23,7 @@ enum spa_node_event {
     SPA_NODE_EVENT_RequestRefresh,
     SPA_NODE_EVENT_RequestProcess,        /*< Ask the driver to start processing
                          *  the graph */
+    SPA_NODE_EVENT_User,            /* User defined event */
 };
 
 #define SPA_NODE_EVENT_ID(ev)    SPA_EVENT_ID(ev, SPA_TYPE_EVENT_Node)
@@ -31,6 +32,11 @@ enum spa_node_event {
 /* properties for SPA_TYPE_EVENT_Node */
 enum spa_event_node {
     SPA_EVENT_NODE_START,
+
+    SPA_EVENT_NODE_START_User     = 0x1000,
+    SPA_EVENT_NODE_extra,        /** extra info (String) */
+
+    SPA_EVENT_NODE_START_CUSTOM       = 0x1000000,
 };
 
 /**
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/node/io.h b/src/java.desktop/unix/native/libpipewire/include/spa/node/io.h
index fffde5bb27b..3169b461a0c 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/node/io.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/node/io.h
@@ -5,6 +5,9 @@
 #ifndef SPA_IO_H
 #define SPA_IO_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,9 +17,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-
 /** IO areas
  *
  * IO information for a port on a node. This is allocated
@@ -114,23 +114,54 @@ struct spa_io_range {
  * Driver nodes are supposed to update the contents of \ref SPA_IO_Clock before
  * signaling the start of a graph cycle.  These updated clock values become
  * visible to other nodes in \ref SPA_IO_Position. Non-driver nodes do
- * not need to update the contents of their \ref SPA_IO_Clock.
+ * not need to update the contents of their \ref SPA_IO_Clock. Also
+ * see \ref page_driver for further details.
  *
  * The host generally gives each node a separate \ref spa_io_clock in \ref
  * SPA_IO_Clock, so that updates made by the driver are not visible in the
  * contents of \ref SPA_IO_Clock of other nodes. Instead, \ref SPA_IO_Position
  * is used to look up the current graph time.
  *
- * A node is a driver when \ref spa_io_clock.id in \ref SPA_IO_Clock and
- * \ref spa_io_position.clock.id in \ref SPA_IO_Position are the same.
+ * A node is a driver when \ref spa_io_clock::id and the ID in
+ * \ref spa_io_position.clock in \ref SPA_IO_Position are the same.
+ *
+ * The flags are set by the graph driver at the start of each cycle.
  */
 struct spa_io_clock {
-#define SPA_IO_CLOCK_FLAG_FREEWHEEL    (1u<<0) /* graph is freewheeling */
-#define SPA_IO_CLOCK_FLAG_XRUN_RECOVER    (1u<<1) /* recovering from xrun */
-#define SPA_IO_CLOCK_FLAG_LAZY        (1u<<2) /* lazy scheduling */
-#define SPA_IO_CLOCK_FLAG_NO_RATE    (1u<<3) /* the rate of the clock is only approximately.
-                         * it is recommended to use the nsec as a clock source.
-                         * The rate_diff contains the measured inaccuracy. */
+#define SPA_IO_CLOCK_FLAG_FREEWHEEL    (1u<<0) /**< Graph is freewheeling. It runs at the maximum
+                          *  possible rate, only constrained by the processing
+                          *  power of the machine it runs on. This can be useful
+                          *  for offline processing, where processing in real
+                          *  time is not desired. */
+#define SPA_IO_CLOCK_FLAG_XRUN_RECOVER    (1u<<1) /**< A node's process callback did not complete within
+                          *  the last cycle's deadline, resulting in an xrun.
+                          *  This flag is not set for the entire graph. Instead,
+                          *  it is set at the start of the current cycle before
+                          *  a node that experienced an xrun has its process
+                          *  callback invoked. After said callback finished, the
+                          *  flag is cleared again. That way, the node knows that
+                          *  during the last cycle it experienced an xrun. They
+                          *  can use this information for example to resynchronize
+                          *  or clear custom stale states. */
+#define SPA_IO_CLOCK_FLAG_LAZY        (1u<<2) /**< The driver uses lazy scheduling. For details, see
+                          *  \ref PW_KEY_NODE_SUPPORTS_LAZY . */
+#define SPA_IO_CLOCK_FLAG_NO_RATE    (1u<<3) /**< The rate of the clock is only approximately.
+                         *   It is recommended to use the nsec as a clock source.
+                         *   The rate_diff contains the measured inaccuracy. */
+#define SPA_IO_CLOCK_FLAG_DISCONT    (1u<<4) /**< The clock experienced a discontinuity in its
+                         *   timestamps since the last cycle. If this is set,
+                         *   nodes know that timestamps between the last and
+                         *   the current cycle cannot be assumed to be
+                         *   continuous. Nodes that synchronize playback against
+                         *   clock timestamps should resynchronize (for example
+                         *   by flushing buffers to avoid incorrect delays).
+                         *   This differs from an xrun in that it is not necessariy
+                         *   an error and that it is not caused by missed process
+                         *   deadlines. If for example a custom network time
+                         *   based driver starts to follow a different time
+                         *   server, and the offset between that server and its
+                         *   local clock consequently suddenly changes, then that
+                         *   driver should set this flag. */
     uint32_t flags;            /**< Clock flags */
     uint32_t id;            /**< Unique clock id, set by host application */
     char name[64];            /**< Clock name prefixed with API, set by node when it receives
@@ -138,13 +169,16 @@ struct spa_io_clock {
                       *  can be used to check if nodes share the same clock. */
     uint64_t nsec;            /**< Time in nanoseconds against monotonic clock
                       * (CLOCK_MONOTONIC). This fields reflects a real time instant
-                      * in the past. The value may have jitter. */
+                      * in the past, when the current cycle started. The value may
+                      * have jitter. */
     struct spa_fraction rate;    /**< Rate for position/duration/delay/xrun */
     uint64_t position;        /**< Current position, in samples @ \ref rate */
     uint64_t duration;        /**< Duration of current cycle, in samples @ \ref rate */
     int64_t delay;            /**< Delay between position and hardware, in samples @ \ref rate */
     double rate_diff;        /**< Rate difference between clock and monotonic time, as a ratio of
-                      *  clock speeds. */
+                      *  clock speeds. A value higher than 1.0 means that the driver's
+                      *  internal clock is faster than the monotonic clock (by that
+                      *  factor), and vice versa. */
     uint64_t next_nsec;        /**< Estimated next wakeup time in nanoseconds.
                       *  This time is a logical start time of the next cycle, and
                       *  is not necessarily in the future.
@@ -278,8 +312,8 @@ enum spa_io_position_state {
  *
  * It is set on all nodes in \ref SPA_IO_Position, and the contents of \ref
  * spa_io_position.clock contain the clock updates made by the driving node in
- * the graph in its \ref SPA_IO_Clock.  Also, \ref spa_io_position.clock.id
- * will contain the clock id of the driving node in the graph.
+ * the graph in its \ref SPA_IO_Clock.  Also, the ID in \ref spa_io_position.clock
+ * will be the clock id of the driving node in the graph.
  *
  * The position clock indicates the logical start time of the current graph
  * cycle.
@@ -313,7 +347,7 @@ struct spa_io_position {
  * and node rates. The \a flags and \a rate fields may be modified by the node.
  *
  * The node can request a correction to the resampling rate in its process(), by setting
- * \ref SPA_IO_RATE_MATCH_ACTIVE on \a flags, and setting \a rate to the desired rate
+ * \ref SPA_IO_RATE_MATCH_FLAG_ACTIVE on \a flags, and setting \a rate to the desired rate
  * correction.  Usually the rate is obtained from DLL or other adaptive mechanism that
  * e.g. drives the node buffer fill level toward a specific value.
  *
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/node/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/node/type-info.h
index ab4dbdedfb7..bd8684ac0b2 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/node/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/node/type-info.h
@@ -5,6 +5,12 @@
 #ifndef SPA_NODE_TYPES_H
 #define SPA_NODE_TYPES_H
 
+#include 
+
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,12 +20,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
-#include 
-#include 
-#include 
-
 #define SPA_TYPE_INFO_IO            SPA_TYPE_INFO_ENUM_BASE "IO"
 #define SPA_TYPE_INFO_IO_BASE        SPA_TYPE_INFO_IO ":"
 
@@ -46,16 +46,20 @@ static const struct spa_type_info spa_type_node_event_id[] = {
     { SPA_NODE_EVENT_Buffering,     SPA_TYPE_EVENT_Node, SPA_TYPE_INFO_NODE_EVENT_BASE "Buffering", NULL },
     { SPA_NODE_EVENT_RequestRefresh, SPA_TYPE_EVENT_Node, SPA_TYPE_INFO_NODE_EVENT_BASE "RequestRefresh", NULL },
     { SPA_NODE_EVENT_RequestProcess, SPA_TYPE_EVENT_Node, SPA_TYPE_INFO_NODE_EVENT_BASE "RequestProcess", NULL },
+    { SPA_NODE_EVENT_User,           SPA_TYPE_EVENT_Node, SPA_TYPE_INFO_NODE_EVENT_BASE "User", NULL },
     { 0, 0, NULL, NULL },
 };
 
 static const struct spa_type_info spa_type_node_event[] = {
     { SPA_EVENT_NODE_START, SPA_TYPE_Id, SPA_TYPE_INFO_NODE_EVENT_BASE, spa_type_node_event_id },
+
+    { SPA_EVENT_NODE_extra, SPA_TYPE_String, SPA_TYPE_INFO_NODE_EVENT_BASE "extra", NULL },
+
     { 0, 0, NULL, NULL },
 };
 
 #define SPA_TYPE_INFO_NodeCommand            SPA_TYPE_INFO_COMMAND_BASE "Node"
-#define SPA_TYPE_INFO_NODE_COMMAND_BASE        SPA_TYPE_INFO_NodeCommand ":"
+#define SPA_TYPE_INFO_NODE_COMMAND_BASE            SPA_TYPE_INFO_NodeCommand ":"
 
 static const struct spa_type_info spa_type_node_command_id[] = {
     { SPA_NODE_COMMAND_Suspend,    SPA_TYPE_COMMAND_Node, SPA_TYPE_INFO_NODE_COMMAND_BASE "Suspend", NULL },
@@ -69,11 +73,15 @@ static const struct spa_type_info spa_type_node_command_id[] = {
     { SPA_NODE_COMMAND_ParamBegin,    SPA_TYPE_COMMAND_Node, SPA_TYPE_INFO_NODE_COMMAND_BASE "ParamBegin",  NULL },
     { SPA_NODE_COMMAND_ParamEnd,    SPA_TYPE_COMMAND_Node, SPA_TYPE_INFO_NODE_COMMAND_BASE "ParamEnd",  NULL },
     { SPA_NODE_COMMAND_RequestProcess, SPA_TYPE_COMMAND_Node, SPA_TYPE_INFO_NODE_COMMAND_BASE "RequestProcess",  NULL },
+    { SPA_NODE_COMMAND_User,        SPA_TYPE_COMMAND_Node, SPA_TYPE_INFO_NODE_COMMAND_BASE "User",  NULL },
     { 0, 0, NULL, NULL },
 };
 
 static const struct spa_type_info spa_type_node_command[] = {
-    { 0, SPA_TYPE_Id, SPA_TYPE_INFO_NODE_COMMAND_BASE, spa_type_node_command_id },
+    { SPA_COMMAND_NODE_START, SPA_TYPE_Id, SPA_TYPE_INFO_NODE_COMMAND_BASE, spa_type_node_command_id },
+
+    { SPA_COMMAND_NODE_extra, SPA_TYPE_String, SPA_TYPE_INFO_NODE_COMMAND_BASE "extra", NULL },
+
     { 0, 0, NULL, NULL },
 };
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac-types.h
index e941250ff96..8d6d87de7c2 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac-types.h
@@ -5,13 +5,13 @@
 #ifndef SPA_AUDIO_AAC_TYPES_H
 #define SPA_AUDIO_AAC_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac.h
index 164eaf7de8b..0c06ee5d7ca 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/aac.h
@@ -5,12 +5,12 @@
 #ifndef SPA_AUDIO_AAC_H
 #define SPA_AUDIO_AAC_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
@@ -18,19 +18,19 @@ extern "C" {
 
 enum spa_audio_aac_stream_format {
     SPA_AUDIO_AAC_STREAM_FORMAT_UNKNOWN,
-    /* Raw AAC frames */
+    /** Raw AAC frames */
     SPA_AUDIO_AAC_STREAM_FORMAT_RAW,
-    /* ISO/IEC 13818-7 MPEG-2 Audio Data Transport Stream (ADTS) */
+    /** ISO/IEC 13818-7 MPEG-2 Audio Data Transport Stream (ADTS) */
     SPA_AUDIO_AAC_STREAM_FORMAT_MP2ADTS,
-    /* ISO/IEC 14496-3 MPEG-4 Audio Data Transport Stream (ADTS) */
+    /** ISO/IEC 14496-3 MPEG-4 Audio Data Transport Stream (ADTS) */
     SPA_AUDIO_AAC_STREAM_FORMAT_MP4ADTS,
-    /* ISO/IEC 14496-3 Low Overhead Audio Stream (LOAS) */
+    /** ISO/IEC 14496-3 Low Overhead Audio Stream (LOAS) */
     SPA_AUDIO_AAC_STREAM_FORMAT_MP4LOAS,
-    /* ISO/IEC 14496-3 Low Overhead Audio Transport Multiplex (LATM) */
+    /** ISO/IEC 14496-3 Low Overhead Audio Transport Multiplex (LATM) */
     SPA_AUDIO_AAC_STREAM_FORMAT_MP4LATM,
-    /* ISO/IEC 14496-3 Audio Data Interchange Format (ADIF) */
+    /** ISO/IEC 14496-3 Audio Data Interchange Format (ADIF) */
     SPA_AUDIO_AAC_STREAM_FORMAT_ADIF,
-    /* ISO/IEC 14496-12 MPEG-4 file format */
+    /** ISO/IEC 14496-12 MPEG-4 file format */
     SPA_AUDIO_AAC_STREAM_FORMAT_MP4FF,
 
     SPA_AUDIO_AAC_STREAM_FORMAT_CUSTOM = 0x10000,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr-types.h
index 34281c85763..5a9a348a892 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr-types.h
@@ -5,13 +5,13 @@
 #ifndef SPA_AUDIO_AMR_TYPES_H
 #define SPA_AUDIO_AMR_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr.h
index aece0ab119e..8dec9fdbafb 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/amr.h
@@ -5,12 +5,12 @@
 #ifndef SPA_AUDIO_AMR_H
 #define SPA_AUDIO_AMR_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts-types.h
new file mode 100644
index 00000000000..eedc8f8e354
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts-types.h
@@ -0,0 +1,39 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 Carlos Rafael Giani */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_AUDIO_DTS_TYPES_H
+#define SPA_AUDIO_DTS_TYPES_H
+
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+#define SPA_TYPE_INFO_AudioDTSExtType        SPA_TYPE_INFO_ENUM_BASE "AudioDTSExtType"
+#define SPA_TYPE_INFO_AUDIO_DTS_EXT_TYPE_BASE    SPA_TYPE_INFO_AudioDTSExtType ":"
+
+static const struct spa_type_info spa_type_audio_dts_ext_type[] = {
+    { SPA_AUDIO_DTS_EXT_UNKNOWN, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_DTS_EXT_TYPE_BASE "UNKNOWN", NULL },
+    { SPA_AUDIO_DTS_EXT_NONE, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_DTS_EXT_TYPE_BASE "NONE", NULL },
+    { SPA_AUDIO_DTS_EXT_HD_HRA, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_DTS_EXT_TYPE_BASE "HRA", NULL },
+    { SPA_AUDIO_DTS_EXT_HD_MA, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_DTS_EXT_TYPE_BASE "MA", NULL },
+    { 0, 0, NULL, NULL },
+};
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_AUDIO_DTS_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts.h
new file mode 100644
index 00000000000..4ed16c3ef61
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/dts.h
@@ -0,0 +1,51 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 Carlos Rafael Giani */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_AUDIO_DTS_H
+#define SPA_AUDIO_DTS_H
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+/**
+ * Possible high-definition DTS extensions on top of core DTS.
+ */
+enum spa_audio_dts_ext_type {
+    SPA_AUDIO_DTS_EXT_UNKNOWN,
+    SPA_AUDIO_DTS_EXT_NONE,        /**< No extension present; this is just regular DTS data */
+    SPA_AUDIO_DTS_EXT_HD_HRA,    /**< DTS-HD High Resolution Audio (lossy HD audio extension) */
+    SPA_AUDIO_DTS_EXT_HD_MA,    /**< DTS-HD Master Audio (lossless HD audio extension) */
+};
+
+/**
+ * DTS Coherent Acoustics audio info. Optional extensions on top
+ * of the DTS content can be present, resulting in what is known
+ * as DTS-HD. \a ext_type specifies which extension is used in
+ * combination with the core DTS content (if any).
+ */
+struct spa_audio_info_dts {
+    uint32_t rate;                    /*< sample rate */
+    uint32_t channels;                /*< number of channels */
+    enum spa_audio_dts_ext_type ext_type;        /*< DTS-HD extension type */
+};
+
+#define SPA_AUDIO_INFO_DTS_INIT(...)        ((struct spa_audio_info_dts) { __VA_ARGS__ })
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_AUDIO_DTS_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958-types.h
index 6e2e3f028a5..eda1ac2daba 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958-types.h
@@ -5,13 +5,13 @@
 #ifndef SPA_AUDIO_IEC958_TYPES_H
 #define SPA_AUDIO_IEC958_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958.h
index 103f235cb66..1ddeb086562 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/iec958.h
@@ -31,7 +31,7 @@ enum spa_audio_iec958_codec {
 };
 
 struct spa_audio_info_iec958 {
-    enum spa_audio_iec958_codec codec;    /*< format, one of the DSP formats in enum spa_audio_format_dsp */
+    enum spa_audio_iec958_codec codec;    /*< codec, one of the values in enum spa_audio_iec958_codec */
     uint32_t flags;                /*< extra flags */
     uint32_t rate;                /*< sample rate */
 };
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout-types.h
new file mode 100644
index 00000000000..f996fddefed
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout-types.h
@@ -0,0 +1,118 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_AUDIO_LAYOUT_TYPES_H
+#define SPA_AUDIO_LAYOUT_TYPES_H
+
+#include 
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+#ifndef SPA_API_AUDIO_LAYOUT_TYPES
+ #ifdef SPA_API_IMPL
+  #define SPA_API_AUDIO_LAYOUT_TYPES SPA_API_IMPL
+ #else
+  #define SPA_API_AUDIO_LAYOUT_TYPES static inline
+ #endif
+#endif
+
+static const struct spa_type_audio_layout_info {
+    const char *name;
+    struct spa_audio_layout_info layout;
+} spa_type_audio_layout_info[] = {
+    { "Mono",  { SPA_AUDIO_LAYOUT_Mono } },
+    { "Stereo",  { SPA_AUDIO_LAYOUT_Stereo } },
+    { "Quad", { SPA_AUDIO_LAYOUT_Quad } },
+    { "Pentagonal", { SPA_AUDIO_LAYOUT_Pentagonal } },
+    { "Hexagonal", { SPA_AUDIO_LAYOUT_Hexagonal } },
+    { "Octagonal", { SPA_AUDIO_LAYOUT_Octagonal } },
+    { "Cube", { SPA_AUDIO_LAYOUT_Cube } },
+    { "MPEG-1.0", { SPA_AUDIO_LAYOUT_MPEG_1_0 } },
+    { "MPEG-2.0", { SPA_AUDIO_LAYOUT_MPEG_2_0 } },
+    { "MPEG-3.0A", { SPA_AUDIO_LAYOUT_MPEG_3_0A } },
+    { "MPEG-3.0B", { SPA_AUDIO_LAYOUT_MPEG_3_0B } },
+    { "MPEG-4.0A", { SPA_AUDIO_LAYOUT_MPEG_4_0A } },
+    { "MPEG-4.0B", { SPA_AUDIO_LAYOUT_MPEG_4_0B } },
+    { "MPEG-5.0A", { SPA_AUDIO_LAYOUT_MPEG_5_0A } },
+    { "MPEG-5.0B", { SPA_AUDIO_LAYOUT_MPEG_5_0B } },
+    { "MPEG-5.0C", { SPA_AUDIO_LAYOUT_MPEG_5_0C } },
+    { "MPEG-5.0D", { SPA_AUDIO_LAYOUT_MPEG_5_0D } },
+    { "MPEG-5.1A", { SPA_AUDIO_LAYOUT_MPEG_5_1A } },
+    { "MPEG-5.1B", { SPA_AUDIO_LAYOUT_MPEG_5_1B } },
+    { "MPEG-5.1C", { SPA_AUDIO_LAYOUT_MPEG_5_1C } },
+    { "MPEG-5.1D", { SPA_AUDIO_LAYOUT_MPEG_5_1D } },
+    { "MPEG-6.1A", { SPA_AUDIO_LAYOUT_MPEG_6_1A } },
+    { "MPEG-7.1A", { SPA_AUDIO_LAYOUT_MPEG_7_1A } },
+    { "MPEG-7.1B", { SPA_AUDIO_LAYOUT_MPEG_7_1B } },
+    { "MPEG-7.1C", { SPA_AUDIO_LAYOUT_MPEG_7_1C } },
+    { "2.1", { SPA_AUDIO_LAYOUT_2_1 } },
+    { "2RC", { SPA_AUDIO_LAYOUT_2RC } },
+    { "2FC", { SPA_AUDIO_LAYOUT_2FC } },
+    { "3.1", { SPA_AUDIO_LAYOUT_3_1 } },
+    { "4.0", { SPA_AUDIO_LAYOUT_4_0 } },
+    { "2.2", { SPA_AUDIO_LAYOUT_2_2 } },
+    { "4.1", { SPA_AUDIO_LAYOUT_4_1 } },
+    { "5.0", { SPA_AUDIO_LAYOUT_5_0 } },
+    { "5.0R", { SPA_AUDIO_LAYOUT_5_0R } },
+    { "5.1", { SPA_AUDIO_LAYOUT_5_1 } },
+    { "5.1R", { SPA_AUDIO_LAYOUT_5_1R } },
+    { "6.0", { SPA_AUDIO_LAYOUT_6_0 } },
+    { "6.0F", { SPA_AUDIO_LAYOUT_6_0F } },
+    { "6.1", { SPA_AUDIO_LAYOUT_6_1 } },
+    { "6.1F", { SPA_AUDIO_LAYOUT_6_1F } },
+    { "7.0", { SPA_AUDIO_LAYOUT_7_0 } },
+    { "7.0F", { SPA_AUDIO_LAYOUT_7_0F } },
+    { "7.1", { SPA_AUDIO_LAYOUT_7_1 } },
+    { "7.1W", { SPA_AUDIO_LAYOUT_7_1W } },
+    { "7.1WR", { SPA_AUDIO_LAYOUT_7_1WR } },
+    { NULL, { 0, { SPA_AUDIO_CHANNEL_UNKNOWN } } },
+};
+
+SPA_API_AUDIO_LAYOUT_TYPES int
+spa_audio_layout_info_parse_name(struct spa_audio_layout_info *layout, size_t size,
+        const char *name)
+{
+    uint32_t max_position = SPA_AUDIO_LAYOUT_INFO_MAX_POSITION(size);
+    if (spa_strstartswith(name, "AUX")) {
+        uint32_t i, n_pos;
+        if (spa_atou32(name+3, &n_pos, 10)) {
+            if (n_pos > max_position)
+                return -ECHRNG;
+            for (i = 0; i < 0x1000 && i < n_pos; i++)
+                layout->position[i] = SPA_AUDIO_CHANNEL_AUX0 + i;
+            for (; i < n_pos; i++)
+                layout->position[i] = SPA_AUDIO_CHANNEL_UNKNOWN;
+            layout->n_channels = n_pos;
+            return n_pos;
+        }
+    }
+    SPA_FOR_EACH_ELEMENT_VAR(spa_type_audio_layout_info, i) {
+        if (spa_streq(name, i->name)) {
+            if (i->layout.n_channels > max_position)
+                return -ECHRNG;
+            *layout = i->layout;
+            return i->layout.n_channels;
+        }
+    }
+    return -ENOTSUP;
+}
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_AUDIO_LAYOUT_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout.h
new file mode 100644
index 00000000000..0352bef944b
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/layout.h
@@ -0,0 +1,174 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2018 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_AUDIO_LAYOUT_H
+#define SPA_AUDIO_LAYOUT_H
+
+#include 
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+struct spa_audio_layout_info {
+    uint32_t n_channels;
+    uint32_t position[SPA_AUDIO_MAX_CHANNELS];
+    /* padding may follow to allow more channels */
+};
+
+#define SPA_AUDIO_LAYOUT_INFO_MAX_POSITION(size)    (((size)-offsetof(struct spa_audio_layout_info,position))/sizeof(uint32_t))
+
+#define SPA_AUDIO_LAYOUT_Mono        1, { SPA_AUDIO_CHANNEL_MONO, }
+#define SPA_AUDIO_LAYOUT_Stereo        2, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, }
+#define SPA_AUDIO_LAYOUT_Quad        4, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, }
+#define SPA_AUDIO_LAYOUT_Pentagonal    5, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_FC, }
+#define SPA_AUDIO_LAYOUT_Hexagonal    6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_Octagonal    8, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_RC, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_Cube        8, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_TFL, SPA_AUDIO_CHANNEL_TFR, \
+                         SPA_AUDIO_CHANNEL_TRL, SPA_AUDIO_CHANNEL_TRR, }
+
+
+#define SPA_AUDIO_LAYOUT_MPEG_1_0    SPA_AUDIO_LAYOUT_Mono
+#define SPA_AUDIO_LAYOUT_MPEG_2_0    SPA_AUDIO_LAYOUT_Stereo
+#define SPA_AUDIO_LAYOUT_MPEG_3_0A    3, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, }
+#define SPA_AUDIO_LAYOUT_MPEG_3_0B    3, { SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_FL, \
+                         SPA_AUDIO_CHANNEL_FR, }
+#define SPA_AUDIO_LAYOUT_MPEG_4_0A    4, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_MPEG_4_0B    4, { SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_FL, \
+                         SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_0A    5, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_0B    5, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, \
+                         SPA_AUDIO_CHANNEL_FC, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_0C    5, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FC, \
+                         SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_0D    5, { SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_FL, \
+                         SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_1A    6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_1B    6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_1C    6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FC, \
+                         SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, SPA_AUDIO_CHANNEL_LFE, }
+#define SPA_AUDIO_LAYOUT_MPEG_5_1D    6, { SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_FL, \
+                         SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, SPA_AUDIO_CHANNEL_LFE, }
+#define SPA_AUDIO_LAYOUT_MPEG_6_1A    7, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, \
+                         SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_MPEG_7_1A    8, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_MPEG_7_1B    8, { SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, SPA_AUDIO_CHANNEL_FL, \
+                         SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_RL, \
+                         SPA_AUDIO_CHANNEL_RR, SPA_AUDIO_CHANNEL_LFE, }
+#define SPA_AUDIO_LAYOUT_MPEG_7_1C    8, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, }
+
+
+#define SPA_AUDIO_LAYOUT_2_1        3, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_LFE, }
+
+#define SPA_AUDIO_LAYOUT_2RC        3, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_2FC        3, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, }
+
+#define SPA_AUDIO_LAYOUT_3_1        4, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, }
+#define SPA_AUDIO_LAYOUT_4_0        4, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_2_2        4, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+
+#define SPA_AUDIO_LAYOUT_4_1        5, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_5_0        5, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_5_0R        5, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_RL, \
+                         SPA_AUDIO_CHANNEL_RR, }
+#define SPA_AUDIO_LAYOUT_5_1        6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_5_1R        6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, }
+#define SPA_AUDIO_LAYOUT_6_0        6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_RC, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_6_0F        6, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FLC, SPA_AUDIO_CHANNEL_FRC, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_6_1        7, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_RC, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_6_1F        7, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_RC, }
+#define SPA_AUDIO_LAYOUT_7_0        7, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_RL, \
+                         SPA_AUDIO_CHANNEL_RR, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_7_0F        7, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_FLC, \
+                         SPA_AUDIO_CHANNEL_FRC, SPA_AUDIO_CHANNEL_SL, \
+                         SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_7_1        8, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_7_1W        8, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_FLC, SPA_AUDIO_CHANNEL_FRC, \
+                         SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR, }
+#define SPA_AUDIO_LAYOUT_7_1WR        8, { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, \
+                         SPA_AUDIO_CHANNEL_FC, SPA_AUDIO_CHANNEL_LFE, \
+                         SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR, \
+                         SPA_AUDIO_CHANNEL_FLC, SPA_AUDIO_CHANNEL_FRC, }
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_AUDIO_LAYOUT_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3-types.h
index 8974f1efb33..1cd3d67693f 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3-types.h
@@ -5,13 +5,13 @@
 #ifndef SPA_AUDIO_MP3_TYPES_H
 #define SPA_AUDIO_MP3_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3.h
index bfe61aaea54..e69e937ab8d 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/mp3.h
@@ -5,12 +5,12 @@
 #ifndef SPA_AUDIO_MP3_H
 #define SPA_AUDIO_MP3_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
@@ -18,15 +18,26 @@ extern "C" {
 
 enum spa_audio_mp3_channel_mode {
     SPA_AUDIO_MP3_CHANNEL_MODE_UNKNOWN,
+    /** Mono mode, only used if channel count is 1 */
     SPA_AUDIO_MP3_CHANNEL_MODE_MONO,
+    /** Regular stereo mode with two independent channels */
     SPA_AUDIO_MP3_CHANNEL_MODE_STEREO,
+    /**
+     * Joint stereo mode, exploiting the similarities between channels
+     * using techniques like mid-side coding
+     */
     SPA_AUDIO_MP3_CHANNEL_MODE_JOINTSTEREO,
+    /**
+     * Two mono tracks, different from stereo in that each channel
+     * contains entirely different content (like two different mono songs)
+     */
     SPA_AUDIO_MP3_CHANNEL_MODE_DUAL,
 };
 
 struct spa_audio_info_mp3 {
-    uint32_t rate;                /*< sample rate */
-    uint32_t channels;            /*< number of channels */
+    uint32_t rate;                    /*< sample rate in Hz */
+    uint32_t channels;                /*< number of channels */
+    enum spa_audio_mp3_channel_mode channel_mode;    /*< MP3 channel mode */
 };
 
 #define SPA_AUDIO_INFO_MP3_INIT(...)        ((struct spa_audio_info_mp3) { __VA_ARGS__ })
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw-types.h
index 06b8cc4a7d3..19d993c0086 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw-types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_AUDIO_RAW_TYPES_H
 #define SPA_AUDIO_RAW_TYPES_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #ifndef SPA_API_AUDIO_RAW_TYPES
  #ifdef SPA_API_IMPL
   #define SPA_API_AUDIO_RAW_TYPES SPA_API_IMPL
@@ -192,7 +192,7 @@ static const struct spa_type_info spa_type_audio_channel[] = {
     { SPA_AUDIO_CHANNEL_TFRC, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "TFRC", NULL },
     { SPA_AUDIO_CHANNEL_TSL, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "TSL", NULL },
     { SPA_AUDIO_CHANNEL_TSR, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "TSR", NULL },
-    { SPA_AUDIO_CHANNEL_LLFE, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "LLFR", NULL },
+    { SPA_AUDIO_CHANNEL_LLFE, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "LLFE", NULL },
     { SPA_AUDIO_CHANNEL_RLFE, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "RLFE", NULL },
     { SPA_AUDIO_CHANNEL_BC, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "BC", NULL },
     { SPA_AUDIO_CHANNEL_BLC, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_CHANNEL_BASE "BLC", NULL },
@@ -267,13 +267,44 @@ static const struct spa_type_info spa_type_audio_channel[] = {
 
 SPA_API_AUDIO_RAW_TYPES uint32_t spa_type_audio_channel_from_short_name(const char *name)
 {
-    return spa_type_from_short_name(name, spa_type_audio_channel, SPA_AUDIO_CHANNEL_UNKNOWN);
+    uint32_t res;
+    if (spa_strstartswith(name, "AUX")) {
+        if (spa_atou32(name+3, &res, 10) && res < 0x1000)
+            res = SPA_AUDIO_CHANNEL_AUX0 + res;
+        else
+            res = SPA_AUDIO_CHANNEL_UNKNOWN;
+    } else {
+        res = spa_type_from_short_name(name, spa_type_audio_channel, SPA_AUDIO_CHANNEL_UNKNOWN);
+    }
+    return res;
 }
 SPA_API_AUDIO_RAW_TYPES const char * spa_type_audio_channel_to_short_name(uint32_t type)
 {
     return spa_type_to_short_name(type, spa_type_audio_channel, "UNK");
 }
+SPA_API_AUDIO_RAW_TYPES const char * spa_type_audio_channel_make_short_name(uint32_t type,
+        char *buf, size_t size, const char *unknown)
+{
+    if (SPA_AUDIO_CHANNEL_IS_AUX(type)) {
+        snprintf(buf, size, "AUX%u", type - SPA_AUDIO_CHANNEL_AUX0);
+    } else {
+        const char *str = spa_type_to_short_name(type, spa_type_audio_channel, NULL);
+        if (str == NULL)
+            return unknown;
+        snprintf(buf, size, "%.7s", str);
+    }
+    return buf;
+}
 
+#define SPA_TYPE_INFO_AudioVolumeRampScale        SPA_TYPE_INFO_ENUM_BASE "AudioVolumeRampScale"
+#define SPA_TYPE_INFO_AUDIO_VOLUME_RAMP_SCALE_BASE    SPA_TYPE_INFO_AudioVolumeRampScale ":"
+
+static const struct spa_type_info spa_type_audio_volume_ramp_scale[] = {
+    { SPA_AUDIO_VOLUME_RAMP_INVALID, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_VOLUME_RAMP_SCALE_BASE "INVALID", NULL },
+    { SPA_AUDIO_VOLUME_RAMP_LINEAR, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_VOLUME_RAMP_SCALE_BASE "LINEAR", NULL },
+    { SPA_AUDIO_VOLUME_RAMP_CUBIC, SPA_TYPE_Int, SPA_TYPE_INFO_AUDIO_VOLUME_RAMP_SCALE_BASE "CUBIC", NULL },
+    { 0, 0, NULL, NULL },
+};
 
 /**
  * \}
@@ -283,4 +314,4 @@ SPA_API_AUDIO_RAW_TYPES const char * spa_type_audio_channel_to_short_name(uint32
 }  /* extern "C" */
 #endif
 
-#endif /* SPA_AUDIO_RAW_RAW_TYPES_H */
+#endif /* SPA_AUDIO_RAW_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw.h
index 462cf58a13c..df1d271736a 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/raw.h
@@ -5,20 +5,24 @@
 #ifndef SPA_AUDIO_RAW_H
 #define SPA_AUDIO_RAW_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
  * \addtogroup spa_param
  * \{
  */
 
+/* This is the max number of channels, changing this will change the
+ * size of some helper structures. This value should be at least 64 */
+#ifndef SPA_AUDIO_MAX_CHANNELS
 #define SPA_AUDIO_MAX_CHANNELS    64u
+#endif
 
 enum spa_audio_format {
     SPA_AUDIO_FORMAT_UNKNOWN,
@@ -152,41 +156,42 @@ enum spa_audio_channel {
 
     SPA_AUDIO_CHANNEL_MONO,         /**< mono stream */
 
-    SPA_AUDIO_CHANNEL_FL,           /**< front left */
-    SPA_AUDIO_CHANNEL_FR,           /**< front right */
-    SPA_AUDIO_CHANNEL_FC,           /**< front center */
-    SPA_AUDIO_CHANNEL_LFE,          /**< LFE */
-    SPA_AUDIO_CHANNEL_SL,           /**< side left */
-    SPA_AUDIO_CHANNEL_SR,           /**< side right */
-    SPA_AUDIO_CHANNEL_FLC,          /**< front left center */
-    SPA_AUDIO_CHANNEL_FRC,          /**< front right center */
-    SPA_AUDIO_CHANNEL_RC,           /**< rear center */
-    SPA_AUDIO_CHANNEL_RL,           /**< rear left */
-    SPA_AUDIO_CHANNEL_RR,           /**< rear right */
-    SPA_AUDIO_CHANNEL_TC,           /**< top center */
-    SPA_AUDIO_CHANNEL_TFL,          /**< top front left */
-    SPA_AUDIO_CHANNEL_TFC,          /**< top front center */
-    SPA_AUDIO_CHANNEL_TFR,          /**< top front right */
-    SPA_AUDIO_CHANNEL_TRL,          /**< top rear left */
-    SPA_AUDIO_CHANNEL_TRC,          /**< top rear center */
-    SPA_AUDIO_CHANNEL_TRR,          /**< top rear right */
-    SPA_AUDIO_CHANNEL_RLC,          /**< rear left center */
-    SPA_AUDIO_CHANNEL_RRC,          /**< rear right center */
-    SPA_AUDIO_CHANNEL_FLW,          /**< front left wide */
-    SPA_AUDIO_CHANNEL_FRW,          /**< front right wide */
-    SPA_AUDIO_CHANNEL_LFE2,        /**< LFE 2 */
-    SPA_AUDIO_CHANNEL_FLH,          /**< front left high */
-    SPA_AUDIO_CHANNEL_FCH,          /**< front center high */
-    SPA_AUDIO_CHANNEL_FRH,          /**< front right high */
-    SPA_AUDIO_CHANNEL_TFLC,         /**< top front left center */
-    SPA_AUDIO_CHANNEL_TFRC,         /**< top front right center */
-    SPA_AUDIO_CHANNEL_TSL,          /**< top side left */
-    SPA_AUDIO_CHANNEL_TSR,          /**< top side right */
-    SPA_AUDIO_CHANNEL_LLFE,         /**< left LFE */
-    SPA_AUDIO_CHANNEL_RLFE,         /**< right LFE */
-    SPA_AUDIO_CHANNEL_BC,           /**< bottom center */
-    SPA_AUDIO_CHANNEL_BLC,          /**< bottom left center */
-    SPA_AUDIO_CHANNEL_BRC,          /**< bottom right center */
+    /**                                                        Azimuth Elevation */
+    SPA_AUDIO_CHANNEL_FL,           /**< front left               30       0     */
+    SPA_AUDIO_CHANNEL_FR,           /**< front right             -30       0     */
+    SPA_AUDIO_CHANNEL_FC,           /**< front center              0       0     */
+    SPA_AUDIO_CHANNEL_LFE,          /**< LFE                       0     -30     */
+    SPA_AUDIO_CHANNEL_SL,           /**< side left                90       0     */
+    SPA_AUDIO_CHANNEL_SR,           /**< side right              -90       0     */
+    SPA_AUDIO_CHANNEL_FLC,          /**< front left center        22.5     0     */
+    SPA_AUDIO_CHANNEL_FRC,          /**< front right center      -22.5     0     */
+    SPA_AUDIO_CHANNEL_RC,           /**< rear center             180       0     */
+    SPA_AUDIO_CHANNEL_RL,           /**< rear left               110       0     */
+    SPA_AUDIO_CHANNEL_RR,           /**< rear right             -110       0     */
+    SPA_AUDIO_CHANNEL_TC,           /**< top center                0      90     */
+    SPA_AUDIO_CHANNEL_TFL,          /**< top front left           30      30     */
+    SPA_AUDIO_CHANNEL_TFC,          /**< top front center          0      30     */
+    SPA_AUDIO_CHANNEL_TFR,          /**< top front right         -30      30     */
+    SPA_AUDIO_CHANNEL_TRL,          /**< top rear left           110      30     */
+    SPA_AUDIO_CHANNEL_TRC,          /**< top rear center         180      30     */
+    SPA_AUDIO_CHANNEL_TRR,          /**< top rear right         -110      30     */
+    SPA_AUDIO_CHANNEL_RLC,          /**< rear left center        135       0     */
+    SPA_AUDIO_CHANNEL_RRC,          /**< rear right center      -135       0     */
+    SPA_AUDIO_CHANNEL_FLW,          /**< front left wide          60       0     */
+    SPA_AUDIO_CHANNEL_FRW,          /**< front right wide        -60       0     */
+    SPA_AUDIO_CHANNEL_LFE2,        /**< LFE 2                     0     -30     */
+    SPA_AUDIO_CHANNEL_FLH,          /**< front left high         22.5     30     */
+    SPA_AUDIO_CHANNEL_FCH,          /**< front center high        0       30     */
+    SPA_AUDIO_CHANNEL_FRH,          /**< front right high       -22.5     30     */
+    SPA_AUDIO_CHANNEL_TFLC,         /**< top front left center    45      30     */
+    SPA_AUDIO_CHANNEL_TFRC,         /**< top front right center  -45      30     */
+    SPA_AUDIO_CHANNEL_TSL,          /**< top side left            90       0     */
+    SPA_AUDIO_CHANNEL_TSR,          /**< top side right          -90       0     */
+    SPA_AUDIO_CHANNEL_LLFE,         /**< left LFE                 45     -30     */
+    SPA_AUDIO_CHANNEL_RLFE,         /**< right LFE               -45     -30     */
+    SPA_AUDIO_CHANNEL_BC,           /**< bottom center             0     -30     */
+    SPA_AUDIO_CHANNEL_BLC,          /**< bottom left center       45     -30     */
+    SPA_AUDIO_CHANNEL_BRC,          /**< bottom right center     -45     -30     */
 
     SPA_AUDIO_CHANNEL_START_Aux    = 0x1000,    /**< aux channels */
     SPA_AUDIO_CHANNEL_AUX0 = SPA_AUDIO_CHANNEL_START_Aux,
@@ -259,6 +264,8 @@ enum spa_audio_channel {
     SPA_AUDIO_CHANNEL_START_Custom    = 0x10000,
 };
 
+#define SPA_AUDIO_CHANNEL_IS_AUX(ch)    ((ch)>=SPA_AUDIO_CHANNEL_START_Aux && (ch)<=SPA_AUDIO_CHANNEL_LAST_Aux)
+
 enum spa_audio_volume_ramp_scale {
     SPA_AUDIO_VOLUME_RAMP_INVALID,
     SPA_AUDIO_VOLUME_RAMP_LINEAR,
@@ -269,23 +276,34 @@ enum spa_audio_volume_ramp_scale {
 #define SPA_AUDIO_FLAG_NONE        (0)        /*< no valid flag */
 #define SPA_AUDIO_FLAG_UNPOSITIONED    (1 << 0)    /*< the position array explicitly
                              *  contains unpositioned channels. */
-/** Audio information description */
+/** Audio information description. You can assume when you receive this structure
+ * that there is enought padding to accomodate all channel positions in case the
+ * channel count is more than SPA_AUDIO_MAX_CHANNELS. */
 struct spa_audio_info_raw {
     enum spa_audio_format format;        /*< format, one of enum spa_audio_format */
     uint32_t flags;                /*< extra flags */
     uint32_t rate;                /*< sample rate */
-    uint32_t channels;            /*< number of channels */
+    uint32_t channels;            /*< number of channels. This can be more than SPA_AUDIO_MAX_CHANNELS
+                         *  and you may assume there is enough padding for the extra
+                         *  channel positions. */
     uint32_t position[SPA_AUDIO_MAX_CHANNELS];    /*< channel position from enum spa_audio_channel */
+    /* padding follows here when channels > SPA_AUDIO_MAX_CHANNELS */
 };
 
 #define SPA_AUDIO_INFO_RAW_INIT(...)        ((struct spa_audio_info_raw) { __VA_ARGS__ })
 
+#define SPA_AUDIO_INFO_RAW_MAX_POSITION(size)    (((size)-offsetof(struct spa_audio_info_raw,position))/sizeof(uint32_t))
+
+#define SPA_AUDIO_INFO_RAW_VALID_SIZE(size)    ((size) >= offsetof(struct spa_audio_info_raw, position))
+
+
 #define SPA_KEY_AUDIO_FORMAT        "audio.format"        /**< an audio format as string,
                                   *  Ex. "S16LE" */
 #define SPA_KEY_AUDIO_CHANNEL        "audio.channel"        /**< an audio channel as string,
                                   *  Ex. "FL" */
 #define SPA_KEY_AUDIO_CHANNELS        "audio.channels"    /**< an audio channel count as int */
 #define SPA_KEY_AUDIO_RATE        "audio.rate"        /**< an audio sample rate as int */
+#define SPA_KEY_AUDIO_LAYOUT        "audio.layout"        /**< channel positions as predefined layout */
 #define SPA_KEY_AUDIO_POSITION        "audio.position"    /**< channel positions as comma separated list
                                   *  of channels ex. "FL,FR" */
 #define SPA_KEY_AUDIO_ALLOWED_RATES    "audio.allowed-rates"    /**< a list of allowed samplerates
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/type-info.h
index 8a3aa49aabf..3c5d6f4c724 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/type-info.h
@@ -6,10 +6,12 @@
 #define SPA_AUDIO_TYPES_H
 
 #include 
+#include 
 #include 
 #include 
 #include 
 #include 
 #include 
+#include 
 
 #endif /* SPA_AUDIO_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma-types.h
index 78ce1b98773..11b03fc95d2 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma-types.h
@@ -5,13 +5,13 @@
 #ifndef SPA_AUDIO_WMA_TYPES_H
 #define SPA_AUDIO_WMA_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma.h
index 4f86efe84b7..a970f0d276d 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/audio/wma.h
@@ -5,12 +5,12 @@
 #ifndef SPA_AUDIO_WMA_H
 #define SPA_AUDIO_WMA_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /**
  * \addtogroup spa_param
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/audio.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/audio.h
index 13590545ed7..0b3ee8d00e3 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/audio.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/audio.h
@@ -41,6 +41,7 @@ enum spa_bluetooth_audio_codec {
     SPA_BLUETOOTH_AUDIO_CODEC_CVSD = 0x100,
     SPA_BLUETOOTH_AUDIO_CODEC_MSBC,
     SPA_BLUETOOTH_AUDIO_CODEC_LC3_SWB,
+    SPA_BLUETOOTH_AUDIO_CODEC_LC3_A127,
 
     /* BAP */
     SPA_BLUETOOTH_AUDIO_CODEC_LC3 = 0x200,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/type-info.h
index 2affa465b45..5e023466a13 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/bluetooth/type-info.h
@@ -5,6 +5,8 @@
 #ifndef SPA_BLUETOOTH_TYPES_H
 #define SPA_BLUETOOTH_TYPES_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 #define SPA_TYPE_INFO_BluetoothAudioCodec        SPA_TYPE_INFO_ENUM_BASE "BluetoothAudioCodec"
 #define SPA_TYPE_INFO_BLUETOOTH_AUDIO_CODEC_BASE    SPA_TYPE_INFO_BluetoothAudioCodec ":"
 
@@ -44,6 +44,7 @@ static const struct spa_type_info spa_type_bluetooth_audio_codec[] = {
     { SPA_BLUETOOTH_AUDIO_CODEC_CVSD, SPA_TYPE_Int, SPA_TYPE_INFO_BLUETOOTH_AUDIO_CODEC_BASE "cvsd", NULL },
     { SPA_BLUETOOTH_AUDIO_CODEC_MSBC, SPA_TYPE_Int, SPA_TYPE_INFO_BLUETOOTH_AUDIO_CODEC_BASE "msbc", NULL },
     { SPA_BLUETOOTH_AUDIO_CODEC_LC3_SWB, SPA_TYPE_Int, SPA_TYPE_INFO_BLUETOOTH_AUDIO_CODEC_BASE "lc3_swb", NULL },
+    { SPA_BLUETOOTH_AUDIO_CODEC_LC3_A127, SPA_TYPE_Int, SPA_TYPE_INFO_BLUETOOTH_AUDIO_CODEC_BASE "lc3_a127", NULL },
 
     { SPA_BLUETOOTH_AUDIO_CODEC_LC3, SPA_TYPE_Int, SPA_TYPE_INFO_BLUETOOTH_AUDIO_CODEC_BASE "lc3", NULL },
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers-types.h
index a963193a60c..dc8a1ee7fbe 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers-types.h
@@ -5,6 +5,11 @@
 #ifndef SPA_PARAM_BUFFERS_TYPES_H
 #define SPA_PARAM_BUFFERS_TYPES_H
 
+#include 
+#include 
+
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,11 +19,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-
-#include 
-
 #define SPA_TYPE_INFO_PARAM_Meta        SPA_TYPE_INFO_PARAM_BASE "Meta"
 #define SPA_TYPE_INFO_PARAM_META_BASE        SPA_TYPE_INFO_PARAM_Meta ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers.h
index eb8c107337e..5f670e456d7 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/buffers.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_BUFFERS_H
 #define SPA_PARAM_BUFFERS_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** properties for SPA_TYPE_OBJECT_ParamBuffers */
 enum spa_param_buffers {
     SPA_PARAM_BUFFERS_START,
@@ -33,6 +33,7 @@ enum spa_param_meta {
     SPA_PARAM_META_START,
     SPA_PARAM_META_type,        /**< the metadata, one of enum spa_meta_type (Id enum spa_meta_type) */
     SPA_PARAM_META_size,        /**< the expected maximum size the meta (Int) */
+    SPA_PARAM_META_features,    /**< meta data features (Features Int) */
 };
 
 /** properties for SPA_TYPE_OBJECT_ParamIO */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/dict-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/dict-types.h
new file mode 100644
index 00000000000..c44a8d8c8d2
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/dict-types.h
@@ -0,0 +1,38 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2018 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_PARAM_DICT_TYPES_H
+#define SPA_PARAM_DICT_TYPES_H
+
+#include 
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+#define SPA_TYPE_INFO_PARAM_Dict    SPA_TYPE_INFO_PARAM_BASE "Dict"
+#define SPA_TYPE_INFO_PARAM_DICT_BASE    SPA_TYPE_INFO_PARAM_Dict ":"
+
+static const struct spa_type_info spa_type_param_dict[] = {
+    { SPA_PARAM_DICT_START, SPA_TYPE_Id, SPA_TYPE_INFO_PARAM_DICT_BASE, spa_type_param, },
+    { SPA_PARAM_DICT_info, SPA_TYPE_Struct, SPA_TYPE_INFO_PARAM_DICT_BASE "info", NULL, },
+    { 0, 0, NULL, NULL },
+};
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_PARAM_DICT_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/dict.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/dict.h
new file mode 100644
index 00000000000..ae399efda5d
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/dict.h
@@ -0,0 +1,42 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_PARAM_DICT_H
+#define SPA_PARAM_DICT_H
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+/** properties for SPA_TYPE_OBJECT_ParamDict */
+enum spa_param_dict {
+    SPA_PARAM_DICT_START,
+    SPA_PARAM_DICT_info,        /**< Struct(
+                      *      Int: n_items
+                      *      (String: key
+                      *       String: value)*
+                      *  ) */
+};
+
+/** helper structure for managing info objects */
+struct spa_param_dict_info {
+    const struct spa_pod *info;
+};
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_PARAM_DICT_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/format-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/format-types.h
index a02aa3c4c3e..b9a9af133dd 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/format-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/format-types.h
@@ -5,6 +5,13 @@
 #ifndef SPA_PARAM_FORMAT_TYPES_H
 #define SPA_PARAM_FORMAT_TYPES_H
 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,12 +21,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-
-#include 
-#include 
-
 #define SPA_TYPE_INFO_Format            SPA_TYPE_INFO_PARAM_BASE "Format"
 #define SPA_TYPE_INFO_FORMAT_BASE        SPA_TYPE_INFO_Format ":"
 
@@ -64,6 +65,11 @@ static const struct spa_type_info spa_type_media_subtype[] = {
     { SPA_MEDIA_SUBTYPE_flac, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "flac", NULL },
     { SPA_MEDIA_SUBTYPE_ape, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "ape", NULL },
     { SPA_MEDIA_SUBTYPE_opus, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "opus", NULL },
+    { SPA_MEDIA_SUBTYPE_ac3, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "ac3", NULL },
+    { SPA_MEDIA_SUBTYPE_eac3, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "eac3", NULL },
+    { SPA_MEDIA_SUBTYPE_truehd, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "truehd", NULL },
+    { SPA_MEDIA_SUBTYPE_dts, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "dts", NULL },
+    { SPA_MEDIA_SUBTYPE_mpegh, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "mpegh", NULL },
     /* video subtypes */
     { SPA_MEDIA_SUBTYPE_h264, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "h264", NULL },
     { SPA_MEDIA_SUBTYPE_mjpg, SPA_TYPE_Int, SPA_TYPE_INFO_MEDIA_SUBTYPE_BASE "mjpg", NULL },
@@ -96,6 +102,10 @@ static const struct spa_type_info spa_type_media_subtype[] = {
 #define SPA_TYPE_INFO_FORMAT_AUDIO_WMA_BASE    SPA_TYPE_INFO_FORMAT_AUDIO_WMA ":"
 #define SPA_TYPE_INFO_FORMAT_AUDIO_AMR        SPA_TYPE_INFO_FORMAT_AUDIO_BASE "AMR"
 #define SPA_TYPE_INFO_FORMAT_AUDIO_AMR_BASE    SPA_TYPE_INFO_FORMAT_AUDIO_AMR ":"
+#define SPA_TYPE_INFO_FORMAT_AUDIO_MP3        SPA_TYPE_INFO_FORMAT_AUDIO_BASE "MP3"
+#define SPA_TYPE_INFO_FORMAT_AUDIO_MP3_BASE    SPA_TYPE_INFO_FORMAT_AUDIO_MP3 ":"
+#define SPA_TYPE_INFO_FORMAT_AUDIO_DTS        SPA_TYPE_INFO_FORMAT_AUDIO_BASE "DTS"
+#define SPA_TYPE_INFO_FORMAT_AUDIO_DTS_BASE    SPA_TYPE_INFO_FORMAT_AUDIO_DTS ":"
 
 #define SPA_TYPE_INFO_FormatVideo        SPA_TYPE_INFO_FORMAT_BASE "Video"
 #define SPA_TYPE_INFO_FORMAT_VIDEO_BASE        SPA_TYPE_INFO_FormatVideo ":"
@@ -103,6 +113,9 @@ static const struct spa_type_info spa_type_media_subtype[] = {
 #define SPA_TYPE_INFO_FORMAT_VIDEO_H264        SPA_TYPE_INFO_FORMAT_VIDEO_BASE "H264"
 #define SPA_TYPE_INFO_FORMAT_VIDEO_H264_BASE    SPA_TYPE_INFO_FORMAT_VIDEO_H264 ":"
 
+#define SPA_TYPE_INFO_FormatControl        SPA_TYPE_INFO_FORMAT_BASE "Control"
+#define SPA_TYPE_INFO_FORMAT_CONTROL_BASE    SPA_TYPE_INFO_FormatControl ":"
+
 static const struct spa_type_info spa_type_format[] = {
     { SPA_FORMAT_START, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_BASE, spa_type_param, },
 
@@ -135,6 +148,10 @@ static const struct spa_type_info spa_type_format[] = {
         spa_type_audio_wma_profile },
     { SPA_FORMAT_AUDIO_AMR_bandMode, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_AUDIO_AMR_BASE "bandMode",
         spa_type_audio_amr_band_mode },
+    { SPA_FORMAT_AUDIO_MP3_channelMode, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_AUDIO_MP3_BASE "channelMode",
+        spa_type_audio_mp3_channel_mode },
+    { SPA_FORMAT_AUDIO_DTS_extType, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_AUDIO_DTS_BASE "extType",
+        spa_type_audio_dts_ext_type },
 
     { SPA_FORMAT_VIDEO_format, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "format",
         spa_type_video_format, },
@@ -149,15 +166,23 @@ static const struct spa_type_info spa_type_format[] = {
     { SPA_FORMAT_VIDEO_multiviewMode, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "multiviewMode", NULL },
     { SPA_FORMAT_VIDEO_multiviewFlags, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "multiviewFlags", NULL },
     { SPA_FORMAT_VIDEO_chromaSite, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "chromaSite", NULL },
-    { SPA_FORMAT_VIDEO_colorRange, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "colorRange", NULL },
-    { SPA_FORMAT_VIDEO_colorMatrix, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "colorMatrix", NULL },
-    { SPA_FORMAT_VIDEO_transferFunction, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "transferFunction", NULL },
-    { SPA_FORMAT_VIDEO_colorPrimaries, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "colorPrimaries", NULL },
+    { SPA_FORMAT_VIDEO_colorRange, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "colorRange",
+        spa_type_video_color_range, },
+    { SPA_FORMAT_VIDEO_colorMatrix, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "colorMatrix",
+        spa_type_video_color_matrix, },
+    { SPA_FORMAT_VIDEO_transferFunction, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "transferFunction",
+        spa_type_video_transfer_function, },
+    { SPA_FORMAT_VIDEO_colorPrimaries, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "colorPrimaries",
+        spa_type_video_color_primaries, },
     { SPA_FORMAT_VIDEO_profile, SPA_TYPE_Int, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "profile", NULL },
     { SPA_FORMAT_VIDEO_level, SPA_TYPE_Int, SPA_TYPE_INFO_FORMAT_VIDEO_BASE "level", NULL },
 
     { SPA_FORMAT_VIDEO_H264_streamFormat, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_H264_BASE "streamFormat", NULL },
     { SPA_FORMAT_VIDEO_H264_alignment, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_VIDEO_H264_BASE "alignment", NULL },
+
+    { SPA_FORMAT_CONTROL_types, SPA_TYPE_Id, SPA_TYPE_INFO_FORMAT_CONTROL_BASE "types", spa_type_control },
+
+    { SPA_FORMAT_VIDEO_deviceId, SPA_TYPE_Bytes, SPA_TYPE_INFO_FORMAT_BASE "deviceId", NULL },
     { 0, 0, NULL, NULL },
 };
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/format-utils.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/format-utils.h
index b829209351d..73238660ce0 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/format-utils.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/format-utils.h
@@ -5,6 +5,9 @@
 #ifndef SPA_PARAM_FORMAT_UTILS_H
 #define SPA_PARAM_FORMAT_UTILS_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -15,9 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-
 #ifndef SPA_API_FORMAT_UTILS
  #ifdef SPA_API_IMPL
   #define SPA_API_FORMAT_UTILS SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/format.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/format.h
index 7de2775ca44..bfb13bb371d 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/format.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/format.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_FORMAT_H
 #define SPA_PARAM_FORMAT_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** media type for SPA_TYPE_OBJECT_Format */
 enum spa_media_type {
     SPA_MEDIA_TYPE_unknown,
@@ -52,6 +52,11 @@ enum spa_media_subtype {
     SPA_MEDIA_SUBTYPE_flac,        /** since 0.3.65 */
     SPA_MEDIA_SUBTYPE_ape,        /** since 0.3.65 */
     SPA_MEDIA_SUBTYPE_opus,        /** since 0.3.68 */
+    SPA_MEDIA_SUBTYPE_ac3,        /** since 1.5.1 */
+    SPA_MEDIA_SUBTYPE_eac3,        /** since 1.5.1 */
+    SPA_MEDIA_SUBTYPE_truehd,    /** since 1.5.1 */
+    SPA_MEDIA_SUBTYPE_dts,        /** since 1.5.1 */
+    SPA_MEDIA_SUBTYPE_mpegh,    /** since 1.5.1 */
 
     SPA_MEDIA_SUBTYPE_START_Video    = 0x20000,
     SPA_MEDIA_SUBTYPE_h264,
@@ -67,6 +72,7 @@ enum spa_media_subtype {
     SPA_MEDIA_SUBTYPE_vp8,
     SPA_MEDIA_SUBTYPE_vp9,
     SPA_MEDIA_SUBTYPE_bayer,
+    SPA_MEDIA_SUBTYPE_h265,
 
     SPA_MEDIA_SUBTYPE_START_Image    = 0x30000,
     SPA_MEDIA_SUBTYPE_jpeg,
@@ -109,6 +115,10 @@ enum spa_format {
 
     SPA_FORMAT_AUDIO_AMR_bandMode,        /**< AMR band mode (Id enum spa_audio_amr_band_mode) */
 
+    SPA_FORMAT_AUDIO_MP3_channelMode,    /**< MP3 channel mode, (Id enum spa_audio_mp3_channel_mode) */
+
+    SPA_FORMAT_AUDIO_DTS_extType,        /**< DTS extension type (Id enum spa_audio_dts_ext_type) */
+
 
     /* Video Format keys */
     SPA_FORMAT_START_Video = 0x20000,
@@ -132,6 +142,9 @@ enum spa_format {
     SPA_FORMAT_VIDEO_level,            /**< (Int) */
     SPA_FORMAT_VIDEO_H264_streamFormat,    /**< (Id enum spa_h264_stream_format) */
     SPA_FORMAT_VIDEO_H264_alignment,    /**< (Id enum spa_h264_alignment) */
+    SPA_FORMAT_VIDEO_H265_streamFormat,    /**< (Id enum spa_h265_stream_format) */
+    SPA_FORMAT_VIDEO_H265_alignment,    /**< (Id enum spa_h265_alignment) */
+    SPA_FORMAT_VIDEO_deviceId,            /**< dev_t identifier (Bytes) */
 
     /* Image Format keys */
     SPA_FORMAT_START_Image = 0x30000,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/latency-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/latency-types.h
index 6b9822bad35..efc55c9f413 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/latency-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/latency-types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_PARAM_LATENCY_TYPES_H
 #define SPA_PARAM_LATENCY_TYPES_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #define SPA_TYPE_INFO_PARAM_Latency        SPA_TYPE_INFO_PARAM_BASE "Latency"
 #define SPA_TYPE_INFO_PARAM_LATENCY_BASE    SPA_TYPE_INFO_PARAM_Latency ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/latency.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/latency.h
index 2d567f79eb2..91eedccd30d 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/latency.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/latency.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_LATENY_H
 #define SPA_PARAM_LATENY_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /**
  * Properties for SPA_TYPE_OBJECT_ParamLatency
  *
@@ -57,6 +57,10 @@ struct spa_latency_info {
 };
 
 #define SPA_LATENCY_INFO(dir,...) ((struct spa_latency_info) { .direction = (dir), ## __VA_ARGS__ })
+#define SPA_LATENCY_INFO_UNSET(dir) SPA_LATENCY_INFO(dir,     \
+        .min_quantum = FLT_MAX, .max_quantum = FLT_MIN,    \
+        .min_rate = INT32_MAX, .max_rate = INT32_MIN,    \
+        .min_ns = INT64_MAX, .max_ns = INT64_MIN)
 
 /**
  * Properties for SPA_TYPE_OBJECT_ParamProcessLatency
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/param-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/param-types.h
index b996666d2b2..4610fe6fb4a 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/param-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/param-types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_PARAM_TYPES_H
 #define SPA_PARAM_TYPES_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 /* base for parameter object enumerations */
 #define SPA_TYPE_INFO_ParamId        SPA_TYPE_INFO_ENUM_BASE "ParamId"
 #define SPA_TYPE_INFO_PARAM_ID_BASE    SPA_TYPE_INFO_ParamId ":"
@@ -41,6 +41,9 @@ static const struct spa_type_info spa_type_param[] = {
     { SPA_PARAM_Latency, SPA_TYPE_OBJECT_ParamLatency, SPA_TYPE_INFO_PARAM_ID_BASE "Latency", NULL },
     { SPA_PARAM_ProcessLatency, SPA_TYPE_OBJECT_ParamProcessLatency, SPA_TYPE_INFO_PARAM_ID_BASE "ProcessLatency", NULL },
     { SPA_PARAM_Tag, SPA_TYPE_OBJECT_ParamTag, SPA_TYPE_INFO_PARAM_ID_BASE "Tag", NULL },
+    { SPA_PARAM_PeerEnumFormat, SPA_TYPE_OBJECT_PeerParam, SPA_TYPE_INFO_PARAM_ID_BASE "PeerEnumFormat", NULL },
+    { SPA_PARAM_Capability, SPA_TYPE_OBJECT_ParamDict, SPA_TYPE_INFO_PARAM_ID_BASE "Capability", NULL },
+    { SPA_PARAM_PeerCapability, SPA_TYPE_OBJECT_PeerParam, SPA_TYPE_INFO_PARAM_ID_BASE "PeerCapability", NULL },
     { 0, 0, NULL, NULL },
 };
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/param.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/param.h
index aac55b73591..27b09d97636 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/param.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/param.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_H
 #define SPA_PARAM_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -18,8 +20,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** different parameter types that can be queried */
 enum spa_param_type {
     SPA_PARAM_Invalid,        /**< invalid */
@@ -40,6 +40,11 @@ enum spa_param_type {
     SPA_PARAM_Latency,        /**< latency reporting, a SPA_TYPE_OBJECT_ParamLatency */
     SPA_PARAM_ProcessLatency,    /**< processing latency, a SPA_TYPE_OBJECT_ParamProcessLatency */
     SPA_PARAM_Tag,            /**< tag reporting, a SPA_TYPE_OBJECT_ParamTag. Since 0.3.79 */
+    SPA_PARAM_PeerEnumFormat,    /**< peer formats, a SPA_TYPE_OBJECT_PeerParam with
+                      *  SPA_TYPE_OBJECT_Format. Since 1.5.0 */
+    SPA_PARAM_Capability,        /**< capability info, a SPA_TYPE_OBJECT_ParamDict, Since 1.5.84 */
+    SPA_PARAM_PeerCapability,    /**< peer capabilities, a SPA_TYPE_OBJECT_PeerParam with
+                      *  SPA_TYPE_OBJECT_ParamDict, since 1.5.84 */
 };
 
 /** information about a parameter */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/peer-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/peer-types.h
new file mode 100644
index 00000000000..bae2447b9e7
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/peer-types.h
@@ -0,0 +1,38 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2018 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_PARAM_PEER_TYPES_H
+#define SPA_PARAM_PEER_TYPES_H
+
+#include 
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+#define SPA_TYPE_INFO_PeerParam        SPA_TYPE_INFO_OBJECT_BASE "PeerParam"
+#define SPA_TYPE_INFO_PEER_PARAM_BASE    SPA_TYPE_INFO_PeerParam ":"
+
+static const struct spa_type_info spa_type_peer_param[] = {
+    { SPA_PEER_PARAM_START, SPA_TYPE_Id, SPA_TYPE_INFO_PEER_PARAM_BASE, spa_type_param, },
+    { SPA_ID_INVALID, SPA_TYPE_Id, SPA_TYPE_INFO_PEER_PARAM_BASE, NULL, },
+    { 0, 0, NULL, NULL },
+};
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_PARAM_PEER_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/peer.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/peer.h
new file mode 100644
index 00000000000..e69c866dad2
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/peer.h
@@ -0,0 +1,37 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_PARAM_PEER_PARAM_H
+#define SPA_PARAM_PEER_PARAM_H
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+/** properties for SPA_TYPE_OBJECT_PeerParam */
+enum spa_peer_param {
+    SPA_PEER_PARAM_START,    /**< id of peer as key, SPA_TYPE_Pod as value */
+    SPA_PEER_PARAM_END = 0xfffffffe,
+};
+
+struct spa_peer_param_info {
+    uint32_t peer_id;
+    const struct spa_pod *param;
+};
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_PARAM_PEER_PARAM_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config-types.h
index b25d9ced193..35adcf78bbc 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config-types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_PARAM_PORT_CONFIG_TYPES_H
 #define SPA_PARAM_PORT_CONFIG_TYPES_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #define SPA_TYPE_INFO_ParamPortConfigMode        SPA_TYPE_INFO_ENUM_BASE "ParamPortConfigMode"
 #define SPA_TYPE_INFO_PARAM_PORT_CONFIG_MODE_BASE    SPA_TYPE_INFO_ParamPortConfigMode ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config.h
index ab77a183414..d1eed691982 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/port-config.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_PORT_CONFIG_H
 #define SPA_PARAM_PORT_CONFIG_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 enum spa_param_port_config_mode {
     SPA_PARAM_PORT_CONFIG_MODE_none,    /**< no configuration */
     SPA_PARAM_PORT_CONFIG_MODE_passthrough,    /**< passthrough configuration */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/profile-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/profile-types.h
index 1176a0dd5a3..1ff9efc557d 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/profile-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/profile-types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_PARAM_PROFILE_TYPES_H
 #define SPA_PARAM_PROFILE_TYPES_H
 
+#include 
+
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
-#include 
-
 #define SPA_TYPE_INFO_PARAM_Profile        SPA_TYPE_INFO_PARAM_BASE "Profile"
 #define SPA_TYPE_INFO_PARAM_PROFILE_BASE    SPA_TYPE_INFO_PARAM_Profile ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/profile.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/profile.h
index c31b714d17e..448d4d3c934 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/profile.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/profile.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_PROFILE_H
 #define SPA_PARAM_PROFILE_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** properties for SPA_TYPE_OBJECT_ParamProfile */
 enum spa_param_profile {
     SPA_PARAM_PROFILE_START,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler-types.h
index b87a125a416..888f8dbba2f 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler-types.h
@@ -5,6 +5,9 @@
 #ifndef SPA_PARAM_PROFILER_TYPES_H
 #define SPA_PARAM_PROFILER_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,9 +17,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-
 #define SPA_TYPE_INFO_Profiler        SPA_TYPE_INFO_OBJECT_BASE "Profiler"
 #define SPA_TYPE_INFO_PROFILER_BASE    SPA_TYPE_INFO_Profiler ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler.h
index 97e5431a7de..26750de78cb 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/profiler.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_PROFILER_H
 #define SPA_PARAM_PROFILER_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** properties for SPA_TYPE_OBJECT_Profiler */
 enum spa_profiler {
     SPA_PROFILER_START,
@@ -66,7 +66,8 @@ enum spa_profiler {
                               *      Long : finish,
                               *      Int : status,
                               *      Fraction : latency,
-                              *      Int : xrun_count))  */
+                              *      Int : xrun_count))
+                              *      Bool : async))  */
     SPA_PROFILER_followerClock,            /**< follower clock information
                               *  (Struct(
                               *      Int : clock id,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/props-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/props-types.h
index e52f6c9a228..35d88c677bb 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/props-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/props-types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_PARAM_PROPS_TYPES_H
 #define SPA_PARAM_PROPS_TYPES_H
 
+#include 
+
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
-#include 
-
 /** Props Param */
 #define SPA_TYPE_INFO_Props            SPA_TYPE_INFO_PARAM_BASE "Props"
 #define SPA_TYPE_INFO_PROPS_BASE        SPA_TYPE_INFO_Props ":"
@@ -40,13 +40,16 @@ static const struct spa_type_info spa_type_props[] = {
     { SPA_PROP_quality, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "quality", NULL },
     { SPA_PROP_bluetoothAudioCodec, SPA_TYPE_Id, SPA_TYPE_INFO_PROPS_BASE "bluetoothAudioCodec", spa_type_bluetooth_audio_codec },
     { SPA_PROP_bluetoothOffloadActive, SPA_TYPE_Bool, SPA_TYPE_INFO_PROPS_BASE "bluetoothOffloadActive", NULL },
+    { SPA_PROP_clockId, SPA_TYPE_String, SPA_TYPE_INFO_PROPS_BASE "clockId", NULL },
+    { SPA_PROP_clockDevice, SPA_TYPE_String, SPA_TYPE_INFO_PROPS_BASE "clockDevice", NULL },
+    { SPA_PROP_clockInterface, SPA_TYPE_String, SPA_TYPE_INFO_PROPS_BASE "clockInterface", NULL },
 
-    { SPA_PROP_waveType, SPA_TYPE_Id, SPA_TYPE_INFO_PROPS_BASE "waveType", NULL },
+    { SPA_PROP_waveType, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "waveType", NULL },
     { SPA_PROP_frequency, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "frequency", NULL },
     { SPA_PROP_volume, SPA_TYPE_Float, SPA_TYPE_INFO_PROPS_BASE "volume", NULL },
     { SPA_PROP_mute, SPA_TYPE_Bool, SPA_TYPE_INFO_PROPS_BASE "mute", NULL },
-    { SPA_PROP_patternType, SPA_TYPE_Id, SPA_TYPE_INFO_PROPS_BASE "patternType", NULL },
-    { SPA_PROP_ditherType, SPA_TYPE_Id, SPA_TYPE_INFO_PROPS_BASE "ditherType", NULL },
+    { SPA_PROP_patternType, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "patternType", NULL },
+    { SPA_PROP_ditherType, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "ditherType", NULL },
     { SPA_PROP_truncate, SPA_TYPE_Bool, SPA_TYPE_INFO_PROPS_BASE "truncate", NULL },
     { SPA_PROP_channelVolumes, SPA_TYPE_Array, SPA_TYPE_INFO_PROPS_BASE "channelVolumes", spa_type_prop_float_array },
     { SPA_PROP_volumeBase, SPA_TYPE_Float, SPA_TYPE_INFO_PROPS_BASE "volumeBase", NULL },
@@ -62,7 +65,7 @@ static const struct spa_type_info spa_type_props[] = {
     { SPA_PROP_volumeRampStepSamples, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "volumeRampStepSamples", NULL },
     { SPA_PROP_volumeRampTime, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "volumeRampTime", NULL },
     { SPA_PROP_volumeRampStepTime, SPA_TYPE_Int, SPA_TYPE_INFO_PROPS_BASE "volumeRampStepTime", NULL },
-    { SPA_PROP_volumeRampScale, SPA_TYPE_Id, SPA_TYPE_INFO_PROPS_BASE "volumeRampScale", NULL },
+    { SPA_PROP_volumeRampScale, SPA_TYPE_Id, SPA_TYPE_INFO_PROPS_BASE "volumeRampScale", spa_type_audio_volume_ramp_scale },
 
     { SPA_PROP_brightness, SPA_TYPE_Float, SPA_TYPE_INFO_PROPS_BASE "brightness", NULL },
     { SPA_PROP_contrast, SPA_TYPE_Float, SPA_TYPE_INFO_PROPS_BASE "contrast", NULL },
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/props.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/props.h
index 2656c1087c7..9c9c2c303c2 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/props.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/props.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_PROPS_H
 #define SPA_PARAM_PROPS_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** properties of SPA_TYPE_OBJECT_PropInfo */
 enum spa_prop_info {
     SPA_PROP_INFO_START,
@@ -55,6 +55,9 @@ enum spa_prop {
     SPA_PROP_quality,
     SPA_PROP_bluetoothAudioCodec,
     SPA_PROP_bluetoothOffloadActive,
+    SPA_PROP_clockId,
+    SPA_PROP_clockDevice,
+    SPA_PROP_clockInterface,
 
     SPA_PROP_START_Audio    = 0x10000,    /**< audio related properties */
     SPA_PROP_waveType,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/route-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/route-types.h
index d7f2bf96b47..df46582b7ea 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/route-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/route-types.h
@@ -5,6 +5,11 @@
 #ifndef SPA_PARAM_ROUTE_TYPES_H
 #define SPA_PARAM_ROUTE_TYPES_H
 
+#include 
+#include 
+
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,11 +19,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-
-#include 
-
 #define SPA_TYPE_INFO_PARAM_Route        SPA_TYPE_INFO_PARAM_BASE "Route"
 #define SPA_TYPE_INFO_PARAM_ROUTE_BASE        SPA_TYPE_INFO_PARAM_Route ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/route.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/route.h
index ad4f7ff40bf..e2a1d2f91ab 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/route.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/route.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_ROUTE_H
 #define SPA_PARAM_ROUTE_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** properties for SPA_TYPE_OBJECT_ParamRoute */
 enum spa_param_route {
     SPA_PARAM_ROUTE_START,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/tag-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/tag-types.h
index 0a473ef9099..fb044ff07d9 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/tag-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/tag-types.h
@@ -5,6 +5,10 @@
 #ifndef SPA_PARAM_TAG_TYPES_H
 #define SPA_PARAM_TAG_TYPES_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #define SPA_TYPE_INFO_PARAM_Tag        SPA_TYPE_INFO_PARAM_BASE "Tag"
 #define SPA_TYPE_INFO_PARAM_TAG_BASE    SPA_TYPE_INFO_PARAM_Tag ":"
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/tag.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/tag.h
index 558da087dc7..8ad6f5ae992 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/tag.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/tag.h
@@ -5,6 +5,8 @@
 #ifndef SPA_PARAM_TAG_H
 #define SPA_PARAM_TAG_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 /** properties for SPA_TYPE_OBJECT_ParamTag */
 enum spa_param_tag {
     SPA_PARAM_TAG_START,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/type-info.h
index fee2d030a0a..ba39294a9eb 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/type-info.h
@@ -15,5 +15,7 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 
 #endif /* SPA_PARAM_TYPE_INFO_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/color-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/color-types.h
new file mode 100644
index 00000000000..d7ac0931c70
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/color-types.h
@@ -0,0 +1,79 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 PipeWire authors */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_VIDEO_COLOR_TYPES_H
+#define SPA_VIDEO_COLOR_TYPES_H
+
+#include 
+#include 
+
+#define SPA_TYPE_INFO_VideColorRange        SPA_TYPE_INFO_ENUM_BASE "VideoColorRange"
+#define SPA_TYPE_INFO_VIDEO_COLOR_RANGE_BASE    SPA_TYPE_INFO_VideColorRange ":"
+
+static const struct spa_type_info spa_type_video_color_range[] = {
+    { SPA_VIDEO_COLOR_RANGE_UNKNOWN, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_RANGE_BASE "unknown", NULL },
+    { SPA_VIDEO_COLOR_RANGE_0_255, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_RANGE_BASE "0-255", NULL },
+    { SPA_VIDEO_COLOR_RANGE_16_235, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_RANGE_BASE "16-235", NULL },
+    { 0, 0, NULL, NULL },
+};
+
+#define SPA_TYPE_INFO_VideoColorMatrix        SPA_TYPE_INFO_ENUM_BASE "VideoColorMatrix"
+#define SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE    SPA_TYPE_INFO_VideoColorMatrix ":"
+
+static const struct spa_type_info spa_type_video_color_matrix[] = {
+    { SPA_VIDEO_COLOR_MATRIX_UNKNOWN, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE "unknown", NULL },
+    { SPA_VIDEO_COLOR_MATRIX_RGB, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE "rgb", NULL },
+    { SPA_VIDEO_COLOR_MATRIX_FCC, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE "fcc", NULL },
+    { SPA_VIDEO_COLOR_MATRIX_BT709, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE "bt709", NULL },
+    { SPA_VIDEO_COLOR_MATRIX_BT601, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE "bt601", NULL },
+    { SPA_VIDEO_COLOR_MATRIX_SMPTE240M, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE "smpte240m", NULL },
+    { SPA_VIDEO_COLOR_MATRIX_BT2020, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_MATRIX_BASE "bt2020", NULL },
+    { 0, 0, NULL, NULL },
+};
+
+#define SPA_TYPE_INFO_VideoTransferFunction        SPA_TYPE_INFO_ENUM_BASE "VideoTransferFunction"
+#define SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE    SPA_TYPE_INFO_VideoTransferFunction ":"
+
+static const struct spa_type_info spa_type_video_transfer_function[] = {
+    { SPA_VIDEO_TRANSFER_UNKNOWN, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "unknown", NULL },
+    { SPA_VIDEO_TRANSFER_GAMMA10, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "gamma10", NULL },
+    { SPA_VIDEO_TRANSFER_GAMMA18, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "gamma18", NULL },
+    { SPA_VIDEO_TRANSFER_GAMMA20, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "gamma20", NULL },
+    { SPA_VIDEO_TRANSFER_GAMMA22, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "gamma22", NULL },
+    { SPA_VIDEO_TRANSFER_BT709, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "bt709", NULL },
+    { SPA_VIDEO_TRANSFER_SMPTE240M, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "smpte240m", NULL },
+    { SPA_VIDEO_TRANSFER_SRGB, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "srgb", NULL },
+    { SPA_VIDEO_TRANSFER_GAMMA28, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "gamma28", NULL },
+    { SPA_VIDEO_TRANSFER_LOG100, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "log100", NULL },
+    { SPA_VIDEO_TRANSFER_LOG316, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "log316", NULL },
+    { SPA_VIDEO_TRANSFER_BT2020_12, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "bt2020-12", NULL },
+    { SPA_VIDEO_TRANSFER_ADOBERGB, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "adobergb", NULL },
+    { SPA_VIDEO_TRANSFER_BT2020_10, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "bt2020-10", NULL },
+    { SPA_VIDEO_TRANSFER_SMPTE2084, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "smpte2084", NULL },
+    { SPA_VIDEO_TRANSFER_ARIB_STD_B67, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "arib-std-b67", NULL },
+    { SPA_VIDEO_TRANSFER_BT601, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_TRANSFER_FUNCTION_BASE "bt601", NULL },
+    { 0, 0, NULL, NULL },
+};
+
+#define SPA_TYPE_INFO_VideoColorPrimaries        SPA_TYPE_INFO_ENUM_BASE "VideoColorPrimaries"
+#define SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE    SPA_TYPE_INFO_VideoColorPrimaries ":"
+
+static const struct spa_type_info spa_type_video_color_primaries[] = {
+    { SPA_VIDEO_COLOR_PRIMARIES_UNKNOWN, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "unknown", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_BT709, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "bt709", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_BT470M, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "bt470m", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_BT470BG, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "bt470bg", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_SMPTE170M, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "smpte170m", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_SMPTE240M, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "smpte240m", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_FILM, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "film", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_BT2020, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "bt2020", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_ADOBERGB, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "adobergb", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_SMPTEST428, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "smptest428", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_SMPTERP431, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "smpterp431", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_SMPTEEG432, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "smpteeg432", NULL },
+    { SPA_VIDEO_COLOR_PRIMARIES_EBU3213, SPA_TYPE_Int, SPA_TYPE_INFO_VIDEO_COLOR_PRIMARIES_BASE "ebu3213", NULL },
+    { 0, 0, NULL, NULL },
+};
+
+#endif /* SPA_VIDEO_COLOR_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/color.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/color.h
index 0fdb968c841..bb049eb3259 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/color.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/color.h
@@ -36,7 +36,7 @@ enum spa_video_color_matrix {
     SPA_VIDEO_COLOR_MATRIX_BT709,        /**< ITU BT.709 color matrix */
     SPA_VIDEO_COLOR_MATRIX_BT601,        /**< ITU BT.601 color matrix */
     SPA_VIDEO_COLOR_MATRIX_SMPTE240M,    /**< SMTPE  240M color matrix */
-    SPA_VIDEO_COLOR_MATRIX_BT2020,        /**<  ITU-R BT.2020 color matrix. since 1.6. */
+    SPA_VIDEO_COLOR_MATRIX_BT2020,        /**<  ITU-R BT.2020 color matrix */
 };
 
 /**
@@ -57,8 +57,18 @@ enum spa_video_transfer_function {
     SPA_VIDEO_TRANSFER_LOG316,    /**< Logarithmic transfer characteristic 316.22777:1 range */
     SPA_VIDEO_TRANSFER_BT2020_12,    /**< Gamma 2.2 curve with a linear segment in the lower
                      *   range. Used for BT.2020 with 12 bits per
-                     *   component. \since 1.6. */
-    SPA_VIDEO_TRANSFER_ADOBERGB,    /**< Gamma 2.19921875. \since 1.8 */
+                     *   component */
+    SPA_VIDEO_TRANSFER_ADOBERGB,    /**< Gamma 2.19921875 */
+    SPA_VIDEO_TRANSFER_BT2020_10,    /**< Rec. ITU-R BT.2020-2 with 10 bits per component.
+                     *   (functionally the same as the values
+                     * SPA_VIDEO_TRANSFER_BT709 and SPA_VIDEO_TRANSFER_BT601) */
+    SPA_VIDEO_TRANSFER_SMPTE2084,    /**< SMPTE ST 2084 for 10, 12, 14, and 16-bit systems.
+                     * Known as perceptual quantization (PQ) */
+    SPA_VIDEO_TRANSFER_ARIB_STD_B67,/**< Association of Radio Industries and Businesses (ARIB)
+                     * STD-B67 and Rec. ITU-R BT.2100-1 hybrid loggamma (HLG) system */
+    SPA_VIDEO_TRANSFER_BT601,    /**< also known as SMPTE170M / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC
+                     * Functionally the same as the values
+                     * SPA_VIDEO_TRANSFER_BT709, and SPA_VIDEO_TRANSFER_BT2020_10 */
 };
 
 /**
@@ -73,8 +83,12 @@ enum spa_video_color_primaries {
     SPA_VIDEO_COLOR_PRIMARIES_SMPTE170M,    /**< SMPTE170M primaries */
     SPA_VIDEO_COLOR_PRIMARIES_SMPTE240M,    /**< SMPTE240M primaries */
     SPA_VIDEO_COLOR_PRIMARIES_FILM,        /**< Generic film */
-    SPA_VIDEO_COLOR_PRIMARIES_BT2020,    /**< BT2020 primaries. \since 1.6. */
-    SPA_VIDEO_COLOR_PRIMARIES_ADOBERGB,    /**< Adobe RGB primaries. \since 1.8 */
+    SPA_VIDEO_COLOR_PRIMARIES_BT2020,    /**< BT2020 primaries */
+    SPA_VIDEO_COLOR_PRIMARIES_ADOBERGB,    /**< Adobe RGB primaries */
+    SPA_VIDEO_COLOR_PRIMARIES_SMPTEST428,    /**< SMPTE ST 428 primaries (CIE 1931 XYZ) */
+    SPA_VIDEO_COLOR_PRIMARIES_SMPTERP431,    /**< SMPTE RP 431 primaries (ST 431-2 (2011) / DCI P3) */
+    SPA_VIDEO_COLOR_PRIMARIES_SMPTEEG432,    /**< SMPTE EG 432 primaries (ST 432-1 (2010) / P3 D65) */
+    SPA_VIDEO_COLOR_PRIMARIES_EBU3213,    /**< EBU 3213 primaries (JEDEC P22 phosphors) */
 };
 
 /**
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/dsp-utils.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/dsp-utils.h
index d8f075901e3..d40ec1558b3 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/dsp-utils.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/dsp-utils.h
@@ -5,6 +5,11 @@
 #ifndef SPA_VIDEO_DSP_UTILS_H
 #define SPA_VIDEO_DSP_UTILS_H
 
+#include 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +19,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #ifndef SPA_API_VIDEO_DSP_UTILS
  #ifdef SPA_API_IMPL
   #define SPA_API_VIDEO_DSP_UTILS SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format-utils.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format-utils.h
index 13495a473a3..9fb10db6e66 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format-utils.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format-utils.h
@@ -5,17 +5,18 @@
 #ifndef SPA_PARAM_VIDEO_FORMAT_UTILS_H
 #define SPA_PARAM_VIDEO_FORMAT_UTILS_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #ifndef SPA_API_VIDEO_FORMAT_UTILS
  #ifdef SPA_API_IMPL
   #define SPA_API_VIDEO_FORMAT_UTILS SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format.h
index b4daf69e030..e39b9fbc435 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/format.h
@@ -5,6 +5,11 @@
 #ifndef SPA_PARAM_VIDEO_FORMAT_H
 #define SPA_PARAM_VIDEO_FORMAT_H
 
+#include 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,11 +19,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-#include 
-
 struct spa_video_info {
     uint32_t media_type;
     uint32_t media_subtype;
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264-utils.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264-utils.h
index d15b4a0ee68..f3e0acd35a2 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264-utils.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264-utils.h
@@ -5,6 +5,10 @@
 #ifndef SPA_VIDEO_H264_UTILS_H
 #define SPA_VIDEO_H264_UTILS_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #ifndef SPA_API_VIDEO_H264_UTILS
  #ifdef SPA_API_IMPL
   #define SPA_API_VIDEO_H264_UTILS SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264.h
index b5071ff0a35..fa9f11b9f10 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h264.h
@@ -5,6 +5,8 @@
 #ifndef SPA_VIDEO_H264_H
 #define SPA_VIDEO_H264_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 enum spa_h264_stream_format {
     SPA_H264_STREAM_FORMAT_UNKNOWN = 0,
     SPA_H264_STREAM_FORMAT_AVC,
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265-utils.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265-utils.h
new file mode 100644
index 00000000000..6ccf04f764a
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265-utils.h
@@ -0,0 +1,79 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 Wim Taymans */
+/* SPDX-FileCopyrightText: Copyright © 2025 Arun Raghavan */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_VIDEO_H265_UTILS_H
+#define SPA_VIDEO_H265_UTILS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+#include 
+#include 
+#include 
+
+#ifndef SPA_API_VIDEO_H265_UTILS
+ #ifdef SPA_API_IMPL
+  #define SPA_API_VIDEO_H265_UTILS SPA_API_IMPL
+ #else
+  #define SPA_API_VIDEO_H265_UTILS static inline
+ #endif
+#endif
+
+SPA_API_VIDEO_H265_UTILS int
+spa_format_video_h265_parse(const struct spa_pod *format,
+                struct spa_video_info_h265 *info)
+{
+    return spa_pod_parse_object(format,
+            SPA_TYPE_OBJECT_Format, NULL,
+            SPA_FORMAT_VIDEO_size,            SPA_POD_OPT_Rectangle(&info->size),
+            SPA_FORMAT_VIDEO_framerate,        SPA_POD_OPT_Fraction(&info->framerate),
+            SPA_FORMAT_VIDEO_maxFramerate,        SPA_POD_OPT_Fraction(&info->max_framerate),
+            SPA_FORMAT_VIDEO_H265_streamFormat,    SPA_POD_OPT_Id(&info->stream_format),
+            SPA_FORMAT_VIDEO_H265_alignment,    SPA_POD_OPT_Id(&info->alignment));
+}
+
+SPA_API_VIDEO_H265_UTILS struct spa_pod *
+spa_format_video_h265_build(struct spa_pod_builder *builder, uint32_t id,
+                const struct spa_video_info_h265 *info)
+{
+    struct spa_pod_frame f;
+    spa_pod_builder_push_object(builder, &f, SPA_TYPE_OBJECT_Format, id);
+    spa_pod_builder_add(builder,
+            SPA_FORMAT_mediaType,        SPA_POD_Id(SPA_MEDIA_TYPE_video),
+            SPA_FORMAT_mediaSubtype,    SPA_POD_Id(SPA_MEDIA_SUBTYPE_h265),
+            0);
+    if (info->size.width != 0 && info->size.height != 0)
+        spa_pod_builder_add(builder,
+            SPA_FORMAT_VIDEO_size,        SPA_POD_Rectangle(&info->size), 0);
+    if (info->framerate.denom != 0)
+        spa_pod_builder_add(builder,
+            SPA_FORMAT_VIDEO_framerate,    SPA_POD_Fraction(&info->framerate), 0);
+    if (info->max_framerate.denom != 0)
+        spa_pod_builder_add(builder,
+            SPA_FORMAT_VIDEO_maxFramerate,    SPA_POD_Fraction(&info->max_framerate), 0);
+    if (info->stream_format != 0)
+        spa_pod_builder_add(builder,
+            SPA_FORMAT_VIDEO_H265_streamFormat, SPA_POD_Id(info->stream_format), 0);
+    if (info->alignment != 0)
+        spa_pod_builder_add(builder,
+            SPA_FORMAT_VIDEO_H265_alignment, SPA_POD_Id(info->alignment), 0);
+    return (struct spa_pod*)spa_pod_builder_pop(builder, &f);
+}
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* SPA_VIDEO_H265_UTILS_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265.h
new file mode 100644
index 00000000000..45013852084
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/h265.h
@@ -0,0 +1,49 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2025 Wim Taymans */
+/* SPDX-FileCopyrightText: Copyright © 2025 Arun Raghavan */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_VIDEO_H265_H
+#define SPA_VIDEO_H265_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup spa_param
+ * \{
+ */
+
+#include 
+
+enum spa_h265_stream_format {
+    SPA_H265_STREAM_FORMAT_UNKNOWN = 0,
+    SPA_H265_STREAM_FORMAT_HVC1,
+    SPA_H265_STREAM_FORMAT_HEV1,
+    SPA_H265_STREAM_FORMAT_BYTESTREAM
+};
+
+enum spa_h265_alignment {
+    SPA_H265_ALIGNMENT_UNKNOWN = 0,
+    SPA_H265_ALIGNMENT_AU,
+    SPA_H265_ALIGNMENT_NAL
+};
+
+struct spa_video_info_h265 {
+    struct spa_rectangle size;
+    struct spa_fraction framerate;
+    struct spa_fraction max_framerate;
+    enum spa_h265_stream_format stream_format;
+    enum spa_h265_alignment alignment;
+};
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* SPA_VIDEO_H265_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg-utils.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg-utils.h
index af362360755..e757ff73e92 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg-utils.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg-utils.h
@@ -5,6 +5,10 @@
 #ifndef SPA_VIDEO_MJPG_UTILS_H
 #define SPA_VIDEO_MJPG_UTILS_H
 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +18,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #ifndef SPA_API_VIDEO_MJPG_UTILS
  #ifdef SPA_API_IMPL
   #define SPA_API_VIDEO_MJPG_UTILS SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg.h
index 59725d7148b..db36179a4cb 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/mjpg.h
@@ -5,6 +5,8 @@
 #ifndef SPA_VIDEO_MJPG_H
 #define SPA_VIDEO_MJPG_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,8 +16,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
 struct spa_video_info_mjpg {
     struct spa_rectangle size;
     struct spa_fraction framerate;
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-types.h
index b216250eda6..62ca6bc4a78 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-types.h
@@ -5,6 +5,9 @@
 #ifndef SPA_VIDEO_RAW_TYPES_H
 #define SPA_VIDEO_RAW_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -13,8 +16,6 @@ extern "C" {
  * \addtogroup spa_param
  * \{
  */
-#include 
-#include 
 
 #ifndef SPA_API_VIDEO_RAW_TYPES
  #ifdef SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-utils.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-utils.h
index 424c04004cc..999df2727ad 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-utils.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw-utils.h
@@ -5,6 +5,11 @@
 #ifndef SPA_VIDEO_RAW_UTILS_H
 #define SPA_VIDEO_RAW_UTILS_H
 
+#include 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,10 +19,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-
 #ifndef SPA_API_VIDEO_RAW_UTILS
  #ifdef SPA_API_IMPL
   #define SPA_API_VIDEO_RAW_UTILS SPA_API_IMPL
@@ -117,6 +118,56 @@ spa_format_video_raw_build(struct spa_pod_builder *builder, uint32_t id,
     return (struct spa_pod*)spa_pod_builder_pop(builder, &f);
 }
 
+static inline bool
+spa_format_video_is_rgb(enum spa_video_format format)
+{
+    switch (format) {
+    case SPA_VIDEO_FORMAT_RGBx:
+    case SPA_VIDEO_FORMAT_BGRx:
+    case SPA_VIDEO_FORMAT_xRGB:
+    case SPA_VIDEO_FORMAT_xBGR:
+    case SPA_VIDEO_FORMAT_RGBA:
+    case SPA_VIDEO_FORMAT_BGRA:
+    case SPA_VIDEO_FORMAT_ARGB:
+    case SPA_VIDEO_FORMAT_ABGR:
+    case SPA_VIDEO_FORMAT_RGB:
+    case SPA_VIDEO_FORMAT_BGR:
+    case SPA_VIDEO_FORMAT_GRAY8:
+    case SPA_VIDEO_FORMAT_GRAY16_BE:
+    case SPA_VIDEO_FORMAT_GRAY16_LE:
+    case SPA_VIDEO_FORMAT_RGB16:
+    case SPA_VIDEO_FORMAT_BGR16:
+    case SPA_VIDEO_FORMAT_RGB15:
+    case SPA_VIDEO_FORMAT_BGR15:
+    case SPA_VIDEO_FORMAT_RGB8P:
+    case SPA_VIDEO_FORMAT_ARGB64:
+    case SPA_VIDEO_FORMAT_r210:
+    case SPA_VIDEO_FORMAT_GBR:
+    case SPA_VIDEO_FORMAT_GBR_10BE:
+    case SPA_VIDEO_FORMAT_GBR_10LE:
+    case SPA_VIDEO_FORMAT_GBRA:
+    case SPA_VIDEO_FORMAT_GBRA_10BE:
+    case SPA_VIDEO_FORMAT_GBRA_10LE:
+    case SPA_VIDEO_FORMAT_GBR_12BE:
+    case SPA_VIDEO_FORMAT_GBR_12LE:
+    case SPA_VIDEO_FORMAT_GBRA_12BE:
+    case SPA_VIDEO_FORMAT_GBRA_12LE:
+    case SPA_VIDEO_FORMAT_RGBA_F16:
+    case SPA_VIDEO_FORMAT_RGBA_F32:
+    case SPA_VIDEO_FORMAT_xRGB_210LE:
+    case SPA_VIDEO_FORMAT_xBGR_210LE:
+    case SPA_VIDEO_FORMAT_RGBx_102LE:
+    case SPA_VIDEO_FORMAT_BGRx_102LE:
+    case SPA_VIDEO_FORMAT_ARGB_210LE:
+    case SPA_VIDEO_FORMAT_ABGR_210LE:
+    case SPA_VIDEO_FORMAT_RGBA_102LE:
+    case SPA_VIDEO_FORMAT_BGRA_102LE:
+        return true;
+    default:
+        return false;
+    }
+}
+
 /**
  * \}
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw.h
index c2d369569d8..d0883bea218 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/raw.h
@@ -5,6 +5,11 @@
 #ifndef SPA_VIDEO_RAW_H
 #define SPA_VIDEO_RAW_H
 
+#include 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -14,11 +19,6 @@ extern "C" {
  * \{
  */
 
-#include 
-#include 
-#include 
-#include 
-
 #define SPA_VIDEO_MAX_PLANES 4
 #define SPA_VIDEO_MAX_COMPONENTS 4
 
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/type-info.h
index 04e00c9c1af..cc8d296e0b2 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/param/video/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/param/video/type-info.h
@@ -5,6 +5,7 @@
 #ifndef SPA_VIDEO_TYPES_H
 #define SPA_VIDEO_TYPES_H
 
+#include 
 #include 
 
 #endif /* SPA_VIDEO_TYPES_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/body.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/body.h
new file mode 100644
index 00000000000..e43a027eb20
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/body.h
@@ -0,0 +1,465 @@
+/* Simple Plugin API */
+/* SPDX-FileCopyrightText: Copyright © 2018 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_POD_BODY_H
+#define SPA_POD_BODY_H
+
+#include 
+#include 
+
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef SPA_API_POD_BODY
+ #ifdef SPA_API_IMPL
+  #define SPA_API_POD_BODY SPA_API_IMPL
+ #else
+  #define SPA_API_POD_BODY static inline
+ #endif
+#endif
+
+/**
+ * \addtogroup spa_pod
+ * \{
+ */
+
+struct spa_pod_frame {
+    struct spa_pod pod;
+    struct spa_pod_frame *parent;
+    uint32_t offset;
+    uint32_t flags;
+};
+
+SPA_API_POD_BODY uint32_t spa_pod_type_size(uint32_t type)
+{
+    switch (type) {
+    case SPA_TYPE_None:
+    case SPA_TYPE_Bytes:
+    case SPA_TYPE_Struct:
+    case SPA_TYPE_Pod:
+        return 0;
+    case SPA_TYPE_String:
+        return 1;
+    case SPA_TYPE_Bool:
+    case SPA_TYPE_Int:
+        return sizeof(int32_t);
+    case SPA_TYPE_Id:
+        return sizeof(uint32_t);
+    case SPA_TYPE_Long:
+        return sizeof(int64_t);
+    case SPA_TYPE_Float:
+        return sizeof(float);
+    case SPA_TYPE_Double:
+        return sizeof(double);
+    case SPA_TYPE_Rectangle:
+        return sizeof(struct spa_rectangle);
+    case SPA_TYPE_Fraction:
+        return sizeof(struct spa_fraction);
+    case SPA_TYPE_Bitmap:
+        return sizeof(uint8_t);
+    case SPA_TYPE_Array:
+        return sizeof(struct spa_pod_array_body);
+    case SPA_TYPE_Object:
+        return sizeof(struct spa_pod_object_body);
+    case SPA_TYPE_Sequence:
+        return sizeof(struct spa_pod_sequence_body);
+    case SPA_TYPE_Pointer:
+        return sizeof(struct spa_pod_pointer_body);
+    case SPA_TYPE_Fd:
+        return sizeof(int64_t);
+    case SPA_TYPE_Choice:
+        return sizeof(struct spa_pod_choice_body);
+    }
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_choice_n_values(uint32_t choice_type, uint32_t *min, uint32_t *max)
+{
+    switch (choice_type) {
+    case SPA_CHOICE_Enum:
+        *min = 2;
+        *max = UINT32_MAX;
+        break;
+    case SPA_CHOICE_Range:
+        *min = *max = 3;
+        break;
+    case SPA_CHOICE_Step:
+        *min = *max = 4;
+        break;
+    case SPA_CHOICE_None:
+    case SPA_CHOICE_Flags:
+        *min = *max = 1;
+        break;
+    default:
+        /*
+         * This must always return at least 1, because callers
+         * assume that n_vals >= spa_pod_choice_n_values()
+         * mean that n_vals is at least 1.
+         */
+        *min = 1;
+        *max = UINT32_MAX;
+        return 0;
+    }
+    return 1;
+}
+
+SPA_API_POD_BODY int spa_pod_body_from_data(void *data, size_t maxsize, off_t offset, size_t size,
+        struct spa_pod *pod, const void **body)
+{
+    if (offset < 0 || offset > (int64_t)UINT32_MAX)
+        return -EINVAL;
+    if (size < sizeof(struct spa_pod) ||
+        size > maxsize ||
+        maxsize - size < (uint32_t)offset)
+        return -EINVAL;
+    memcpy(pod, SPA_PTROFF(data, offset, void), sizeof(struct spa_pod));
+    if (!SPA_POD_IS_VALID(pod))
+        return -EINVAL;
+    if (pod->size > size - sizeof(struct spa_pod))
+        return -EINVAL;
+    *body = SPA_PTROFF(data, offset + sizeof(struct spa_pod), void);
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_none(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK_TYPE(pod, SPA_TYPE_None);
+}
+
+SPA_API_POD_BODY int spa_pod_is_bool(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Bool, sizeof(int32_t));
+}
+
+#define SPA_POD_BODY_LOAD_ONCE(a, b) (*(a) = SPA_LOAD_ONCE(*(__typeof__(a))(b)))
+#define SPA_POD_BODY_LOAD_FIELD_ONCE(a, b, field) ((a)->field = SPA_LOAD_ONCE(((__typeof__(a))(b))->field))
+
+SPA_API_POD_BODY int spa_pod_body_get_bool(const struct spa_pod *pod, const void *body, bool *value)
+{
+    if (!spa_pod_is_bool(pod))
+        return -EINVAL;
+    *value = !!__atomic_load_n((const int32_t *)body, __ATOMIC_RELAXED);
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_id(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Id, sizeof(uint32_t));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_id(const struct spa_pod *pod, const void *body, uint32_t *value)
+{
+    if (!spa_pod_is_id(pod))
+        return -EINVAL;
+    SPA_POD_BODY_LOAD_ONCE(value, body);
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_int(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Int, sizeof(int32_t));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_int(const struct spa_pod *pod, const void *body, int32_t *value)
+{
+    if (!spa_pod_is_int(pod))
+        return -EINVAL;
+    SPA_POD_BODY_LOAD_ONCE(value, body);
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_long(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Long, sizeof(int64_t));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_long(const struct spa_pod *pod, const void *body, int64_t *value)
+{
+    if (!spa_pod_is_long(pod))
+        return -EINVAL;
+    /* TODO this is wrong per C standard, but if it breaks so does the Linux kernel. */
+    SPA_BARRIER;
+    memcpy(value, body, sizeof *value);
+    SPA_BARRIER;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_float(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Float, sizeof(float));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_float(const struct spa_pod *pod, const void *body, float *value)
+{
+    if (!spa_pod_is_float(pod))
+        return -EINVAL;
+    SPA_BARRIER;
+    memcpy(value, body, sizeof *value);
+    SPA_BARRIER;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_double(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Double, sizeof(double));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_double(const struct spa_pod *pod, const void *body, double *value)
+{
+    if (!spa_pod_is_double(pod))
+        return -EINVAL;
+    SPA_BARRIER;
+    memcpy(value, body, sizeof *value);
+    SPA_BARRIER;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_string(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_String, 1);
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_string(const struct spa_pod *pod,
+        const void *body, const char **value)
+{
+    const char *s;
+    if (!spa_pod_is_string(pod))
+        return -EINVAL;
+    s = (const char *)body;
+    if (((const volatile char *)s)[pod->size-1] != '\0')
+        return -EINVAL;
+    *value = s;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_body_copy_string(const struct spa_pod *pod, const void *body,
+        char *dest, size_t maxlen)
+{
+    const char *s;
+    if (spa_pod_body_get_string(pod, body, &s) < 0 || maxlen < 1)
+        return -EINVAL;
+    /* pod->size includes the null terminator; a string that does not fit
+     * is reported as -ENOSPC instead of being silently truncated. */
+    if (pod->size > maxlen) {
+        dest[0] = '\0';
+        return -ENOSPC;
+    }
+    SPA_BARRIER;
+    strncpy(dest, s, maxlen-1);
+    SPA_BARRIER;
+    dest[maxlen-1]= '\0';
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_bytes(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK_TYPE(pod, SPA_TYPE_Bytes);
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_bytes(const struct spa_pod *pod, const void *body,
+        const void **value, uint32_t *len)
+{
+    if (!spa_pod_is_bytes(pod))
+        return -EINVAL;
+    *value = (const void *)body;
+    *len = pod->size;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_pointer(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Pointer, sizeof(struct spa_pod_pointer_body));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_pointer(const struct spa_pod *pod, const void *body,
+        uint32_t *type, const void **value)
+{
+    struct spa_pod_pointer_body b;
+    if (!spa_pod_is_pointer(pod))
+        return -EINVAL;
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&b, body, type);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&b, body, value);
+    *type = b.type;
+    *value = b.value;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_fd(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Fd, sizeof(int64_t));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_fd(const struct spa_pod *pod, const void *body,
+        int64_t *value)
+{
+    if (!spa_pod_is_fd(pod))
+        return -EINVAL;
+    SPA_BARRIER;
+    memcpy(value, body, sizeof *value);
+    SPA_BARRIER;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_rectangle(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Rectangle, sizeof(struct spa_rectangle));
+}
+
+SPA_API_POD_BODY int spa_pod_body_get_rectangle(const struct spa_pod *pod, const void *body,
+        struct spa_rectangle *value)
+{
+    if (!spa_pod_is_rectangle(pod))
+        return -EINVAL;
+    SPA_POD_BODY_LOAD_FIELD_ONCE(value, body, width);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(value, body, height);
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_fraction(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Fraction, sizeof(struct spa_fraction));
+}
+SPA_API_POD_BODY int spa_pod_body_get_fraction(const struct spa_pod *pod, const void *body,
+        struct spa_fraction *value)
+{
+    if (!spa_pod_is_fraction(pod))
+        return -EINVAL;
+    SPA_POD_BODY_LOAD_FIELD_ONCE(value, body, num);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(value, body, denom);
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_bitmap(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Bitmap, sizeof(uint8_t));
+}
+SPA_API_POD_BODY int spa_pod_body_get_bitmap(const struct spa_pod *pod, const void *body,
+        const uint8_t **value)
+{
+    if (!spa_pod_is_bitmap(pod))
+        return -EINVAL;
+    *value = (const uint8_t *)body;
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_array(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Array, sizeof(struct spa_pod_array_body));
+}
+SPA_API_POD_BODY int spa_pod_body_get_array(const struct spa_pod *pod, const void *body,
+        struct spa_pod_array *arr, const void **arr_body)
+{
+    if (!spa_pod_is_array(pod))
+        return -EINVAL;
+    arr->pod = *pod;
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&arr->body.child, body, type);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&arr->body.child, body, size);
+    *arr_body = SPA_PTROFF(body, sizeof(struct spa_pod_array_body), void);
+    return 0;
+}
+SPA_API_POD_BODY const void *spa_pod_array_body_get_values(const struct spa_pod_array *arr,
+        const void *body, uint32_t *n_values, uint32_t *val_size, uint32_t *val_type)
+{
+    uint32_t child_size = arr->body.child.size;
+    *n_values = child_size ? (arr->pod.size - sizeof(arr->body)) / child_size : 0;
+    *val_size = child_size;
+    *val_type = arr->body.child.type;
+    if (*val_size < spa_pod_type_size(*val_type))
+        *n_values = 0;
+    return body;
+}
+
+SPA_API_POD_BODY const void *spa_pod_body_get_array_values(const struct spa_pod *pod,
+        const void *body, uint32_t *n_values, uint32_t *val_size, uint32_t *val_type)
+{
+    struct spa_pod_array arr;
+    if (spa_pod_body_get_array(pod, body, &arr, &body) < 0)
+        return NULL;
+    return spa_pod_array_body_get_values(&arr, body, n_values, val_size, val_type);
+}
+
+SPA_API_POD_BODY int spa_pod_is_choice(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Choice, sizeof(struct spa_pod_choice_body));
+}
+SPA_API_POD_BODY int spa_pod_body_get_choice(const struct spa_pod *pod, const void *body,
+        struct spa_pod_choice *choice, const void **choice_body)
+{
+    if (!spa_pod_is_choice(pod))
+        return -EINVAL;
+    choice->pod = *pod;
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&choice->body, body, type);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&choice->body, body, flags);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&choice->body, body, child.size);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&choice->body, body, child.type);
+    *choice_body = SPA_PTROFF(body, sizeof(struct spa_pod_choice_body), void);
+    return 0;
+}
+SPA_API_POD_BODY const void *spa_pod_choice_body_get_values(const struct spa_pod_choice *pod,
+        const void *body, uint32_t *n_values, uint32_t *choice,
+        uint32_t *val_size, uint32_t *val_type)
+{
+    uint32_t child_size = pod->body.child.size, min, max;
+    *val_size = child_size;
+    *val_type = pod->body.child.type;
+    *n_values = child_size ? (pod->pod.size - sizeof(pod->body)) / child_size : 0;
+    *choice = pod->body.type;
+    spa_pod_choice_n_values(*choice, &min, &max);
+    if (*n_values < min || *val_size < spa_pod_type_size(*val_type))
+        *n_values = 0;
+    else if (*n_values > max)
+        *n_values = max;
+    return body;
+}
+
+SPA_API_POD_BODY int spa_pod_is_struct(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK_TYPE(pod, SPA_TYPE_Struct);
+}
+
+SPA_API_POD_BODY int spa_pod_is_object(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Object, sizeof(struct spa_pod_object_body));
+}
+SPA_API_POD_BODY int spa_pod_body_get_object(const struct spa_pod *pod, const void *body,
+        struct spa_pod_object *object, const void **object_body)
+{
+    if (!spa_pod_is_object(pod))
+        return -EINVAL;
+    object->pod = *pod;
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&object->body, body, type);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&object->body, body, id);
+    *object_body = SPA_PTROFF(body, sizeof(struct spa_pod_object_body), void);
+    return 0;
+}
+
+SPA_API_POD_BODY int spa_pod_is_sequence(const struct spa_pod *pod)
+{
+    return SPA_POD_CHECK(pod, SPA_TYPE_Sequence, sizeof(struct spa_pod_sequence_body));
+}
+SPA_API_POD_BODY int spa_pod_body_get_sequence(const struct spa_pod *pod, const void *body,
+        struct spa_pod_sequence *seq, const void **seq_body)
+{
+    if (!spa_pod_is_sequence(pod))
+        return -EINVAL;
+    seq->pod = *pod;
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&seq->body, body, unit);
+    SPA_POD_BODY_LOAD_FIELD_ONCE(&seq->body, body, pad);
+    *seq_body = SPA_PTROFF(body, sizeof(struct spa_pod_sequence_body), void);
+    return 0;
+}
+
+/**
+ * \}
+ */
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* SPA_POD_BODY_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/builder.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/builder.h
index 745e0d671a5..57ff9a04154 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/pod/builder.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/builder.h
@@ -5,6 +5,12 @@
 #ifndef SPA_POD_BUILDER_H
 #define SPA_POD_BUILDER_H
 
+#include 
+
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -18,12 +24,6 @@ extern "C" {
  * \{
  */
 
-#include 
-
-#include 
-#include 
-#include 
-
 #ifndef SPA_API_POD_BUILDER
  #ifdef SPA_API_IMPL
   #define SPA_API_POD_BUILDER SPA_API_IMPL
@@ -65,6 +65,11 @@ spa_pod_builder_get_state(struct spa_pod_builder *builder, struct spa_pod_builde
     *state = builder->state;
 }
 
+SPA_API_POD_BUILDER bool spa_pod_builder_corrupted(const struct spa_pod_builder *builder)
+{
+    return builder->state.offset > builder->size;
+}
+
 SPA_API_POD_BUILDER void
 spa_pod_builder_set_callbacks(struct spa_pod_builder *builder,
         const struct spa_pod_builder_callbacks *callbacks, void *data)
@@ -79,7 +84,7 @@ spa_pod_builder_reset(struct spa_pod_builder *builder, struct spa_pod_builder_st
     uint32_t size = builder->state.offset - state->offset;
     builder->state = *state;
     for (f = builder->state.frame; f ; f = f->parent)
-        f->pod.size -= size;
+        f->pod.size -= SPA_MIN(size, f->pod.size);
 }
 
 SPA_API_POD_BUILDER void spa_pod_builder_init(struct spa_pod_builder *builder, void *data, uint32_t size)
@@ -88,21 +93,28 @@ SPA_API_POD_BUILDER void spa_pod_builder_init(struct spa_pod_builder *builder, v
 }
 
 SPA_API_POD_BUILDER struct spa_pod *
-spa_pod_builder_deref(struct spa_pod_builder *builder, uint32_t offset)
+spa_pod_builder_deref_fallback(struct spa_pod_builder *builder, uint32_t offset, struct spa_pod *fallback)
 {
     uint32_t size = builder->size;
-    if (offset + 8 <= size) {
+    if (offset + UINT64_C(8) <= size) {
         struct spa_pod *pod = SPA_PTROFF(builder->data, offset, struct spa_pod);
-        if (offset + SPA_POD_SIZE(pod) <= size)
+        if (offset + (uint64_t)SPA_POD_SIZE(pod) <= size &&
+            SPA_POD_IS_VALID(pod))
             return pod;
     }
-    return NULL;
+    return fallback;
+}
+
+SPA_API_POD_BUILDER struct spa_pod *
+spa_pod_builder_deref(struct spa_pod_builder *builder, uint32_t offset)
+{
+    return (struct spa_pod*)spa_pod_builder_deref_fallback(builder, offset, NULL);
 }
 
 SPA_API_POD_BUILDER struct spa_pod *
 spa_pod_builder_frame(struct spa_pod_builder *builder, struct spa_pod_frame *frame)
 {
-    if (frame->offset + SPA_POD_SIZE(&frame->pod) <= builder->size)
+    if (frame->offset + (uint64_t)SPA_POD_SIZE(&frame->pod) <= builder->size)
         return SPA_PTROFF(builder->data, frame->offset, struct spa_pod);
     return NULL;
 }
@@ -128,18 +140,31 @@ SPA_API_POD_BUILDER int spa_pod_builder_raw(struct spa_pod_builder *builder, con
     int res = 0;
     struct spa_pod_frame *f;
     uint32_t offset = builder->state.offset;
+    size_t data_offset = -1;
+    uint64_t total_size = offset + (uint64_t) size;
+
+    if (total_size > builder->size) {
+        if (total_size > UINT32_MAX)
+            return -ENOSPC;
+
+        /* data could be inside the data we will realloc */
+        if (spa_ptrinside(builder->data, builder->size, data, size, NULL))
+            data_offset = SPA_PTRDIFF(data, builder->data);
 
-    if (offset + size > builder->size) {
         res = -ENOSPC;
         if (offset <= builder->size)
             spa_callbacks_call_res(&builder->callbacks,
                     struct spa_pod_builder_callbacks, res,
-                    overflow, 0, offset + size);
+                    overflow, 0, total_size);
     }
-    if (res == 0 && data)
+    if (res == 0 && data) {
+        if (data_offset != (size_t) -1)
+            data = SPA_PTROFF(builder->data, data_offset, const void);
+
         memcpy(SPA_PTROFF(builder->data, offset, void), data, size);
+    }
 
-    builder->state.offset += size;
+    builder->state.offset = total_size;
 
     for (f = builder->state.frame; f ; f = f->parent)
         f->pod.size += size;
@@ -147,10 +172,20 @@ SPA_API_POD_BUILDER int spa_pod_builder_raw(struct spa_pod_builder *builder, con
     return res;
 }
 
+SPA_API_POD_BUILDER void spa_pod_builder_remove(struct spa_pod_builder *builder, uint32_t size)
+{
+    struct spa_pod_frame *f;
+    builder->state.offset -= SPA_MIN(size, builder->state.offset);
+    for (f = builder->state.frame; f ; f = f->parent)
+        f->pod.size -= SPA_MIN(size, f->pod.size);
+}
+
 SPA_API_POD_BUILDER int spa_pod_builder_pad(struct spa_pod_builder *builder, uint32_t size)
 {
     uint64_t zeroes = 0;
-    size = SPA_ROUND_UP_N(size, 8) - size;
+    if (builder->state.flags == SPA_POD_BUILDER_FLAG_BODY)
+        return 0;
+    size = SPA_ROUND_UP_N(size, SPA_POD_ALIGN) - size;
     return size ? spa_pod_builder_raw(builder, &zeroes, size) : 0;
 }
 
@@ -181,27 +216,31 @@ SPA_API_POD_BUILDER void *spa_pod_builder_pop(struct spa_pod_builder *builder, s
 }
 
 SPA_API_POD_BUILDER int
-spa_pod_builder_primitive(struct spa_pod_builder *builder, const struct spa_pod *p)
+spa_pod_builder_primitive_body(struct spa_pod_builder *builder, const struct spa_pod *p,
+        const void *body, uint32_t body_size, const char *suffix, uint32_t suffix_size)
 {
-    const void *data;
-    uint32_t size;
-    int r, res;
-
-    if (builder->state.flags == SPA_POD_BUILDER_FLAG_BODY) {
-        data = SPA_POD_BODY_CONST(p);
-        size = SPA_POD_BODY_SIZE(p);
-    } else {
-        data = p;
-        size = SPA_POD_SIZE(p);
+    int res = 0, r;
+    uint32_t size = SPA_POD_SIZE(p) - body_size - suffix_size;
+    if (builder->state.flags != SPA_POD_BUILDER_FLAG_BODY) {
         SPA_FLAG_CLEAR(builder->state.flags, SPA_POD_BUILDER_FLAG_FIRST);
+        res = spa_pod_builder_raw(builder, p, size);
     }
-    res = spa_pod_builder_raw(builder, data, size);
-    if (builder->state.flags != SPA_POD_BUILDER_FLAG_BODY)
-        if ((r = spa_pod_builder_pad(builder, size)) < 0)
-            res = r;
+    if (body_size > 0 && (r = spa_pod_builder_raw(builder, body, body_size)) < 0)
+        res = r;
+    if (suffix_size > 0 && (r = spa_pod_builder_raw(builder, suffix, suffix_size)) < 0)
+        res = r;
+    if ((r = spa_pod_builder_pad(builder, builder->state.offset)) < 0)
+        res = r;
     return res;
 }
 
+SPA_API_POD_BUILDER int
+spa_pod_builder_primitive(struct spa_pod_builder *builder, const struct spa_pod *p)
+{
+    return spa_pod_builder_primitive_body(builder, p,
+            SPA_POD_BODY_CONST(p), p->size, NULL, 0);
+}
+
 #define SPA_POD_INIT(size,type) ((struct spa_pod) { (size), (type) })
 
 #define SPA_POD_INIT_None() SPA_POD_INIT(0, SPA_TYPE_None)
@@ -285,10 +324,7 @@ SPA_API_POD_BUILDER int
 spa_pod_builder_string_len(struct spa_pod_builder *builder, const char *str, uint32_t len)
 {
     const struct spa_pod_string p = SPA_POD_INIT_String(len+1);
-    int r, res = spa_pod_builder_raw(builder, &p, sizeof(p));
-    if ((r = spa_pod_builder_write_string(builder, str, len)) < 0)
-        res = r;
-    return res;
+    return spa_pod_builder_primitive_body(builder, &p.pod, str, len, "", 1);
 }
 
 SPA_API_POD_BUILDER int spa_pod_builder_string(struct spa_pod_builder *builder, const char *str)
@@ -303,10 +339,7 @@ SPA_API_POD_BUILDER int
 spa_pod_builder_bytes(struct spa_pod_builder *builder, const void *bytes, uint32_t len)
 {
     const struct spa_pod_bytes p = SPA_POD_INIT_Bytes(len);
-    int r, res = spa_pod_builder_raw(builder, &p, sizeof(p));
-    if ((r = spa_pod_builder_raw_padded(builder, bytes, len)) < 0)
-        res = r;
-    return res;
+    return spa_pod_builder_primitive_body(builder, &p.pod, bytes, len, NULL, 0);
 }
 SPA_API_POD_BUILDER void *
 spa_pod_builder_reserve_bytes(struct spa_pod_builder *builder, uint32_t len)
@@ -314,7 +347,7 @@ spa_pod_builder_reserve_bytes(struct spa_pod_builder *builder, uint32_t len)
     uint32_t offset = builder->state.offset;
     if (spa_pod_builder_bytes(builder, NULL, len) < 0)
         return NULL;
-    return SPA_POD_BODY(spa_pod_builder_deref(builder, offset));
+    return SPA_PTROFF(builder->data, offset + sizeof(struct spa_pod), void);
 }
 
 #define SPA_POD_INIT_Pointer(type,value) ((struct spa_pod_pointer){ { sizeof(struct spa_pod_pointer_body), SPA_TYPE_Pointer }, { (type), 0, (value) } })
@@ -372,10 +405,7 @@ spa_pod_builder_array(struct spa_pod_builder *builder,
         {(uint32_t)(sizeof(struct spa_pod_array_body) + n_elems * child_size), SPA_TYPE_Array},
         {{child_size, child_type}}
     };
-    int r, res = spa_pod_builder_raw(builder, &p, sizeof(p));
-    if ((r = spa_pod_builder_raw_padded(builder, elems, child_size * n_elems)) < 0)
-        res = r;
-    return res;
+    return spa_pod_builder_primitive_body(builder, &p.pod, elems, n_elems * child_size, NULL, 0);
 }
 
 #define SPA_POD_INIT_CHOICE_BODY(type, flags, child_size, child_type)                \
@@ -456,7 +486,7 @@ spa_pod_builder_control(struct spa_pod_builder *builder, uint32_t offset, uint32
     return spa_pod_builder_raw(builder, &p, sizeof(p));
 }
 
-SPA_API_POD_BUILDER uint32_t spa_choice_from_id(char id)
+SPA_API_POD_BUILDER uint32_t spa_choice_from_id_flags(char id, uint32_t *flags)
 {
     switch (id) {
     case 'r':
@@ -465,6 +495,9 @@ SPA_API_POD_BUILDER uint32_t spa_choice_from_id(char id)
         return SPA_CHOICE_Step;
     case 'e':
         return SPA_CHOICE_Enum;
+    case 'F':
+        *flags |= SPA_POD_PROP_FLAG_DROP;
+        SPA_FALLTHROUGH;
     case 'f':
         return SPA_CHOICE_Flags;
     case 'n':
@@ -472,6 +505,11 @@ SPA_API_POD_BUILDER uint32_t spa_choice_from_id(char id)
         return SPA_CHOICE_None;
     }
 }
+SPA_API_POD_BUILDER uint32_t spa_choice_from_id(char id)
+{
+    uint32_t flags = 0;
+    return spa_choice_from_id_flags(id, &flags);
+}
 
 #define SPA_POD_BUILDER_COLLECT(builder,type,args)                \
 do {                                        \
@@ -565,6 +603,17 @@ do {                                        \
             spa_pod_builder_primitive(builder, pod);        \
         break;                                \
     }                                    \
+    case 'Q':                                \
+    case 'N':                                \
+    case 'U':                                \
+    case 'W':                                \
+    {                                    \
+        struct spa_pod *pod = va_arg(args, struct spa_pod *);        \
+        const void *body = va_arg(args, const void *);            \
+        spa_pod_builder_primitive_body(builder, pod,            \
+                    body, pod->size, NULL, 0);        \
+        break;                                \
+    }                                    \
     }                                    \
 } while(false)
 
@@ -580,39 +629,46 @@ spa_pod_builder_addv(struct spa_pod_builder *builder, va_list args)
         int n_values = 1;
         struct spa_pod_frame f;
         bool choice;
+        uint32_t key = 0, flags = 0, offset = 0, type = 0, ctype = 0;
 
         switch (ftype) {
         case SPA_TYPE_Object:
-        {
-            uint32_t key = va_arg(args, uint32_t);
+            key = va_arg(args, uint32_t);
             if (key == 0)
                 goto exit;
-            spa_pod_builder_prop(builder, key, 0);
+            if (key == SPA_ID_INVALID) {
+                key = va_arg(args, uint32_t);
+                flags = va_arg(args, uint32_t);
+            }
             break;
-        }
         case SPA_TYPE_Sequence:
-        {
-            uint32_t offset = va_arg(args, uint32_t);
-            uint32_t type = va_arg(args, uint32_t);
+            offset = va_arg(args, uint32_t);
+            type = va_arg(args, uint32_t);
             if (type == 0)
                 goto exit;
-            spa_pod_builder_control(builder, offset, type);
-            SPA_FALLTHROUGH
-        }
-        default:
             break;
         }
+
+
         if ((format = va_arg(args, const char *)) == NULL)
             break;
 
         choice = *format == '?';
         if (choice) {
-            uint32_t type = spa_choice_from_id(*++format);
+            ctype = spa_choice_from_id_flags(*++format, &flags);
             if (*format != '\0')
                 format++;
-
-            spa_pod_builder_push_choice(builder, &f, type, 0);
-
+        }
+        switch (ftype) {
+        case SPA_TYPE_Object:
+            spa_pod_builder_prop(builder, key, flags);
+            break;
+        case SPA_TYPE_Sequence:
+            spa_pod_builder_control(builder, offset, type);
+            break;
+        }
+        if (choice) {
+            spa_pod_builder_push_choice(builder, &f, ctype, 0);
             n_values = va_arg(args, int);
         }
         while (n_values-- > 0)
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/command.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/command.h
index 9290a44b8db..f3c13edb902 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/pod/command.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/command.h
@@ -5,13 +5,13 @@
 #ifndef SPA_COMMAND_H
 #define SPA_COMMAND_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_pod
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/event.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/event.h
index 0fa02f698f5..12e84dc8846 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/pod/event.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/event.h
@@ -5,12 +5,12 @@
 #ifndef SPA_EVENT_H
 #define SPA_EVENT_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /**
  * \addtogroup spa_pod
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/iter.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/iter.h
index cb9b7b89884..a042dd1a08e 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/pod/iter.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/iter.h
@@ -5,14 +5,15 @@
 #ifndef SPA_POD_ITER_H
 #define SPA_POD_ITER_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 #include 
 
 #include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
 
 #ifndef SPA_API_POD_ITER
  #ifdef SPA_API_IMPL
@@ -27,24 +28,17 @@ extern "C" {
  * \{
  */
 
-struct spa_pod_frame {
-    struct spa_pod pod;
-    struct spa_pod_frame *parent;
-    uint32_t offset;
-    uint32_t flags;
-};
-
 SPA_API_POD_ITER bool spa_pod_is_inside(const void *pod, uint32_t size, const void *iter)
 {
     size_t remaining;
 
     return spa_ptr_type_inside(pod, size, iter, struct spa_pod, &remaining) &&
-           remaining >= SPA_POD_BODY_SIZE(iter);
+        remaining >= SPA_POD_BODY_SIZE(iter);
 }
 
 SPA_API_POD_ITER void *spa_pod_next(const void *iter)
 {
-    return SPA_PTROFF(iter, SPA_ROUND_UP_N(SPA_POD_SIZE(iter), 8), void);
+    return SPA_PTROFF(iter, SPA_ROUND_UP_N(SPA_POD_SIZE(iter), SPA_POD_ALIGN), void);
 }
 
 SPA_API_POD_ITER struct spa_pod_prop *spa_pod_prop_first(const struct spa_pod_object_body *body)
@@ -58,12 +52,12 @@ SPA_API_POD_ITER bool spa_pod_prop_is_inside(const struct spa_pod_object_body *b
     size_t remaining;
 
     return spa_ptr_type_inside(body, size, iter, struct spa_pod_prop, &remaining) &&
-           remaining >= iter->value.size;
+        remaining >= iter->value.size;
 }
 
 SPA_API_POD_ITER struct spa_pod_prop *spa_pod_prop_next(const struct spa_pod_prop *iter)
 {
-    return SPA_PTROFF(iter, SPA_ROUND_UP_N(SPA_POD_PROP_SIZE(iter), 8), struct spa_pod_prop);
+    return SPA_PTROFF(iter, SPA_ROUND_UP_N(SPA_POD_PROP_SIZE(iter), SPA_POD_ALIGN), struct spa_pod_prop);
 }
 
 SPA_API_POD_ITER struct spa_pod_control *spa_pod_control_first(const struct spa_pod_sequence_body *body)
@@ -77,12 +71,12 @@ SPA_API_POD_ITER bool spa_pod_control_is_inside(const struct spa_pod_sequence_bo
     size_t remaining;
 
     return spa_ptr_type_inside(body, size, iter, struct spa_pod_control, &remaining) &&
-           remaining >= iter->value.size;
+        remaining >= iter->value.size;
 }
 
 SPA_API_POD_ITER struct spa_pod_control *spa_pod_control_next(const struct spa_pod_control *iter)
 {
-    return SPA_PTROFF(iter, SPA_ROUND_UP_N(SPA_POD_CONTROL_SIZE(iter), 8), struct spa_pod_control);
+    return SPA_PTROFF(iter, SPA_ROUND_UP_N(SPA_POD_CONTROL_SIZE(iter), SPA_POD_ALIGN), struct spa_pod_control);
 }
 
 #define SPA_POD_ARRAY_BODY_FOREACH(body, _size, iter)                            \
@@ -107,7 +101,7 @@ SPA_API_POD_ITER struct spa_pod_control *spa_pod_control_next(const struct spa_p
          (iter) = (__typeof__(iter))spa_pod_next(iter))
 
 #define SPA_POD_STRUCT_FOREACH(obj, iter)                            \
-    SPA_POD_FOREACH(SPA_POD_BODY(obj), SPA_POD_BODY_SIZE(obj), iter)
+    SPA_POD_FOREACH(SPA_POD_STRUCT_BODY(obj), SPA_POD_BODY_SIZE(obj), iter)
 
 #define SPA_POD_OBJECT_BODY_FOREACH(body, size, iter)                        \
     for ((iter) = spa_pod_prop_first(body);                \
@@ -125,259 +119,121 @@ SPA_API_POD_ITER struct spa_pod_control *spa_pod_control_next(const struct spa_p
 #define SPA_POD_SEQUENCE_FOREACH(seq, iter)                            \
     SPA_POD_SEQUENCE_BODY_FOREACH(&(seq)->body, SPA_POD_BODY_SIZE(seq), iter)
 
-
 SPA_API_POD_ITER void *spa_pod_from_data(void *data, size_t maxsize, off_t offset, size_t size)
 {
-    void *pod;
-    if (size < sizeof(struct spa_pod) || offset + size > maxsize)
-        return NULL;
-    pod = SPA_PTROFF(data, offset, void);
-    if (SPA_POD_SIZE(pod) > size)
+    struct spa_pod pod;
+    const void *body;
+    if (spa_pod_body_from_data(data, maxsize, offset, size, &pod, &body) < 0)
         return NULL;
-    return pod;
-}
-
-SPA_API_POD_ITER int spa_pod_is_none(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_None);
-}
-
-SPA_API_POD_ITER int spa_pod_is_bool(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Bool && SPA_POD_BODY_SIZE(pod) >= sizeof(int32_t));
+    return SPA_PTROFF(data, offset, void);
 }
 
 SPA_API_POD_ITER int spa_pod_get_bool(const struct spa_pod *pod, bool *value)
 {
-    if (!spa_pod_is_bool(pod))
-        return -EINVAL;
-    *value = !!SPA_POD_VALUE(struct spa_pod_bool, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_id(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Id && SPA_POD_BODY_SIZE(pod) >= sizeof(uint32_t));
+    return spa_pod_body_get_bool(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_id(const struct spa_pod *pod, uint32_t *value)
 {
-    if (!spa_pod_is_id(pod))
-        return -EINVAL;
-    *value = SPA_POD_VALUE(struct spa_pod_id, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_int(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Int && SPA_POD_BODY_SIZE(pod) >= sizeof(int32_t));
+    return spa_pod_body_get_id(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_int(const struct spa_pod *pod, int32_t *value)
 {
-    if (!spa_pod_is_int(pod))
-        return -EINVAL;
-    *value = SPA_POD_VALUE(struct spa_pod_int, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_long(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Long && SPA_POD_BODY_SIZE(pod) >= sizeof(int64_t));
+    return spa_pod_body_get_int(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_long(const struct spa_pod *pod, int64_t *value)
 {
-    if (!spa_pod_is_long(pod))
-        return -EINVAL;
-    *value = SPA_POD_VALUE(struct spa_pod_long, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_float(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Float && SPA_POD_BODY_SIZE(pod) >= sizeof(float));
+    return spa_pod_body_get_long(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_float(const struct spa_pod *pod, float *value)
 {
-    if (!spa_pod_is_float(pod))
-        return -EINVAL;
-    *value = SPA_POD_VALUE(struct spa_pod_float, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_double(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Double && SPA_POD_BODY_SIZE(pod) >= sizeof(double));
+    return spa_pod_body_get_float(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_double(const struct spa_pod *pod, double *value)
 {
-    if (!spa_pod_is_double(pod))
-        return -EINVAL;
-    *value = SPA_POD_VALUE(struct spa_pod_double, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_string(const struct spa_pod *pod)
-{
-    const char *s = (const char *)SPA_POD_CONTENTS(struct spa_pod_string, pod);
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_String &&
-            SPA_POD_BODY_SIZE(pod) > 0 &&
-            s[SPA_POD_BODY_SIZE(pod)-1] == '\0');
+    return spa_pod_body_get_double(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_string(const struct spa_pod *pod, const char **value)
 {
-    if (!spa_pod_is_string(pod))
-        return -EINVAL;
-    *value = (const char *)SPA_POD_CONTENTS(struct spa_pod_string, pod);
-    return 0;
+    return spa_pod_body_get_string(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_copy_string(const struct spa_pod *pod, size_t maxlen, char *dest)
 {
-    const char *s = (const char *)SPA_POD_CONTENTS(struct spa_pod_string, pod);
-    if (!spa_pod_is_string(pod) || maxlen < 1)
-        return -EINVAL;
-    strncpy(dest, s, maxlen-1);
-    dest[maxlen-1]= '\0';
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_bytes(const struct spa_pod *pod)
-{
-    return SPA_POD_TYPE(pod) == SPA_TYPE_Bytes;
+    return spa_pod_body_copy_string(pod, SPA_POD_BODY_CONST(pod), dest, maxlen);
 }
 
 SPA_API_POD_ITER int spa_pod_get_bytes(const struct spa_pod *pod, const void **value, uint32_t *len)
 {
-    if (!spa_pod_is_bytes(pod))
-        return -EINVAL;
-    *value = (const void *)SPA_POD_CONTENTS(struct spa_pod_bytes, pod);
-    *len = SPA_POD_BODY_SIZE(pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_pointer(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Pointer &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(struct spa_pod_pointer_body));
+    return spa_pod_body_get_bytes(pod, SPA_POD_BODY_CONST(pod), value, len);
 }
 
 SPA_API_POD_ITER int spa_pod_get_pointer(const struct spa_pod *pod, uint32_t *type, const void **value)
 {
-    if (!spa_pod_is_pointer(pod))
-        return -EINVAL;
-    *type = ((struct spa_pod_pointer*)pod)->body.type;
-    *value = ((struct spa_pod_pointer*)pod)->body.value;
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_fd(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Fd &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(int64_t));
+    return spa_pod_body_get_pointer(pod, SPA_POD_BODY_CONST(pod), type, value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_fd(const struct spa_pod *pod, int64_t *value)
 {
-    if (!spa_pod_is_fd(pod))
-        return -EINVAL;
-    *value = SPA_POD_VALUE(struct spa_pod_fd, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_rectangle(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Rectangle &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(struct spa_rectangle));
+    return spa_pod_body_get_fd(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_rectangle(const struct spa_pod *pod, struct spa_rectangle *value)
 {
-    if (!spa_pod_is_rectangle(pod))
-        return -EINVAL;
-    *value = SPA_POD_VALUE(struct spa_pod_rectangle, pod);
-    return 0;
-}
-
-SPA_API_POD_ITER int spa_pod_is_fraction(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Fraction &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(struct spa_fraction));
+    return spa_pod_body_get_rectangle(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
 SPA_API_POD_ITER int spa_pod_get_fraction(const struct spa_pod *pod, struct spa_fraction *value)
 {
-    spa_return_val_if_fail(spa_pod_is_fraction(pod), -EINVAL);
-    *value = SPA_POD_VALUE(struct spa_pod_fraction, pod);
-    return 0;
+    return spa_pod_body_get_fraction(pod, SPA_POD_BODY_CONST(pod), value);
 }
 
-SPA_API_POD_ITER int spa_pod_is_bitmap(const struct spa_pod *pod)
+SPA_API_POD_ITER void *spa_pod_get_array_full(const struct spa_pod *pod, uint32_t *n_values,
+        uint32_t *val_size, uint32_t *val_type)
 {
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Bitmap &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(uint8_t));
+    return (void*)spa_pod_body_get_array_values(pod, SPA_POD_BODY(pod), n_values, val_size, val_type);
 }
-
-SPA_API_POD_ITER int spa_pod_is_array(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Array &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(struct spa_pod_array_body));
-}
-
 SPA_API_POD_ITER void *spa_pod_get_array(const struct spa_pod *pod, uint32_t *n_values)
 {
-    spa_return_val_if_fail(spa_pod_is_array(pod), NULL);
-    *n_values = SPA_POD_ARRAY_N_VALUES(pod);
-    return SPA_POD_ARRAY_VALUES(pod);
+    uint32_t size, type;
+    return spa_pod_get_array_full(pod, n_values, &size, &type);
 }
 
-SPA_API_POD_ITER uint32_t spa_pod_copy_array(const struct spa_pod *pod, uint32_t type,
-        void *values, uint32_t max_values)
+SPA_API_POD_ITER uint32_t spa_pod_copy_array_full(const struct spa_pod *pod, uint32_t type,
+        uint32_t size, void *values, uint32_t max_values)
 {
-    uint32_t n_values;
-    void *v = spa_pod_get_array(pod, &n_values);
-    if (v == NULL || max_values == 0 || SPA_POD_ARRAY_VALUE_TYPE(pod) != type)
+    uint32_t n_values, val_size, val_type;
+    const void *v = spa_pod_get_array_full(pod, &n_values, &val_size, &val_type);
+    if (v == NULL || max_values == 0 || val_type != type || val_size != size)
         return 0;
     n_values = SPA_MIN(n_values, max_values);
-    memcpy(values, v, SPA_POD_ARRAY_VALUE_SIZE(pod) * n_values);
+    memcpy(values, v, val_size * n_values);
     return n_values;
 }
 
-SPA_API_POD_ITER int spa_pod_is_choice(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Choice &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(struct spa_pod_choice_body));
-}
+#define spa_pod_copy_array(pod,type,values,max_values)    \
+    spa_pod_copy_array_full(pod,type,sizeof(values[0]),values,max_values)
 
-SPA_API_POD_ITER struct spa_pod *spa_pod_get_values(const struct spa_pod *pod, uint32_t *n_vals, uint32_t *choice)
+SPA_API_POD_ITER struct spa_pod *spa_pod_get_values(const struct spa_pod *pod,
+        uint32_t *n_vals, uint32_t *choice)
 {
-    if (pod->type == SPA_TYPE_Choice) {
-        *n_vals = SPA_POD_CHOICE_N_VALUES(pod);
-        if ((*choice = SPA_POD_CHOICE_TYPE(pod)) == SPA_CHOICE_None)
-            *n_vals = SPA_MIN(1u, SPA_POD_CHOICE_N_VALUES(pod));
-        return (struct spa_pod*)SPA_POD_CHOICE_CHILD(pod);
+    if (spa_pod_is_choice(pod)) {
+        const struct spa_pod_choice *p = (const struct spa_pod_choice*)pod;
+        uint32_t type, size;
+        spa_pod_choice_body_get_values(p, SPA_POD_BODY_CONST(p), n_vals, choice, &size, &type);
+        return (struct spa_pod*)&p->body.child;
     } else {
-        *n_vals = 1;
+        *n_vals = pod->size < spa_pod_type_size(pod->type) ? 0 : 1;
         *choice = SPA_CHOICE_None;
         return (struct spa_pod*)pod;
     }
 }
 
-SPA_API_POD_ITER int spa_pod_is_struct(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Struct);
-}
-
-SPA_API_POD_ITER int spa_pod_is_object(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Object &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(struct spa_pod_object_body));
-}
-
 SPA_API_POD_ITER bool spa_pod_is_object_type(const struct spa_pod *pod, uint32_t type)
 {
     return (pod && spa_pod_is_object(pod) && SPA_POD_OBJECT_TYPE(pod) == type);
@@ -388,12 +244,6 @@ SPA_API_POD_ITER bool spa_pod_is_object_id(const struct spa_pod *pod, uint32_t i
     return (pod && spa_pod_is_object(pod) && SPA_POD_OBJECT_ID(pod) == id);
 }
 
-SPA_API_POD_ITER int spa_pod_is_sequence(const struct spa_pod *pod)
-{
-    return (SPA_POD_TYPE(pod) == SPA_TYPE_Sequence &&
-            SPA_POD_BODY_SIZE(pod) >= sizeof(struct spa_pod_sequence_body));
-}
-
 SPA_API_POD_ITER const struct spa_pod_prop *spa_pod_object_find_prop(const struct spa_pod_object *pod,
         const struct spa_pod_prop *start, uint32_t key)
 {
@@ -422,41 +272,40 @@ SPA_API_POD_ITER const struct spa_pod_prop *spa_pod_find_prop(const struct spa_p
     return spa_pod_object_find_prop((const struct spa_pod_object *)pod, start, key);
 }
 
+SPA_API_POD_ITER int spa_pod_object_has_props(const struct spa_pod_object *pod)
+{
+    struct spa_pod_prop *res;
+    SPA_POD_OBJECT_FOREACH(pod, res)
+        return 1;
+    return 0;
+}
+
 SPA_API_POD_ITER int spa_pod_object_fixate(struct spa_pod_object *pod)
 {
     struct spa_pod_prop *res;
     SPA_POD_OBJECT_FOREACH(pod, res) {
-        if (res->value.type == SPA_TYPE_Choice &&
+        if (spa_pod_is_choice(&res->value) &&
             !SPA_FLAG_IS_SET(res->flags, SPA_POD_PROP_FLAG_DONT_FIXATE))
             ((struct spa_pod_choice*)&res->value)->body.type = SPA_CHOICE_None;
     }
     return 0;
 }
-
-SPA_API_POD_ITER int spa_pod_fixate(struct spa_pod *pod)
-{
-    if (!spa_pod_is_object(pod))
-        return -EINVAL;
-    return spa_pod_object_fixate((struct spa_pod_object *)pod);
-}
-
 SPA_API_POD_ITER int spa_pod_object_is_fixated(const struct spa_pod_object *pod)
 {
     struct spa_pod_prop *res;
     SPA_POD_OBJECT_FOREACH(pod, res) {
-        if (res->value.type == SPA_TYPE_Choice &&
+        if (spa_pod_is_choice(&res->value) &&
            ((struct spa_pod_choice*)&res->value)->body.type != SPA_CHOICE_None)
             return 0;
     }
     return 1;
 }
 
-SPA_API_POD_ITER int spa_pod_object_has_props(const struct spa_pod_object *pod)
+SPA_API_POD_ITER int spa_pod_fixate(struct spa_pod *pod)
 {
-    struct spa_pod_prop *res;
-    SPA_POD_OBJECT_FOREACH(pod, res)
-        return 1;
-    return 0;
+    if (!spa_pod_is_object(pod))
+        return -EINVAL;
+    return spa_pod_object_fixate((struct spa_pod_object *)pod);
 }
 
 SPA_API_POD_ITER int spa_pod_is_fixated(const struct spa_pod *pod)
@@ -474,4 +323,4 @@ SPA_API_POD_ITER int spa_pod_is_fixated(const struct spa_pod *pod)
 }  /* extern "C" */
 #endif
 
-#endif /* SPA_POD_H */
+#endif /* SPA_POD_ITER_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/parser.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/parser.h
index bfec7b88c80..7927636a6ff 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/pod/parser.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/parser.h
@@ -5,16 +5,16 @@
 #ifndef SPA_POD_PARSER_H
 #define SPA_POD_PARSER_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 #include 
 
-#include 
+#include 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #ifndef SPA_API_POD_PARSER
  #ifdef SPA_API_IMPL
   #define SPA_API_POD_PARSER SPA_API_IMPL
@@ -55,6 +55,22 @@ SPA_API_POD_PARSER void spa_pod_parser_pod(struct spa_pod_parser *parser,
     spa_pod_parser_init(parser, pod, SPA_POD_SIZE(pod));
 }
 
+SPA_API_POD_PARSER void spa_pod_parser_init_pod_body(struct spa_pod_parser *parser,
+          const struct spa_pod *pod, const void *body)
+{
+    spa_pod_parser_init(parser,
+            SPA_PTROFF(body, -sizeof(struct spa_pod), const struct spa_pod),
+            pod->size + sizeof(struct spa_pod));
+}
+SPA_API_POD_PARSER void spa_pod_parser_init_from_data(struct spa_pod_parser *parser,
+        const void *data, uint32_t maxsize, uint32_t offset, uint32_t size)
+{
+    size_t offs, sz;
+    offs = SPA_MIN(offset, maxsize);
+    sz = SPA_MIN(maxsize - offs, size);
+    spa_pod_parser_init(parser, SPA_PTROFF(data, offs, void), sz);
+}
+
 SPA_API_POD_PARSER void
 spa_pod_parser_get_state(struct spa_pod_parser *parser, struct spa_pod_parser_state *state)
 {
@@ -67,23 +83,38 @@ spa_pod_parser_reset(struct spa_pod_parser *parser, struct spa_pod_parser_state
     parser->state = *state;
 }
 
-SPA_API_POD_PARSER struct spa_pod *
-spa_pod_parser_deref(struct spa_pod_parser *parser, uint32_t offset, uint32_t size)
+SPA_API_POD_PARSER int
+spa_pod_parser_read_header(struct spa_pod_parser *parser, uint32_t offset, uint32_t size,
+        void *header, uint32_t header_size, uint32_t pod_offset, const void **body)
 {
-    /* Cast to uint64_t to avoid wraparound.  Add 8 for the pod itself. */
-    const uint64_t long_offset = (uint64_t)offset + 8;
+    /* Cast to uint64_t to avoid wraparound. */
+    const uint64_t long_offset = (uint64_t)offset + header_size;
     if (long_offset <= size && (offset & 7) == 0) {
-        /* Use void* because creating a misaligned pointer is undefined. */
-        void *pod = SPA_PTROFF(parser->data, offset, void);
-        /*
-         * Check that the pointer is aligned and that the size (rounded
-         * to the next multiple of 8) is in bounds.
-         */
-        if (SPA_IS_ALIGNED(pod, __alignof__(struct spa_pod)) &&
-            long_offset + SPA_ROUND_UP_N((uint64_t)SPA_POD_BODY_SIZE(pod), 8) <= size)
-            return (struct spa_pod *)pod;
+        struct spa_pod *pod;
+        /* a barrier around the memcpy to make sure it is not moved around or
+         * duplicated after the size check below. We need to work on shared
+         * memory and so there could be updates happening while we read. */
+        SPA_BARRIER;
+        memcpy(header, SPA_PTROFF(parser->data, offset, void), header_size);
+        SPA_BARRIER;
+        pod = SPA_PTROFF(header, pod_offset, struct spa_pod);
+        /* Check that the size (rounded to the next multiple of 8) is in bounds. */
+        if (long_offset + SPA_ROUND_UP_N((uint64_t)pod->size, SPA_POD_ALIGN) <= size) {
+            *body = SPA_PTROFF(parser->data, long_offset, void);
+            return 0;
+        }
     }
-    return NULL;
+    return -EPIPE;
+}
+
+SPA_API_POD_PARSER struct spa_pod *
+spa_pod_parser_deref(struct spa_pod_parser *parser, uint32_t offset, uint32_t size)
+{
+    struct spa_pod pod;
+    const void *body;
+    if (spa_pod_parser_read_header(parser, offset, size, &pod, sizeof(pod), 0, &body) < 0)
+        return NULL;
+    return SPA_PTROFF(body, -sizeof(pod), struct spa_pod);
 }
 
 SPA_API_POD_PARSER struct spa_pod *spa_pod_parser_frame(struct spa_pod_parser *parser, struct spa_pod_frame *frame)
@@ -101,198 +132,400 @@ SPA_API_POD_PARSER void spa_pod_parser_push(struct spa_pod_parser *parser,
     parser->state.frame = frame;
 }
 
-SPA_API_POD_PARSER struct spa_pod *spa_pod_parser_current(struct spa_pod_parser *parser)
+SPA_API_POD_PARSER int spa_pod_parser_get_header(struct spa_pod_parser *parser,
+        void *header, uint32_t header_size, uint32_t pod_offset, const void **body)
 {
     struct spa_pod_frame *f = parser->state.frame;
     uint32_t size = f ? f->offset + SPA_POD_SIZE(&f->pod) : parser->size;
-    return spa_pod_parser_deref(parser, parser->state.offset, size);
+    return spa_pod_parser_read_header(parser, parser->state.offset, size,
+            header, header_size, pod_offset, body);
+}
+
+SPA_API_POD_PARSER int spa_pod_parser_current_body(struct spa_pod_parser *parser,
+        struct spa_pod *pod, const void **body)
+{
+    return spa_pod_parser_get_header(parser, pod, sizeof(struct spa_pod), 0, body);
+}
+
+SPA_API_POD_PARSER struct spa_pod *spa_pod_parser_current(struct spa_pod_parser *parser)
+{
+    struct spa_pod pod;
+    const void *body;
+    if (spa_pod_parser_current_body(parser, &pod, &body) < 0)
+        return NULL;
+    return SPA_PTROFF(body, -sizeof(struct spa_pod), struct spa_pod);
 }
 
 SPA_API_POD_PARSER void spa_pod_parser_advance(struct spa_pod_parser *parser, const struct spa_pod *pod)
 {
-    parser->state.offset += SPA_ROUND_UP_N(SPA_POD_SIZE(pod), 8);
+    parser->state.offset += SPA_ROUND_UP_N(SPA_POD_SIZE(pod), SPA_POD_ALIGN);
+}
+
+SPA_API_POD_PARSER int spa_pod_parser_next_body(struct spa_pod_parser *parser,
+        struct spa_pod *pod, const void **body)
+{
+    if (spa_pod_parser_current_body(parser, pod, body) < 0)
+        return -EINVAL;
+    spa_pod_parser_advance(parser, pod);
+    return 0;
 }
 
 SPA_API_POD_PARSER struct spa_pod *spa_pod_parser_next(struct spa_pod_parser *parser)
 {
-    struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod)
-        spa_pod_parser_advance(parser, pod);
-    return pod;
+    struct spa_pod pod;
+    const void *body;
+    if (spa_pod_parser_current_body(parser, &pod, &body) < 0)
+        return NULL;
+    spa_pod_parser_advance(parser, &pod);
+    return SPA_PTROFF(body, -sizeof(struct spa_pod), struct spa_pod);
 }
 
-SPA_API_POD_PARSER int spa_pod_parser_pop(struct spa_pod_parser *parser,
+SPA_API_POD_PARSER void spa_pod_parser_restart(struct spa_pod_parser *parser,
               struct spa_pod_frame *frame)
 {
+    parser->state.offset = frame->offset;
+}
+
+SPA_API_POD_PARSER void spa_pod_parser_unpush(struct spa_pod_parser *parser,
+              struct spa_pod_frame *frame)
+{
+    spa_pod_parser_restart(parser, frame);
     parser->state.frame = frame->parent;
-    parser->state.offset = frame->offset + SPA_ROUND_UP_N(SPA_POD_SIZE(&frame->pod), 8);
+}
+
+SPA_API_POD_PARSER int spa_pod_parser_pop(struct spa_pod_parser *parser,
+              struct spa_pod_frame *frame)
+{
+    spa_pod_parser_unpush(parser, frame);
+    spa_pod_parser_advance(parser, &frame->pod);
     return 0;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_bool(struct spa_pod_parser *parser, bool *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_bool(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_bool(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_id(struct spa_pod_parser *parser, uint32_t *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_id(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_id(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_int(struct spa_pod_parser *parser, int32_t *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_int(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_int(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_long(struct spa_pod_parser *parser, int64_t *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_long(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_long(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_float(struct spa_pod_parser *parser, float *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_float(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_float(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_double(struct spa_pod_parser *parser, double *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_double(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_double(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_string(struct spa_pod_parser *parser, const char **value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_string(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_string(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_bytes(struct spa_pod_parser *parser, const void **value, uint32_t *len)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_bytes(pod, value, len)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_bytes(&pod, body, value, len)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_pointer(struct spa_pod_parser *parser, uint32_t *type, const void **value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_pointer(pod, type, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_pointer(&pod, body, type, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_fd(struct spa_pod_parser *parser, int64_t *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_fd(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_fd(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_rectangle(struct spa_pod_parser *parser, struct spa_rectangle *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_rectangle(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_rectangle(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
 SPA_API_POD_PARSER int spa_pod_parser_get_fraction(struct spa_pod_parser *parser, struct spa_fraction *value)
 {
-    int res = -EPIPE;
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod != NULL && (res = spa_pod_get_fraction(pod, value)) >= 0)
-        spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_fraction(&pod, body, value)) >= 0)
+        spa_pod_parser_advance(parser, &pod);
     return res;
 }
 
+SPA_API_POD_PARSER int spa_pod_parser_get_pod_body(struct spa_pod_parser *parser,
+        struct spa_pod *value, const void **body)
+{
+    int res;
+    if ((res = spa_pod_parser_current_body(parser, value, body)) < 0)
+        return res;
+    spa_pod_parser_advance(parser, value);
+    return 0;
+}
+
 SPA_API_POD_PARSER int spa_pod_parser_get_pod(struct spa_pod_parser *parser, struct spa_pod **value)
 {
-    struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod == NULL)
-        return -EPIPE;
-    *value = pod;
-    spa_pod_parser_advance(parser, pod);
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_get_pod_body(parser, &pod, &body)) < 0)
+        return res;
+    *value = SPA_PTROFF(body, -sizeof(struct spa_pod), struct spa_pod);
     return 0;
 }
-SPA_API_POD_PARSER int spa_pod_parser_push_struct(struct spa_pod_parser *parser,
-        struct spa_pod_frame *frame)
+
+SPA_API_POD_PARSER int spa_pod_parser_init_struct_body(struct spa_pod_parser *parser,
+        struct spa_pod_frame *frame, const struct spa_pod *pod, const void *body)
 {
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod == NULL)
-        return -EPIPE;
     if (!spa_pod_is_struct(pod))
         return -EINVAL;
+    spa_pod_parser_init_pod_body(parser, pod, body);
     spa_pod_parser_push(parser, frame, pod, parser->state.offset);
     parser->state.offset += sizeof(struct spa_pod_struct);
     return 0;
 }
 
-SPA_API_POD_PARSER int spa_pod_parser_push_object(struct spa_pod_parser *parser,
-        struct spa_pod_frame *frame, uint32_t type, uint32_t *id)
+SPA_API_POD_PARSER int spa_pod_parser_push_struct_body(struct spa_pod_parser *parser,
+        struct spa_pod_frame *frame, struct spa_pod *str, const void **str_body)
 {
-    const struct spa_pod *pod = spa_pod_parser_current(parser);
-    if (pod == NULL)
-        return -EPIPE;
+    int res;
+    if ((res = spa_pod_parser_current_body(parser, str, str_body)) < 0)
+        return res;
+    if (!spa_pod_is_struct(str))
+        return -EINVAL;
+    spa_pod_parser_push(parser, frame, str, parser->state.offset);
+    parser->state.offset += sizeof(struct spa_pod_struct);
+    return 0;
+}
+SPA_API_POD_PARSER int spa_pod_parser_push_struct(struct spa_pod_parser *parser,
+        struct spa_pod_frame *frame)
+{
+    struct spa_pod pod;
+    const void *body;
+    return spa_pod_parser_push_struct_body(parser, frame, &pod, &body);
+}
+
+SPA_API_POD_PARSER int spa_pod_parser_init_object_body(struct spa_pod_parser *parser,
+        struct spa_pod_frame *frame, const struct spa_pod *pod, const void *body,
+        struct spa_pod_object *object, const void **object_body)
+{
+    int res;
     if (!spa_pod_is_object(pod))
         return -EINVAL;
-    if (type != SPA_POD_OBJECT_TYPE(pod))
+    spa_pod_parser_init_pod_body(parser, pod, body);
+    if ((res = spa_pod_body_get_object(pod, body, object, object_body)) < 0)
+        return res;
+    spa_pod_parser_push(parser, frame, pod, parser->state.offset);
+    parser->state.offset += sizeof(struct spa_pod_object);
+    return 0;
+}
+
+SPA_API_POD_PARSER int spa_pod_parser_push_object_body(struct spa_pod_parser *parser,
+        struct spa_pod_frame *frame, struct spa_pod_object *object, const void **object_body)
+{
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_object(&pod, body, object, object_body)) < 0)
+        return res;
+    spa_pod_parser_push(parser, frame, &pod, parser->state.offset);
+    parser->state.offset += sizeof(struct spa_pod_object);
+    return 0;
+}
+SPA_API_POD_PARSER int spa_pod_parser_push_object(struct spa_pod_parser *parser,
+        struct spa_pod_frame *frame, uint32_t type, uint32_t *id)
+{
+    int res;
+    struct spa_pod_object obj;
+    const void *obj_body;
+    if ((res = spa_pod_parser_push_object_body(parser, frame, &obj, &obj_body)) < 0)
+        return res;
+    if (type != obj.body.type) {
+        spa_pod_parser_unpush(parser, frame);
         return -EPROTO;
+    }
     if (id != NULL)
-        *id = SPA_POD_OBJECT_ID(pod);
-    spa_pod_parser_push(parser, frame, pod, parser->state.offset);
-    parser->state.offset = parser->size;
+        *id = obj.body.id;
     return 0;
 }
+SPA_API_POD_PARSER int spa_pod_parser_get_prop_body(struct spa_pod_parser *parser,
+        struct spa_pod_prop *prop, const void **body)
+{
+    int res;
+    if ((res = spa_pod_parser_get_header(parser, prop,
+            sizeof(struct spa_pod_prop),
+            offsetof(struct spa_pod_prop, value), body)) >= 0)
+        parser->state.offset += SPA_ROUND_UP_N(SPA_POD_PROP_SIZE(prop), SPA_POD_ALIGN);
+    return res;
+}
 
-SPA_API_POD_PARSER bool spa_pod_parser_can_collect(const struct spa_pod *pod, char type)
+SPA_API_POD_PARSER int spa_pod_parser_push_sequence_body(struct spa_pod_parser *parser,
+        struct spa_pod_frame *frame, struct spa_pod_sequence *seq, const void **seq_body)
+{
+    int res;
+    struct spa_pod pod;
+    const void *body;
+    if ((res = spa_pod_parser_current_body(parser, &pod, &body)) < 0)
+        return res;
+    if ((res = spa_pod_body_get_sequence(&pod, body, seq, seq_body)) < 0)
+        return res;
+    spa_pod_parser_push(parser, frame, &pod, parser->state.offset);
+    parser->state.offset += sizeof(struct spa_pod_sequence);
+    return 0;
+}
+
+SPA_API_POD_PARSER int spa_pod_parser_get_control_body(struct spa_pod_parser *parser,
+        struct spa_pod_control *control, const void **body)
+{
+    int res;
+    if ((res = spa_pod_parser_get_header(parser, control,
+            sizeof(struct spa_pod_control),
+            offsetof(struct spa_pod_control, value), body)) >= 0)
+        parser->state.offset += SPA_ROUND_UP_N(SPA_POD_CONTROL_SIZE(control), SPA_POD_ALIGN);
+    return res;
+}
+
+SPA_API_POD_PARSER int spa_pod_parser_object_find_prop(struct spa_pod_parser *parser,
+        uint32_t key, struct spa_pod_prop *prop, const void **body)
+{
+    uint32_t start_offset;
+    struct spa_pod_frame *f = parser->state.frame;
+
+    if (f == NULL || f->pod.type != SPA_TYPE_Object)
+        return -EINVAL;
+
+    start_offset = f->offset;
+    while (spa_pod_parser_get_prop_body(parser, prop, body) >= 0) {
+        if (prop->key == key)
+            return 0;
+    }
+    spa_pod_parser_restart(parser, f);
+    parser->state.offset += sizeof(struct spa_pod_object);
+    while (parser->state.offset != start_offset &&
+           spa_pod_parser_get_prop_body(parser, prop, body) >= 0) {
+        if (prop->key == key)
+            return 0;
+    }
+    *body = NULL;
+    return -ENOENT;
+}
+
+SPA_API_POD_PARSER bool spa_pod_parser_body_can_collect(const struct spa_pod *pod, const void *body, char type)
 {
+    struct spa_pod_choice choice;
+
     if (pod == NULL)
         return false;
 
-    if (SPA_POD_TYPE(pod) == SPA_TYPE_Choice) {
+    if (pod->type == SPA_TYPE_Choice) {
         if (!spa_pod_is_choice(pod))
             return false;
-        if (type == 'V')
+        if (type == 'V' || type == 'W')
             return true;
-        if (SPA_POD_CHOICE_TYPE(pod) != SPA_CHOICE_None)
+        if (spa_pod_body_get_choice(pod, body, &choice, &body) < 0)
             return false;
-        pod = SPA_POD_CHOICE_CHILD(pod);
+        if (choice.body.type != SPA_CHOICE_None)
+            return false;
+        pod = &choice.body.child;
     }
 
     switch (type) {
     case 'P':
+    case 'Q':
         return true;
     case 'b':
         return spa_pod_is_bool(pod);
@@ -325,96 +558,193 @@ SPA_API_POD_PARSER bool spa_pod_parser_can_collect(const struct spa_pod *pod, ch
     case 'h':
         return spa_pod_is_fd(pod);
     case 'T':
+    case 'U':
         return spa_pod_is_struct(pod) || spa_pod_is_none(pod);
+    case 'N':
     case 'O':
         return spa_pod_is_object(pod) || spa_pod_is_none(pod);
     case 'V':
+    case 'W':
     default:
         return false;
     }
 }
+SPA_API_POD_PARSER bool spa_pod_parser_can_collect(const struct spa_pod *pod, char type)
+{
+    return spa_pod_parser_body_can_collect(pod, SPA_POD_BODY_CONST(pod), type);
+}
 
-#define SPA_POD_PARSER_COLLECT(pod,_type,args)                        \
-do {                                            \
+#define SPA_POD_PARSER_COLLECT_BODY(_pod,_body,_type,args)                \
+({                                            \
+    int res = 0;                                    \
+    struct spa_pod_choice choice;                            \
+    const struct spa_pod *_p = _pod;                        \
+    const void *_b = _body;                                \
+    if (_p->type == SPA_TYPE_Choice && _type != 'V' && _type != 'W') {        \
+        if (spa_pod_body_get_choice(_p, _b, &choice, &_b) >= 0 &&        \
+            choice.body.type == SPA_CHOICE_None)                \
+            _p = &choice.body.child;                    \
+    }                                        \
     switch (_type) {                                \
     case 'b':                                    \
-        *va_arg(args, bool*) = SPA_POD_VALUE(struct spa_pod_bool, pod);        \
+    {                                        \
+        bool *val = va_arg(args, bool*);                    \
+        res = spa_pod_body_get_bool(_p, _b, val);                \
         break;                                    \
+    }                                        \
     case 'I':                                    \
+    {                                        \
+        uint32_t *val = va_arg(args, uint32_t*);                \
+        res = spa_pod_body_get_id(_p, _b, val);                    \
+        break;                                    \
+    }                                        \
     case 'i':                                    \
-        *va_arg(args, int32_t*) = SPA_POD_VALUE(struct spa_pod_int, pod);    \
+    {                                        \
+        int32_t *val = va_arg(args, int32_t*);                    \
+        res = spa_pod_body_get_int(_p, _b, val);                \
         break;                                    \
+    }                                        \
     case 'l':                                    \
-        *va_arg(args, int64_t*) = SPA_POD_VALUE(struct spa_pod_long, pod);    \
+    {                                        \
+        int64_t *val = va_arg(args, int64_t*);                    \
+        res = spa_pod_body_get_long(_p, _b, val);                \
         break;                                    \
+    }                                        \
     case 'f':                                    \
-        *va_arg(args, float*) = SPA_POD_VALUE(struct spa_pod_float, pod);    \
+    {                                        \
+        float *val = va_arg(args, float*);                    \
+        res = spa_pod_body_get_float(_p, _b, val);                \
         break;                                    \
+    }                                        \
     case 'd':                                    \
-        *va_arg(args, double*) = SPA_POD_VALUE(struct spa_pod_double, pod);    \
+    {                                        \
+        double *val = va_arg(args, double*);                    \
+        res = spa_pod_body_get_double(_p, _b, val);                \
         break;                                    \
+    }                                        \
     case 's':                                    \
-        *va_arg(args, char**) =                            \
-            ((pod) == NULL || (SPA_POD_TYPE(pod) == SPA_TYPE_None)        \
-                ? NULL                            \
-                : (char *)SPA_POD_CONTENTS(struct spa_pod_string, pod));    \
+    {                                        \
+        const char **dest = va_arg(args, const char**);                \
+        if (_p->type == SPA_TYPE_None)                    \
+            *dest = NULL;                            \
+        else                                    \
+            res = spa_pod_body_get_string(_p, _b, dest);            \
         break;                                    \
+    }                                        \
     case 'S':                                    \
     {                                        \
         char *dest = va_arg(args, char*);                    \
         uint32_t maxlen = va_arg(args, uint32_t);                \
-        strncpy(dest, (char *)SPA_POD_CONTENTS(struct spa_pod_string, pod), maxlen-1);    \
-        dest[maxlen-1] = '\0';                            \
+        res = spa_pod_body_copy_string(_p, _b, dest, maxlen);        \
         break;                                    \
     }                                        \
     case 'y':                                    \
-        *(va_arg(args, void **)) = SPA_POD_CONTENTS(struct spa_pod_bytes, pod);    \
-        *(va_arg(args, uint32_t *)) = SPA_POD_BODY_SIZE(pod);            \
+    {                                        \
+        const void **value = va_arg(args, const void**);            \
+        uint32_t *len = va_arg(args, uint32_t*);                \
+        res = spa_pod_body_get_bytes(_p, _b, value, len);            \
         break;                                    \
+    }                                        \
     case 'R':                                    \
-        *va_arg(args, struct spa_rectangle*) =                    \
-                SPA_POD_VALUE(struct spa_pod_rectangle, pod);        \
+    {                                        \
+        struct spa_rectangle *val = va_arg(args, struct spa_rectangle*);    \
+        res = spa_pod_body_get_rectangle(_p, _b, val);            \
         break;                                    \
+    }                                        \
     case 'F':                                    \
-        *va_arg(args, struct spa_fraction*) =                    \
-                SPA_POD_VALUE(struct spa_pod_fraction, pod);        \
+    {                                        \
+        struct spa_fraction *val = va_arg(args, struct spa_fraction*);        \
+        res = spa_pod_body_get_fraction(_p, _b, val);            \
         break;                                    \
+    }                                        \
     case 'B':                                    \
-        *va_arg(args, uint32_t **) =                        \
-            (uint32_t *) SPA_POD_CONTENTS(struct spa_pod_bitmap, pod);    \
+    {                                        \
+        const uint8_t **val = va_arg(args, const uint8_t**);            \
+        res = spa_pod_body_get_bitmap(_p, _b, val);                \
         break;                                    \
+    }                                        \
     case 'a':                                    \
-        *va_arg(args, uint32_t*) = SPA_POD_ARRAY_VALUE_SIZE(pod);        \
-        *va_arg(args, uint32_t*) = SPA_POD_ARRAY_VALUE_TYPE(pod);        \
-        *va_arg(args, uint32_t*) = SPA_POD_ARRAY_N_VALUES(pod);            \
-        *va_arg(args, void**) = SPA_POD_ARRAY_VALUES(pod);            \
+    {                                        \
+        uint32_t *val_size = va_arg(args, uint32_t*);                \
+        uint32_t *val_type = va_arg(args, uint32_t*);                \
+        uint32_t *n_values = va_arg(args, uint32_t*);                \
+        const void **arr_body = va_arg(args, const void**);            \
+        *arr_body = spa_pod_body_get_array_values(_p, _b,            \
+                n_values, val_size, val_type);                \
+        if (*arr_body == NULL)                            \
+            res = -EINVAL;                            \
         break;                                    \
+    }                                        \
     case 'p':                                    \
     {                                        \
-        struct spa_pod_pointer_body *b =                    \
-                (struct spa_pod_pointer_body *) SPA_POD_BODY(pod);    \
-        *(va_arg(args, uint32_t *)) = b->type;                    \
-        *(va_arg(args, const void **)) = b->value;                \
+        uint32_t *type = va_arg(args, uint32_t*);                \
+        const void **value = va_arg(args, const void**);            \
+        res = spa_pod_body_get_pointer(_p, _b, type, value);            \
         break;                                    \
     }                                        \
     case 'h':                                    \
-        *va_arg(args, int64_t*) = SPA_POD_VALUE(struct spa_pod_fd, pod);    \
-        break;                                    \
-    case 'P':                                    \
-    case 'T':                                    \
-    case 'O':                                    \
-    case 'V':                                    \
     {                                        \
-        const struct spa_pod **d = va_arg(args, const struct spa_pod**);    \
-        if (d)                                    \
-            *d = ((pod) == NULL || (SPA_POD_TYPE(pod) == SPA_TYPE_None)    \
-                ? NULL : (pod));                        \
+        int64_t *val = va_arg(args, int64_t*);                    \
+        res = spa_pod_body_get_fd(_p, _b, val);                    \
         break;                                    \
     }                                        \
     default:                                    \
+    {                                        \
+        bool valid = false, do_body = false;                    \
+        switch (_type) {                            \
+        case 'Q':                                \
+            do_body = true;                            \
+            SPA_FALLTHROUGH;                        \
+        case 'P':                                \
+            valid = true;                            \
+            break;                                \
+        case 'U':                                \
+            do_body = true;                            \
+            SPA_FALLTHROUGH;                        \
+        case 'T':                                \
+            valid = spa_pod_is_struct(_p) || spa_pod_is_none(_p);        \
+            break;                                \
+        case 'N':                                \
+            do_body = true;                            \
+            SPA_FALLTHROUGH;                        \
+        case 'O':                                \
+            valid = spa_pod_is_object(_p) || spa_pod_is_none(_p);        \
+            break;                                \
+        case 'W':                                \
+            do_body = true;                            \
+            SPA_FALLTHROUGH;                        \
+        case 'V':                                \
+            valid = spa_pod_is_choice(_p) || spa_pod_is_none(_p);        \
+            break;                                \
+        default:                                \
+            res = -EINVAL;                            \
+            break;                                \
+        }                                    \
+        if (res >= 0 && do_body) {                        \
+            struct spa_pod *p = va_arg(args, struct spa_pod*);        \
+            const void **v = va_arg(args, const void **);            \
+            if (valid && p && v) {                        \
+                *p = *_p;                        \
+                *v = _b;                        \
+            }                                \
+        } else if (res >= 0) {                            \
+            const struct spa_pod **d = va_arg(args, const struct spa_pod**);\
+            if (valid && d)                            \
+                *d = (_p->type == SPA_TYPE_None) ?            \
+                    NULL :                        \
+                    SPA_PTROFF((_b), -sizeof(struct spa_pod),    \
+                        const struct spa_pod);            \
+        }                                    \
+        if (!valid)                                \
+            res = -EINVAL;                            \
         break;                                    \
     }                                        \
-} while(false)
+    }                                        \
+    res;                                        \
+})
+
+#define SPA_POD_PARSER_COLLECT(pod,_type,args)                        \
+    SPA_POD_PARSER_COLLECT_BODY(pod, SPA_POD_BODY_CONST(pod),_type,args)
 
 #define SPA_POD_PARSER_SKIP(_type,args)                            \
 do {                                            \
@@ -446,6 +776,10 @@ do {                                            \
     case 'P':                                    \
     case 'T':                                    \
     case 'O':                                    \
+    case 'W':                                    \
+    case 'Q':                                    \
+    case 'U':                                    \
+    case 'N':                                    \
         va_arg(args, void*);                            \
         break;                                    \
     }                                        \
@@ -454,50 +788,50 @@ do {                                            \
 SPA_API_POD_PARSER int spa_pod_parser_getv(struct spa_pod_parser *parser, va_list args)
 {
     struct spa_pod_frame *f = parser->state.frame;
-        uint32_t ftype = f ? f->pod.type : (uint32_t)SPA_TYPE_Struct;
-    const struct spa_pod_prop *prop = NULL;
     int count = 0;
 
+    if (f == NULL)
+        return -EINVAL;
+
     do {
         bool optional;
-        const struct spa_pod *pod = NULL;
+        struct spa_pod pod = (struct spa_pod) { 0, SPA_TYPE_None };
+        const void *body = NULL;
         const char *format;
+        struct spa_pod_prop prop;
 
-        if (f && ftype == SPA_TYPE_Object) {
-            uint32_t key = va_arg(args, uint32_t);
-            const struct spa_pod_object *object;
+        if (f->pod.type == SPA_TYPE_Object) {
+            uint32_t key = va_arg(args, uint32_t), *flags = NULL;
 
             if (key == 0)
                 break;
-
-            object = (const struct spa_pod_object *)spa_pod_parser_frame(parser, f);
-            prop = spa_pod_object_find_prop(object, prop, key);
-            pod = prop ? &prop->value : NULL;
+            if (key == SPA_ID_INVALID) {
+                key = va_arg(args, uint32_t);
+                flags = va_arg(args, uint32_t*);
+            }
+            if (spa_pod_parser_object_find_prop(parser, key, &prop, &body) >= 0) {
+                pod = prop.value;
+                if (flags)
+                    *flags = prop.flags;
+            }
         }
 
         if ((format = va_arg(args, char *)) == NULL)
             break;
 
-        if (ftype == SPA_TYPE_Struct)
-            pod = spa_pod_parser_next(parser);
+        if (f->pod.type == SPA_TYPE_Struct)
+            spa_pod_parser_next_body(parser, &pod, &body);
 
         if ((optional = (*format == '?')))
             format++;
 
-        if (!spa_pod_parser_can_collect(pod, *format)) {
-            if (!optional) {
-                if (pod == NULL)
-                    return -ESRCH;
-                else
-                    return -EPROTO;
-            }
-            SPA_POD_PARSER_SKIP(*format, args);
-        } else {
-            if (pod->type == SPA_TYPE_Choice && *format != 'V')
-                pod = SPA_POD_CHOICE_CHILD(pod);
-
-            SPA_POD_PARSER_COLLECT(pod, *format, args);
+        if (SPA_POD_PARSER_COLLECT_BODY(&pod, body, *format, args) >= 0) {
             count++;
+        } else if (!optional) {
+            if (body == NULL)
+                return -ESRCH;
+            else
+                return -EPROTO;
         }
     } while (true);
 
@@ -534,6 +868,10 @@ SPA_API_POD_PARSER int spa_pod_parser_get(struct spa_pod_parser *parser, ...)
 #define SPA_POD_OPT_PodObject(val)            "?" SPA_POD_PodObject(val)
 #define SPA_POD_OPT_PodStruct(val)            "?" SPA_POD_PodStruct(val)
 #define SPA_POD_OPT_PodChoice(val)            "?" SPA_POD_PodChoice(val)
+#define SPA_POD_OPT_PodBody(val,body)            "?" SPA_POD_PodBody(val,body)
+#define SPA_POD_OPT_PodBodyObject(val,body)        "?" SPA_POD_PodBodyObject(val,body)
+#define SPA_POD_OPT_PodBodyStruct(val,body)        "?" SPA_POD_PodBodyStruct(val,body)
+#define SPA_POD_OPT_PodBodyChoice(val,body)        "?" SPA_POD_PodBodyChoice(val,body)
 
 #define spa_pod_parser_get_object(p,type,id,...)                \
 ({                                        \
@@ -557,20 +895,25 @@ SPA_API_POD_PARSER int spa_pod_parser_get(struct spa_pod_parser *parser, ...)
     _res;                            \
 })
 
-#define spa_pod_parse_object(pod,type,id,...)            \
+#define spa_pod_body_parse_object(pod,body,type,id,...)        \
 ({                                \
     struct spa_pod_parser _p;                \
-    spa_pod_parser_pod(&_p, pod);                \
+    spa_pod_parser_init_pod_body(&_p, pod, body);        \
     spa_pod_parser_get_object(&_p,type,id,##__VA_ARGS__);    \
 })
 
-#define spa_pod_parse_struct(pod,...)                \
+#define spa_pod_parse_object(pod,type,id,...)        \
+    spa_pod_body_parse_object(pod,SPA_POD_BODY_CONST(pod),type,id,##__VA_ARGS__)
+
+#define spa_pod_body_parse_struct(pod,body,...)            \
 ({                                \
     struct spa_pod_parser _p;                \
-    spa_pod_parser_pod(&_p, pod);                \
+    spa_pod_parser_init_pod_body(&_p, pod, body);        \
     spa_pod_parser_get_struct(&_p,##__VA_ARGS__);        \
 })
 
+#define spa_pod_parse_struct(pod,...)        \
+    spa_pod_body_parse_struct(pod,SPA_POD_BODY_CONST(pod),##__VA_ARGS__)
 /**
  * \}
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/pod.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/pod.h
index 9d54d57522a..79f98f3d33b 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/pod/pod.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/pod.h
@@ -5,18 +5,21 @@
 #ifndef SPA_POD_H
 #define SPA_POD_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_pod
  * \{
  */
 
+#define SPA_POD_ALIGN                8
+#define SPA_POD_MAX_SIZE            (1u<<20)
+
 #define SPA_POD_BODY_SIZE(pod)            (((struct spa_pod*)(pod))->size)
 #define SPA_POD_TYPE(pod)            (((struct spa_pod*)(pod))->type)
 #define SPA_POD_SIZE(pod)            ((uint64_t)sizeof(struct spa_pod) + SPA_POD_BODY_SIZE(pod))
@@ -27,6 +30,15 @@ extern "C" {
 #define SPA_POD_BODY(pod)            SPA_PTROFF((pod),sizeof(struct spa_pod),void)
 #define SPA_POD_BODY_CONST(pod)            SPA_PTROFF((pod),sizeof(struct spa_pod),const void)
 
+#define SPA_POD_IS_VALID(pod)                \
+    (SPA_POD_BODY_SIZE(pod) < SPA_POD_MAX_SIZE)
+#define SPA_POD_CHECK_TYPE(pod,_type)            \
+    (SPA_POD_IS_VALID(pod) &&            \
+    (pod)->type == (_type))
+#define SPA_POD_CHECK(pod,_type,_size) \
+    (SPA_POD_CHECK_TYPE(pod,_type) && (pod)->size >= (_size))
+
+
 struct spa_pod {
     uint32_t size;        /* size of the body */
     uint32_t type;        /* a basic id of enum spa_type */
@@ -94,8 +106,8 @@ struct spa_pod_bitmap {
 };
 
 #define SPA_POD_ARRAY_CHILD(arr)    (&((struct spa_pod_array*)(arr))->body.child)
-#define SPA_POD_ARRAY_VALUE_TYPE(arr)    (SPA_POD_TYPE(SPA_POD_ARRAY_CHILD(arr)))
-#define SPA_POD_ARRAY_VALUE_SIZE(arr)    (SPA_POD_BODY_SIZE(SPA_POD_ARRAY_CHILD(arr)))
+#define SPA_POD_ARRAY_VALUE_TYPE(arr)    (SPA_POD_ARRAY_CHILD(arr)->type)
+#define SPA_POD_ARRAY_VALUE_SIZE(arr)    (SPA_POD_ARRAY_CHILD(arr)->size)
 #define SPA_POD_ARRAY_N_VALUES(arr)    (SPA_POD_ARRAY_VALUE_SIZE(arr) ? ((SPA_POD_BODY_SIZE(arr) - sizeof(struct spa_pod_array_body)) / SPA_POD_ARRAY_VALUE_SIZE(arr)) : 0)
 #define SPA_POD_ARRAY_VALUES(arr)    SPA_POD_CONTENTS(struct spa_pod_array, arr)
 
@@ -112,8 +124,8 @@ struct spa_pod_array {
 #define SPA_POD_CHOICE_CHILD(choice)        (&((struct spa_pod_choice*)(choice))->body.child)
 #define SPA_POD_CHOICE_TYPE(choice)        (((struct spa_pod_choice*)(choice))->body.type)
 #define SPA_POD_CHOICE_FLAGS(choice)        (((struct spa_pod_choice*)(choice))->body.flags)
-#define SPA_POD_CHOICE_VALUE_TYPE(choice)    (SPA_POD_TYPE(SPA_POD_CHOICE_CHILD(choice)))
-#define SPA_POD_CHOICE_VALUE_SIZE(choice)    (SPA_POD_BODY_SIZE(SPA_POD_CHOICE_CHILD(choice)))
+#define SPA_POD_CHOICE_VALUE_TYPE(choice)    (SPA_POD_CHOICE_CHILD(choice)->type)
+#define SPA_POD_CHOICE_VALUE_SIZE(choice)    (SPA_POD_CHOICE_CHILD(choice)->size)
 #define SPA_POD_CHOICE_N_VALUES(choice)        (SPA_POD_CHOICE_VALUE_SIZE(choice) ? ((SPA_POD_BODY_SIZE(choice) - sizeof(struct spa_pod_choice_body)) / SPA_POD_CHOICE_VALUE_SIZE(choice)) : 0)
 #define SPA_POD_CHOICE_VALUES(choice)        (SPA_POD_CONTENTS(struct spa_pod_choice, choice))
 
@@ -122,7 +134,7 @@ enum spa_choice_type {
     SPA_CHOICE_Range,        /**< range: default, min, max */
     SPA_CHOICE_Step,        /**< range with step: default, min, max, step */
     SPA_CHOICE_Enum,        /**< list: default, alternative,...  */
-    SPA_CHOICE_Flags,        /**< flags: default, possible flags,... */
+    SPA_CHOICE_Flags,        /**< flags: first value is flags */
 };
 
 struct spa_pod_choice_body {
@@ -138,6 +150,9 @@ struct spa_pod_choice {
     struct spa_pod_choice_body body;
 };
 
+#define SPA_POD_STRUCT_BODY(pod)        SPA_PTROFF((pod),sizeof(struct spa_pod),struct spa_pod)
+#define SPA_POD_STRUCT_BODY_CONST(pod)        SPA_PTROFF((pod),sizeof(struct spa_pod),const struct spa_pod)
+
 struct spa_pod_struct {
     struct spa_pod pod;
     /* one or more spa_pod follow */
@@ -186,8 +201,11 @@ struct spa_pod_prop {
                              *      Int : n_items,
                              *      (String : key,
                              *       String : value)*)) */
-#define SPA_POD_PROP_FLAG_MANDATORY    (1u<<3)        /**< is mandatory */
+#define SPA_POD_PROP_FLAG_MANDATORY    (1u<<3)        /**< is mandatory, when filtering, both sides
+                              *  need this property or filtering fails. */
 #define SPA_POD_PROP_FLAG_DONT_FIXATE    (1u<<4)        /**< choices need no fixation */
+#define SPA_POD_PROP_FLAG_DROP        (1u<<5)        /**< drop property, when filtering, both sides
+                                                          *  need the property or it will be dropped. */
     uint32_t flags;            /**< flags for property */
     struct spa_pod value;
     /* value follows */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/pod/vararg.h b/src/java.desktop/unix/native/libpipewire/include/spa/pod/vararg.h
index b64761604ba..43351b6d23d 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/pod/vararg.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/pod/vararg.h
@@ -5,14 +5,14 @@
 #ifndef SPA_POD_VARARG_H
 #define SPA_POD_VARARG_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
  * \addtogroup spa_pod
  * \{
@@ -20,14 +20,17 @@ extern "C" {
 
 #define SPA_POD_Prop(key,...)                \
     key, ##__VA_ARGS__
+#define SPA_POD_Propf(key,flags,...)            \
+    SPA_ID_INVALID, key, flags, ##__VA_ARGS__
 
 #define SPA_POD_Control(offset,type,...)        \
     offset, type, ##__VA_ARGS__
 
 #define SPA_CHOICE_RANGE(def,min,max)            3,(def),(min),(max)
 #define SPA_CHOICE_STEP(def,min,max,step)        4,(def),(min),(max),(step)
-#define SPA_CHOICE_ENUM(n_vals,...)            (n_vals),##__VA_ARGS__
+#define SPA_CHOICE_ENUM(n_vals,def,alt1,...)        (n_vals),(def),(alt1),##__VA_ARGS__
 #define SPA_CHOICE_FLAGS(flags)                1, (flags)
+#define SPA_CHOICE_FEATURES(features)            1, (features)
 #define SPA_CHOICE_BOOL(def)                3,(def),(def),!(def)
 
 #define SPA_POD_Bool(val)                "b", val
@@ -41,12 +44,14 @@ extern "C" {
 #define SPA_POD_CHOICE_RANGE_Int(def,min,max)        "?ri", SPA_CHOICE_RANGE(def, min, max)
 #define SPA_POD_CHOICE_STEP_Int(def,min,max,step)    "?si", SPA_CHOICE_STEP(def, min, max, step)
 #define SPA_POD_CHOICE_FLAGS_Int(flags)            "?fi", SPA_CHOICE_FLAGS(flags)
+#define SPA_POD_CHOICE_FEATURES_Int(features)        "?Fi", SPA_CHOICE_FEATURES(features)
 
 #define SPA_POD_Long(val)                "l", val
 #define SPA_POD_CHOICE_ENUM_Long(n_vals,...)        "?el", SPA_CHOICE_ENUM(n_vals, __VA_ARGS__)
 #define SPA_POD_CHOICE_RANGE_Long(def,min,max)        "?rl", SPA_CHOICE_RANGE(def, min, max)
 #define SPA_POD_CHOICE_STEP_Long(def,min,max,step)    "?sl", SPA_CHOICE_STEP(def, min, max, step)
 #define SPA_POD_CHOICE_FLAGS_Long(flags)        "?fl", SPA_CHOICE_FLAGS(flags)
+#define SPA_POD_CHOICE_FEATURES_LONG(features)        "?Fl", SPA_CHOICE_FEATURES(features)
 
 #define SPA_POD_Float(val)                "f", val
 #define SPA_POD_CHOICE_ENUM_Float(n_vals,...)        "?ef", SPA_CHOICE_ENUM(n_vals, __VA_ARGS__)
@@ -82,6 +87,12 @@ extern "C" {
 #define SPA_POD_PodStruct(val)                "T", val
 #define SPA_POD_PodChoice(val)                "V", val
 
+#define SPA_POD_PodBody(val,body)            "Q", val, body
+#define SPA_POD_PodBodyObject(val,body)            "N", val, body
+#define SPA_POD_PodBodyStruct(val,body)            "U", val, body
+#define SPA_POD_PodBodyChoice(val,body)            "W", val, body
+
+
 /**
  * \}
  */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/support/loop.h b/src/java.desktop/unix/native/libpipewire/include/spa/support/loop.h
index 376ab559de3..2a679ee5fc6 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/support/loop.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/support/loop.h
@@ -5,16 +5,16 @@
 #ifndef SPA_LOOP_H
 #define SPA_LOOP_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 
 #include 
 #include 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #ifndef SPA_API_LOOP
  #ifdef SPA_API_IMPL
   #define SPA_API_LOOP SPA_API_IMPL
@@ -38,7 +38,7 @@ extern "C" {
 struct spa_loop { struct spa_interface iface; };
 
 #define SPA_TYPE_INTERFACE_LoopControl    SPA_TYPE_INFO_INTERFACE_BASE "LoopControl"
-#define SPA_VERSION_LOOP_CONTROL    1
+#define SPA_VERSION_LOOP_CONTROL    2
 struct spa_loop_control { struct spa_interface iface; };
 
 #define SPA_TYPE_INTERFACE_LoopUtils    SPA_TYPE_INFO_INTERFACE_BASE "LoopUtils"
@@ -105,6 +105,7 @@ struct spa_loop_methods {
 
     /** Invoke a function in the context of this loop.
      * May be called from any thread and multiple threads at the same time.
+     *
      * If called from the loop's thread, all callbacks previously queued with
      * invoke() will be run synchronously, which might cause unexpected
      * reentrancy problems.
@@ -119,8 +120,11 @@ struct spa_loop_methods {
      *             an object that has identity.
      * \param size The size of data to copy.
      * \param block If \true, do not return until func has been called. Otherwise,
-     *              returns immediately. Passing \true does not risk a deadlock because
-     *              the data thread is never allowed to wait on any other thread.
+     *              returns immediately. Passing \true can cause a deadlock when
+     *              the calling thread is holding the loop context lock. A blocking
+     *              invoke should never be done from a realtime thread. Also beware
+     *              of blocking invokes between 2 threads as you can easily end up
+     *              in a deadly embrace.
      * \param user_data An opaque pointer passed to func.
      * \return `-EPIPE` if the internal ring buffer filled up,
      *         if block is \false, 0 if seq was SPA_ID_INVALID or
@@ -133,6 +137,24 @@ struct spa_loop_methods {
                size_t size,
                bool block,
                void *user_data);
+
+    /** Call a function with the loop lock acquired
+     * May be called from any thread and multiple threads at the same time.
+     *
+     * \param[in] object The callbacks data.
+     * \param func The function to be called.
+     * \param seq An opaque sequence number. This will be made
+     *            available to func.
+     * \param[in] data Data that will be passed to func.
+     * \param size The size of data.
+     * \param user_data An opaque pointer passed to func.
+     * \return the return value of func. */
+    int (*locked) (void *object,
+               spa_invoke_func_t func,
+               uint32_t seq,
+               const void *data,
+               size_t size,
+               void *user_data);
 };
 
 SPA_API_LOOP int spa_loop_add_source(struct spa_loop *object, struct spa_source *source)
@@ -158,6 +180,15 @@ SPA_API_LOOP int spa_loop_invoke(struct spa_loop *object,
             spa_loop, &object->iface, invoke, 0, func, seq, data,
             size, block, user_data);
 }
+SPA_API_LOOP int spa_loop_locked(struct spa_loop *object,
+        spa_invoke_func_t func, uint32_t seq, const void *data,
+        size_t size, void *user_data)
+{
+    return spa_api_method_r(int, -ENOTSUP,
+            spa_loop, &object->iface, locked, 0, func, seq, data,
+            size, user_data);
+}
+
 
 /** Control hooks. These hooks can't be removed from their
  *  callbacks and must be removed from a safe place (when the loop
@@ -166,10 +197,10 @@ struct spa_loop_control_hooks {
 #define SPA_VERSION_LOOP_CONTROL_HOOKS    0
     uint32_t version;
     /** Executed right before waiting for events. It is typically used to
-     * release locks. */
+     * release locks or integrate other fds into the loop. */
     void (*before) (void *data);
     /** Executed right after waiting for events. It is typically used to
-     * reacquire locks. */
+     * reacquire locks or integrate other fds into the loop. */
     void (*after) (void *data);
 };
 
@@ -213,7 +244,7 @@ SPA_API_LOOP void spa_loop_control_hook_after(struct spa_hook_list *l)
 struct spa_loop_control_methods {
     /* the version of this structure. This can be used to expand this
      * structure in the future */
-#define SPA_VERSION_LOOP_CONTROL_METHODS    1
+#define SPA_VERSION_LOOP_CONTROL_METHODS    2
     uint32_t version;
 
     /** get the loop fd
@@ -244,7 +275,7 @@ struct spa_loop_control_methods {
      * This function should be called before calling iterate and is
      * typically used to capture the thread that this loop will run in.
      * It should ideally be called once from the thread that will run
-     * the loop.
+     * the loop. This function will lock the loop.
      */
     void (*enter) (void *object);
     /** Leave a loop
@@ -252,6 +283,8 @@ struct spa_loop_control_methods {
      *
      * It should ideally be called once after calling iterate when the loop
      * will no longer be iterated from the thread that called enter().
+     *
+     * This function will unlock the loop.
      */
     void (*leave) (void *object);
 
@@ -260,8 +293,10 @@ struct spa_loop_control_methods {
      * \param timeout an optional timeout in milliseconds.
      *    0 for no timeout, -1 for infinite timeout.
      *
-     * This function will block
-     * up to \a timeout milliseconds and then dispatch the fds with activity.
+     * This function will first unlock the loop and then block
+     * up to \a timeout milliseconds, lock the loop again and then
+     * dispatch the fds with activity.
+     *
      * The number of dispatched fds is returned.
      */
     int (*iterate) (void *object, int timeout);
@@ -275,6 +310,70 @@ struct spa_loop_control_methods {
      * returns 1 on success, 0 or negative errno value on error.
      */
     int (*check) (void *object);
+
+    /** Lock the loop.
+     * This will ensure the loop is not in the process of dispatching
+     * callbacks. Since version 2:2
+     *
+     * \param[in] object the control
+     * \return 0 on success or a negative return value on error.
+     */
+    int (*lock) (void *object);
+
+    /** Unlock the loop.
+     * Unlocks the loop again so that callbacks can be dispatched
+     * again. Since version 2:2
+     *
+     * \param[in] object the control
+     * \return 0 on success or a negative return value on error.
+     */
+    int (*unlock) (void *object);
+
+    /** get the absolute time
+     * Get the current time with \ref timeout that can be used in wait.
+     * Since version 2:2
+     *
+     * This function can be called from any thread.
+     */
+    int (*get_time) (void *object, struct timespec *abstime, int64_t timeout);
+
+    /** Wait for a signal
+     * Wait until a thread performs signal. Since version 2:2
+     *
+     * This function must be called with the loop lock. Because this is a
+     * blocking call, it should not be performed from a realtime thread.
+     *
+     * \param[in] object the control
+     * \param[in] abstime the maximum time to wait for the signal or NULL
+     * \return 0 on success or a negative return value on error.
+     */
+    int (*wait) (void *object, const struct timespec *abstime);
+
+    /** Signal waiters
+     * Wake up all threads blocked in wait. Since version 2:2
+     * When wait_for_accept is set, this functions blocks until all
+     * threads performed accept.
+     *
+     * This function must be called with the loop lock and is safe to
+     * call from a realtime thread source dispatch functions when
+     * wait_for_accept is false.
+     *
+     * \param[in] object the control
+     * \param[in] wait_for_accept block for accept
+     * \return 0 on success or a negative return value on error.
+     */
+    int (*signal) (void *object, bool wait_for_accept);
+
+    /** Accept signalers
+     * Resume the thread that signaled with wait_for accept.
+     *
+     * This function must be called with the loop lock and is safe to
+     * call from a realtime thread source dispatch functions.
+     *
+     * \param[in] object the control
+     * \return 0 on success or a negative return value on error.
+     */
+    int (*accept) (void *object);
 };
 
 SPA_API_LOOP int spa_loop_control_get_fd(struct spa_loop_control *object)
@@ -314,6 +413,38 @@ SPA_API_LOOP int spa_loop_control_check(struct spa_loop_control *object)
     return spa_api_method_r(int, -ENOTSUP,
             spa_loop_control, &object->iface, check, 1);
 }
+SPA_API_LOOP int spa_loop_control_lock(struct spa_loop_control *object)
+{
+    return spa_api_method_r(int, -ENOTSUP,
+            spa_loop_control, &object->iface, lock, 2);
+}
+SPA_API_LOOP int spa_loop_control_unlock(struct spa_loop_control *object)
+{
+    return spa_api_method_r(int, -ENOTSUP,
+            spa_loop_control, &object->iface, unlock, 2);
+}
+SPA_API_LOOP int spa_loop_control_get_time(struct spa_loop_control *object,
+        struct timespec *abstime, int64_t timeout)
+{
+    return spa_api_method_r(int, -ENOTSUP,
+            spa_loop_control, &object->iface, get_time, 2, abstime, timeout);
+}
+SPA_API_LOOP int spa_loop_control_wait(struct spa_loop_control *object,
+        const struct timespec *abstime)
+{
+    return spa_api_method_r(int, -ENOTSUP,
+            spa_loop_control, &object->iface, wait, 2, abstime);
+}
+SPA_API_LOOP int spa_loop_control_signal(struct spa_loop_control *object, bool wait_for_accept)
+{
+    return spa_api_method_r(int, -ENOTSUP,
+            spa_loop_control, &object->iface, signal, 2, wait_for_accept);
+}
+SPA_API_LOOP int spa_loop_control_accept(struct spa_loop_control *object)
+{
+    return spa_api_method_r(int, -ENOTSUP,
+            spa_loop_control, &object->iface, accept, 2);
+}
 
 typedef void (*spa_source_io_func_t) (void *data, int fd, uint32_t mask);
 typedef void (*spa_source_idle_func_t) (void *data);
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/support/system.h b/src/java.desktop/unix/native/libpipewire/include/spa/support/system.h
index fb58dc337b6..7bbc892e39e 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/support/system.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/support/system.h
@@ -5,12 +5,6 @@
 #ifndef SPA_SYSTEM_H
 #define SPA_SYSTEM_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct itimerspec;
-
 #include 
 #include 
 #include 
@@ -18,6 +12,12 @@ struct itimerspec;
 #include 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct itimerspec;
+
 #ifndef SPA_API_SYSTEM
  #ifdef SPA_API_IMPL
   #define SPA_API_SYSTEM SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/atomic.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/atomic.h
new file mode 100644
index 00000000000..71d0d9f4f1d
--- /dev/null
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/atomic.h
@@ -0,0 +1,37 @@
+/* Atomic operations */
+/* SPDX-FileCopyrightText: Copyright © 2023 Wim Taymans */
+/* SPDX-License-Identifier: MIT */
+
+#ifndef SPA_ATOMIC_H
+#define SPA_ATOMIC_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define SPA_ATOMIC_CAS(v,ov,nv)                        \
+({                                    \
+    __typeof__(v) __ov = (ov);                    \
+    __atomic_compare_exchange_n(&(v), &__ov, (nv),            \
+            0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);        \
+})
+
+#define SPA_ATOMIC_DEC(s)        __atomic_sub_fetch(&(s), 1, __ATOMIC_SEQ_CST)
+#define SPA_ATOMIC_INC(s)        __atomic_add_fetch(&(s), 1, __ATOMIC_SEQ_CST)
+#define SPA_ATOMIC_LOAD(s)        __atomic_load_n(&(s), __ATOMIC_SEQ_CST)
+#define SPA_LOAD_ONCE(s)        __atomic_load_n(&(s), __ATOMIC_RELAXED)
+#define SPA_STORE_ONCE(s,v)        __atomic_store_n(&(s), (v), __ATOMIC_RELAXED)
+#define SPA_ATOMIC_STORE(s,v)        __atomic_store_n(&(s), (v), __ATOMIC_SEQ_CST)
+#define SPA_ATOMIC_XCHG(s,v)        __atomic_exchange_n(&(s), (v), __ATOMIC_SEQ_CST)
+
+#define SPA_SEQ_WRITE(s)        SPA_ATOMIC_INC(s)
+#define SPA_SEQ_WRITE_SUCCESS(s1,s2)    ((s1) + 1 == (s2) && ((s2) & 1) == 0)
+
+#define SPA_SEQ_READ(s)            SPA_ATOMIC_LOAD(s)
+#define SPA_SEQ_READ_SUCCESS(s1,s2)    ((s1) == (s2) && ((s2) & 1) == 0)
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* SPA_ATOMIC_H */
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/cleanup.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/cleanup.h
index 944907ccffb..291f2f91359 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/cleanup.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/cleanup.h
@@ -46,9 +46,13 @@ __extension__ ({ \
 
 /* ========================================================================== */
 
-#if defined(__has_attribute) && __has_attribute(__cleanup__)
-
+#ifdef __has_attribute
+#if __has_attribute(__cleanup__)
 #define spa_cleanup(func) __attribute__((__cleanup__(func)))
+#endif
+#endif
+
+#ifdef spa_cleanup
 
 #define SPA_DEFINE_AUTO_CLEANUP(name, type, ...) \
 typedef __typeof__(type) _spa_auto_cleanup_type_ ## name; \
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/defs.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/defs.h
index ace677015ca..9c54661a5da 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/defs.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/defs.h
@@ -5,6 +5,13 @@
 #ifndef SPA_UTILS_DEFS_H
 #define SPA_UTILS_DEFS_H
 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 # if __cplusplus >= 201103L
@@ -34,13 +41,6 @@ extern "C" {
 #define SPA_CONCAT_NOEXPAND(a, b) a ## b
 #define SPA_CONCAT(a, b) SPA_CONCAT_NOEXPAND(a, b)
 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
 /**
  * \defgroup spa_utils_defs Miscellaneous
  * Helper macros and functions
@@ -242,6 +242,7 @@ struct spa_fraction {
 #define SPA_UNUSED __attribute__ ((unused))
 #define SPA_NORETURN __attribute__ ((noreturn))
 #define SPA_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result))
+#define SPA_BARRIER __asm__ __volatile__("": : :"memory")
 #else
 #define SPA_PRINTF_FUNC(fmt, arg1)
 #define SPA_FORMAT_ARG_FUNC(arg1)
@@ -252,6 +253,7 @@ struct spa_fraction {
 #define SPA_UNUSED
 #define SPA_NORETURN
 #define SPA_WARN_UNUSED_RESULT
+#define SPA_BARRIER
 #endif
 
 #ifndef SPA_API_IMPL
@@ -292,6 +294,13 @@ struct spa_fraction {
 #define SPA_ROUND_DOWN_N(num,align)    ((num) & ~SPA_ROUND_MASK(num, align))
 #define SPA_ROUND_UP_N(num,align)    ((((num)-1) | SPA_ROUND_MASK(num, align))+1)
 
+#define SPA_SCALE32(val,num,denom)                \
+({                                \
+    uint64_t _val = (val);                    \
+    uint64_t _denom = (denom);                \
+    (uint32_t)(((_val) * (num)) / (_denom));        \
+})
+
 #define SPA_SCALE32_UP(val,num,denom)                \
 ({                                \
     uint64_t _val = (val);                    \
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/dict.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/dict.h
index d9258a5fe1c..b9c6b8415db 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/dict.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/dict.h
@@ -5,14 +5,14 @@
 #ifndef SPA_DICT_H
 #define SPA_DICT_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #ifndef SPA_API_DICT
  #ifdef SPA_API_IMPL
   #define SPA_API_DICT SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/enum-types.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/enum-types.h
index c1313f0390e..171662f166c 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/enum-types.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/enum-types.h
@@ -5,13 +5,13 @@
 #ifndef SPA_ENUM_TYPES_H
 #define SPA_ENUM_TYPES_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 /**
  * \addtogroup spa_types
  * \{
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/hook.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/hook.h
index 566433bf8de..fdce441da2e 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/hook.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/hook.h
@@ -5,13 +5,13 @@
 #ifndef SPA_HOOK_H
 #define SPA_HOOK_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 #ifndef SPA_API_HOOK
  #ifdef SPA_API_IMPL
   #define SPA_API_HOOK SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/list.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/list.h
index 6bcc0e2328b..8ebfe4c3d2c 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/list.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/list.h
@@ -5,12 +5,12 @@
 #ifndef SPA_LIST_H
 #define SPA_LIST_H
 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 #ifndef SPA_API_LIST
  #ifdef SPA_API_IMPL
   #define SPA_API_LIST SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/string.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/string.h
index d225a3c87c3..88df3a1b343 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/string.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/string.h
@@ -5,18 +5,19 @@
 #ifndef SPA_UTILS_STRING_H
 #define SPA_UTILS_STRING_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #include 
 #include 
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #ifndef SPA_API_STRING
  #ifdef SPA_API_IMPL
   #define SPA_API_STRING SPA_API_IMPL
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/type-info.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/type-info.h
index 85f831daede..81b389d58ca 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/type-info.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/type-info.h
@@ -5,12 +5,20 @@
 #ifndef SPA_TYPE_INFO_H
 #define SPA_TYPE_INFO_H
 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-
 /**
  * \addtogroup spa_types
  * \{
@@ -20,15 +28,6 @@ extern "C" {
 #define SPA_TYPE_ROOT    spa_types
 #endif
 
-
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-
 static const struct spa_type_info spa_types[] = {
         /* Basic types */
     { SPA_TYPE_START, SPA_TYPE_START, SPA_TYPE_INFO_BASE, NULL },
@@ -80,6 +79,8 @@ static const struct spa_type_info spa_types[] = {
     { SPA_TYPE_OBJECT_ParamLatency, SPA_TYPE_Object, SPA_TYPE_INFO_PARAM_Latency, spa_type_param_latency },
     { SPA_TYPE_OBJECT_ParamProcessLatency, SPA_TYPE_Object, SPA_TYPE_INFO_PARAM_ProcessLatency, spa_type_param_process_latency },
     { SPA_TYPE_OBJECT_ParamTag, SPA_TYPE_Object, SPA_TYPE_INFO_PARAM_Tag, spa_type_param_tag },
+    { SPA_TYPE_OBJECT_PeerParam, SPA_TYPE_Object, SPA_TYPE_INFO_PeerParam, spa_type_peer_param },
+    { SPA_TYPE_OBJECT_ParamDict, SPA_TYPE_Object, SPA_TYPE_INFO_PARAM_Dict, spa_type_param_dict },
 
     { 0, 0, NULL, NULL }
 };
diff --git a/src/java.desktop/unix/native/libpipewire/include/spa/utils/type.h b/src/java.desktop/unix/native/libpipewire/include/spa/utils/type.h
index 79802d2f07e..b4efa917394 100644
--- a/src/java.desktop/unix/native/libpipewire/include/spa/utils/type.h
+++ b/src/java.desktop/unix/native/libpipewire/include/spa/utils/type.h
@@ -5,13 +5,13 @@
 #ifndef SPA_TYPE_H
 #define SPA_TYPE_H
 
+#include 
+#include 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#include 
-#include 
-
 #ifndef SPA_API_TYPE
  #ifdef SPA_API_IMPL
   #define SPA_API_TYPE SPA_API_IMPL
@@ -88,6 +88,8 @@ enum {
     SPA_TYPE_OBJECT_ParamLatency,
     SPA_TYPE_OBJECT_ParamProcessLatency,
     SPA_TYPE_OBJECT_ParamTag,
+    SPA_TYPE_OBJECT_PeerParam,
+    SPA_TYPE_OBJECT_ParamDict,
     _SPA_TYPE_OBJECT_LAST,            /**< not part of ABI */
 
     /* vendor extensions */

From 065de5547122b5f7137d0bd9d2554fbf88df728c Mon Sep 17 00:00:00 2001
From: Rudraroop Ray 
Date: Mon, 23 Nov 2026 19:09:35 +0000
Subject: [PATCH 49/95] 8388931: Shenandoah: Optimize ShenandoahHeapRegion
 footprint

Reviewed-by: shade, kdnilsen
---
 .../share/gc/shenandoah/shenandoahHeap.cpp    |  8 +-
 .../gc/shenandoah/shenandoahHeapRegion.cpp    | 48 ++++++-----
 .../gc/shenandoah/shenandoahHeapRegion.hpp    | 79 +++++++++++--------
 .../shenandoahHeapRegion.inline.hpp           |  9 ++-
 .../gc/shenandoah/vmStructs_shenandoah.hpp    |  2 +-
 5 files changed, 86 insertions(+), 60 deletions(-)

diff --git a/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp b/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp
index 876d8c73a8f..ad19192835f 100644
--- a/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp
+++ b/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp
@@ -353,8 +353,10 @@ jint ShenandoahHeap::initialize() {
   //
   // Create regions and region sets
   //
-  size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
-  size_t region_storage_size_orig = region_align * _num_regions;
+  size_t region_granule = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
+  assert(region_granule == 2 * SHENANDOAH_CACHE_LINE_SIZE,
+         "Performance: should take exactly two cache lines: %zu", region_granule);
+  size_t region_storage_size_orig = region_granule * _num_regions;
   size_t region_storage_size = align_up(region_storage_size_orig,
                                         MAX2(region_page_size, os::vm_allocation_granularity()));
 
@@ -415,7 +417,7 @@ jint ShenandoahHeap::initialize() {
     for (size_t i = 0; i < _num_regions; i++) {
       HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;
       bool is_committed = i < num_committed_regions;
-      void* loc = region_storage.base() + i * region_align;
+      void* loc = region_storage.base() + i * region_granule;
 
       ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);
       assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");
diff --git a/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.cpp b/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.cpp
index d7c7186ca52..18f5072364f 100644
--- a/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.cpp
+++ b/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.cpp
@@ -44,6 +44,7 @@
 #include "runtime/globals_extension.hpp"
 #include "runtime/java.hpp"
 #include "runtime/os.hpp"
+#include "utilities/checkedCast.hpp"
 #include "utilities/powerOfTwo.hpp"
 
 size_t ShenandoahHeapRegion::RegionCount = 0;
@@ -57,32 +58,35 @@ size_t ShenandoahHeapRegion::MaxTLABSizeBytes = 0;
 size_t ShenandoahHeapRegion::MaxTLABSizeWords = 0;
 
 ShenandoahHeapRegion::ShenandoahHeapRegion(HeapWord* start, size_t index, bool committed) :
-  _index(index),
   _bottom(start),
   _end(start + RegionSizeWords),
+  _index(checked_cast(index)),
+  _humongous_start_region_index(UndefinedRegionIndex),
+  _state(committed ? _empty_committed : _empty_uncommitted),
+  _has_self_forwards(false),
+  _age(0),
+  _needs_bitmap_reset(false),
+  _promoted_in_place(false),
   _new_top(nullptr),
-  _empty_time(os::elapsedTime()),
   _top_before_promoted(nullptr),
   _top_at_evac_start(start),
-  _state(committed ? _empty_committed : _empty_uncommitted),
+  _empty_time(os::elapsedTime()),
+  _mixed_candidate_garbage_words(0),
+  _coalesce_and_fill_boundary(start),
+  _critical_pins(0),
+  _update_watermark(start),
   _top(start),
+  _live_data(0),
   _tlab_allocs(0),
   _gclab_allocs(0),
   _plab_allocs(0),
-  _live_data(0),
-  _critical_pins(0),
-  _mixed_candidate_garbage_words(0),
-  _update_watermark(start),
-  _age(0),
-  _needs_bitmap_reset(false),
-  _humongous_start_region_index(UndefinedRegionIndex) {
+  _recycling(false)
+{
   assert(Universe::on_page_boundary(_bottom) && Universe::on_page_boundary(_end),
          "invalid space boundaries");
   if (ZapUnusedHeapArea && committed) {
     SpaceMangler::mangle_region(MemRegion(_bottom, _end));
   }
-  _recycling.unset();
-  _has_self_forwards.unset();
 }
 
 void ShenandoahHeapRegion::report_illegal_transition(const char *method) {
@@ -341,8 +345,8 @@ void ShenandoahHeapRegion::make_empty() {
   reset_age();
   switch (state()) {
     case _trash:
-      set_state(_empty_committed);
       _empty_time = os::elapsedTime();
+      set_state(_empty_committed);
       return;
     default:
       report_illegal_transition("emptying");
@@ -404,7 +408,7 @@ void ShenandoahHeapRegion::set_live_data(size_t s) {
 
 void ShenandoahHeapRegion::print_on(outputStream* st) const {
   st->print("|");
-  st->print("%5zu", this->_index);
+  st->print(UINT32_FORMAT_W(5), this->_index);
 
   switch (state()) {
     case _empty_uncommitted:
@@ -574,7 +578,7 @@ void ShenandoahHeapRegion::oop_iterate_humongous_slice_all(OopIterateClosure* cl
 }
 
 void ShenandoahHeapRegion::recycle_internal() {
-  assert(_recycling.is_set() && is_trash(), "Wrong state");
+  assert(_recycling.load_acquire() && is_trash(), "Wrong state");
   ShenandoahHeap* heap = ShenandoahHeap::heap();
 
   _top_at_evac_start = _bottom;
@@ -605,7 +609,7 @@ void ShenandoahHeapRegion::try_recycle_under_lock() {
   if (!is_trash()) {
     return;
   }
-  if (_recycling.try_set()) {
+  if (_recycling.compare_set(false, true)) {
     if (is_trash()) {
       // At freeset rebuild time, which precedes recycling of collection set, we treat all cset regions as
       // part of capacity, as empty, as fully available, and as unaffiliated.  This provides short-lived optimism
@@ -613,12 +617,15 @@ void ShenandoahHeapRegion::try_recycle_under_lock() {
       // by more time-precise accounting of these details.
       recycle_internal();
     }
-    _recycling.unset();
+    // A release store is enough to hand the recycled region over: a racing recycler
+    // observes it through the CAS or the acquire load in the spin loop below, and
+    // nothing after this point depends on the store. No trailing fence is needed.
+    _recycling.release_store(false);
   } else {
     // Ensure recycling is unset before returning to mutator to continue memory allocation.
     // Otherwise, the mutator might see region as fully recycled and might change its affiliation only to have
     // the racing GC worker thread overwrite its affiliation to FREE.
-    while (_recycling.is_set()) {
+    while (_recycling.load_acquire()) {
       if (os::is_MP()) {
         SpinPause();
       } else {
@@ -636,7 +643,7 @@ void ShenandoahHeapRegion::try_recycle() {
   if (!is_trash()) {
     return;
   }
-  if (_recycling.try_set()) {
+  if (_recycling.compare_set(false, true)) {
     // Double check region state after win the race to set recycling flag
     if (is_trash()) {
       // At freeset rebuild time, which precedes recycling of collection set, we treat all cset regions as
@@ -645,7 +652,8 @@ void ShenandoahHeapRegion::try_recycle() {
       // by more time-precise accounting of these details.
       recycle_internal();
     }
-    _recycling.unset();
+    // A release store is enough here as well, see try_recycle_under_lock().
+    _recycling.release_store(false);
   }
 }
 
diff --git a/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.hpp b/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.hpp
index fb41c95f1df..8d7fb6e220e 100644
--- a/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.hpp
+++ b/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.hpp
@@ -241,52 +241,67 @@ class ShenandoahHeapRegion {
   static size_t MaxTLABSizeBytes;
   static size_t MaxTLABSizeWords;
 
-  // Never updated fields
-  size_t const _index;
+  // NOTE: This class is allocated specially by ShenandoahHeap, starting on cache line
+  // boundary. We have to carefully manage the order of these fields and the total density
+  // of the instance. Sometimes we arrange the fields in "unnatural" order to get more
+  // compact memory representation. If you change/rearrange the fields here, check the new
+  // layout with pahole. ShenandoahHeap::initialize() statically asserts the size limit.
+
+  // We split fields in two groups to hit two different cache lines. The first cache line contains fields
+  // that are read very often but written rarely. The second cache line contains fields updated frequently
+  // during allocation and marking, where/ contention is unfortunate but at least contained.
+
   HeapWord* const _bottom;
   HeapWord* const _end;
+  uint32_t const _index;
 
-  // Rarely updated fields
-  HeapWord* _new_top;
-  double _empty_time;
+  // If this is a humongous region, this index identifies the corresponding humongous start region.
+  // If this is not a humongous region, this field is not used. In debug builds, it is assigned the value
+  // UndefinedRegionIndex to facilitate debugging of state machine.
+  uint32_t _humongous_start_region_index;
+
+  Atomic _state;
 
+  // Set when an evacuation failure self-forwarded at least one object in this
+  // region. The flag is cleared when the region is partially recycled during final-update-refs.
+  Atomic _has_self_forwards;
+
+  // Region age, clamped at markWord::max_age
+  uint8_t _age;
+
+  // This is only read/written by a gc worker to avoid unnecessary bitmap resets
+  bool _needs_bitmap_reset;
+
+  bool _promoted_in_place;
+
+  HeapWord* _new_top;
   HeapWord* _top_before_promoted;
   HeapWord* _top_at_evac_start;
 
-  // Seldom updated fields
-  Atomic _state;
-  HeapWord* _coalesce_and_fill_boundary; // for old regions not selected as collection set candidates.
+  double _empty_time;
 
-  // Frequently updated fields
-  HeapWord* _top;
+  size_t _mixed_candidate_garbage_words;
 
-  size_t _tlab_allocs;
-  size_t _gclab_allocs;
-  size_t _plab_allocs;
+  // For old regions not selected as collection set candidates
+  HeapWord* _coalesce_and_fill_boundary;
 
-  Atomic _live_data;
   Atomic _critical_pins;
 
-  size_t _mixed_candidate_garbage_words;
-
   Atomic _update_watermark;
 
-  uint _age;
-  bool _promoted_in_place;
-
-  ShenandoahSharedFlag _recycling; // Used to indicate that the region is being recycled; see try_recycle*().
+  HeapWord* _top;
 
-  // Set when an evacuation failure self-forwarded at least one object in this
-  // region. The flag is cleared when the region is partially recycled during final-update-refs.
-  ShenandoahSharedFlag _has_self_forwards;
+  // Live data can include humongous region size.
+  Atomic _live_data;
 
-  // This is only read/written by a gc worker to avoid unnecessary bitmap resets
-  bool _needs_bitmap_reset;
+  // Lab allocation counters, in heap words. Their sum is bounded by region_size_words()
+  // only count allocations between bottom() and top(); reset_alloc_metadata() resets them to zero whenever top is reset.
+  uint32_t _tlab_allocs;
+  uint32_t _gclab_allocs;
+  uint32_t _plab_allocs;
 
-  // If this is a humongous region, this index identifies the corresponding humongous start region.
-  // If this is not a humongous region, this field is not used. In debug builds, it is assigned the value
-  // UndefinedRegionIndex to facilitate debugging of state machine.
-  uint32_t _humongous_start_region_index;
+  // Used to indicate that the region is being recycled; see try_recycle*()
+  Atomic _recycling;
 
 public:
   ShenandoahHeapRegion(HeapWord* start, size_t index, bool committed);
@@ -543,9 +558,9 @@ class ShenandoahHeapRegion {
   // Self-forward accounting: set by an evacuating thread after it successfully
   // installs a self-forward mark on an object in this region. Tested and cleared
   // when the region is partially recycled in final-update-refs.
-  bool has_self_forwards() const { return _has_self_forwards.is_set(); }
-  void set_has_self_forwards()   { _has_self_forwards.try_set(); }
-  void clear_has_self_forwards() { _has_self_forwards.unset(); }
+  bool has_self_forwards() const { return _has_self_forwards.load_acquire(); }
+  void set_has_self_forwards()   { if (!_has_self_forwards.load_acquire()) _has_self_forwards.release_store(true); }
+  void clear_has_self_forwards() { _has_self_forwards.release_store(false); }
 
 private:
   void decrement_humongous_waste();
diff --git a/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.inline.hpp b/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.inline.hpp
index 47fc734656e..eed3718a324 100644
--- a/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.inline.hpp
+++ b/src/hotspot/share/gc/shenandoah/shenandoahHeapRegion.inline.hpp
@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2015, 2019, Red Hat, Inc. All rights reserved.
  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
- * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
+#include "utilities/checkedCast.hpp"
 
 HeapWord* ShenandoahHeapRegion::allocate_fill(size_t size) {
   shenandoah_assert_heaplocked_or_safepoint();
@@ -75,11 +76,11 @@ inline void ShenandoahHeapRegion::adjust_alloc_metadata(const ShenandoahAllocReq
   // Only need to update alloc metadata for lab alloc, shared alloc is counted implicitly by tlab/gclab allocs
   if (req.is_lab_alloc()) {
     if (req.is_mutator_alloc()) {
-      _tlab_allocs += size;
+      _tlab_allocs = checked_cast(_tlab_allocs + size);
     } else if (req.is_old()) {
-      _plab_allocs += size;
+      _plab_allocs = checked_cast(_plab_allocs + size);
     } else {
-      _gclab_allocs += size;
+      _gclab_allocs = checked_cast(_gclab_allocs + size);
     }
   }
 }
diff --git a/src/hotspot/share/gc/shenandoah/vmStructs_shenandoah.hpp b/src/hotspot/share/gc/shenandoah/vmStructs_shenandoah.hpp
index 4299bdb8126..cab1abad10f 100644
--- a/src/hotspot/share/gc/shenandoah/vmStructs_shenandoah.hpp
+++ b/src/hotspot/share/gc/shenandoah/vmStructs_shenandoah.hpp
@@ -40,7 +40,7 @@
   static_field(ShenandoahHeapRegion, RegionSizeBytes,              size_t)                                    \
   static_field(ShenandoahHeapRegion, RegionSizeBytesShift,         size_t)                                    \
   nonstatic_field(ShenandoahHeapRegion, _state,                    Atomic) \
-  nonstatic_field(ShenandoahHeapRegion, _index,                    size_t const)                              \
+  nonstatic_field(ShenandoahHeapRegion, _index,                    uint32_t const)                            \
   nonstatic_field(ShenandoahHeapRegion, _bottom,                   HeapWord* const)                           \
   nonstatic_field(ShenandoahHeapRegion, _top,                      HeapWord*)                                 \
   nonstatic_field(ShenandoahHeapRegion, _end,                      HeapWord* const)                           \

From 918aab0c4a9f8a242dad2f2c297d10382df4d306 Mon Sep 17 00:00:00 2001
From: Serguei Spitsyn 
Date: Mon, 23 Nov 2026 19:30:06 +0000
Subject: [PATCH 50/95] 8395356: GetLocalInstance should return OPAQUE_FRAME
 for objects with strict-init fields

Reviewed-by: cjplummer, alanb
---
 src/hotspot/share/prims/jvmti.xml             |  51 +-
 src/hotspot/share/prims/jvmtiImpl.cpp         |  40 +-
 src/hotspot/share/prims/jvmtiImpl.hpp         |   3 -
 .../GetCtorLocalStrictInitFields.java         | 626 ++++++++++++++++++
 .../libGetCtorLocalStrictInitFields.cpp       | 106 +++
 .../GetCtorLocal/libValueGetCtorLocal.cpp     |  32 +-
 .../vm/mlvm/share/jpda/StratumUtils.java      |   5 +-
 test/jdk/ProblemList.txt                      |   1 +
 8 files changed, 785 insertions(+), 79 deletions(-)
 create mode 100644 test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/GetCtorLocalStrictInitFields.java
 create mode 100644 test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libGetCtorLocalStrictInitFields.cpp

diff --git a/src/hotspot/share/prims/jvmti.xml b/src/hotspot/share/prims/jvmti.xml
index 3a7b839db93..887d4f8d08a 100644
--- a/src/hotspot/share/prims/jvmti.xml
+++ b/src/hotspot/share/prims/jvmti.xml
@@ -5916,10 +5916,18 @@ class C2 extends C1 implements I2 {
         This function can be used to retrieve the value of a local
         variable whose type is Object or a subclass of Object.
         

- When preview features are enabled, if the local is the "this" - object and "this" is a value object under construction, the - function retrieves a snapshot of the "this" object representing - the value object's state at the point the snapshot is taken. + When preview features are enabled, the requested slot is zero, + and the specified frame is a constructor frame whose declaring class + or any of its superclasses has + + strictly-initializedPREVIEW instance fields, + the function returns JVMTI_ERROR_OPAQUE_FRAME. +

+ API Note: + + Value classesPREVIEW rely upon strict field + initialization. This function cannot be used to obtain the "this" + object from a constructor of a value class with one or more instance fields.

The specified thread must be suspended or must be the current thread. @@ -5950,11 +5958,6 @@ class C2 extends C1 implements I2 { On return, points to the variable's value. - When preview features are enabled, if the local is the "this" - object and "this" is a value object under construction, - value_ptr will point to a snapshot of the "this" - object representing the value object's state at the point the snapshot - is taken. @@ -5969,6 +5972,11 @@ class C2 extends C1 implements I2 { The implementation is unable to get the frame locals (e.g. the frame at depth is executing a native method). + Also, when preview features are enabled, the requested slot is zero, + and the specified frame is a constructor frame whose declaring class + or any of its superclasses has + + strictly-initializedPREVIEW instance fields. Thread was not suspended and was not the current thread. @@ -5985,10 +5993,17 @@ class C2 extends C1 implements I2 { native method frames, whereas GetLocalObject() would return JVMTI_ERROR_OPAQUE_FRAME in those cases.

- When preview features are enabled and the "this" object is - a value object under construction, the function retrieves a snapshot of the - "this" object that represents the value object's state at - the point the snapshot is taken. + When preview features are enabled and the specified frame is a + constructor frame whose declaring class or any of its superclasses has + + strictly-initializedPREVIEW instance fields, + the function returns JVMTI_ERROR_OPAQUE_FRAME. +

+ API Note: + + Value classesPREVIEW rely upon strict field + initialization. This function cannot be used to obtain the "this" + object from a constructor of a value class with one or more instance fields.

The specified thread must be suspended or must be the current thread. @@ -6013,10 +6028,6 @@ class C2 extends C1 implements I2 { On return, points to the variable's value. - When preview features are enabled, and the "this" object is - a value object under construction, value_ptr will point to - a snapshot of the "this" object representing the value - object's state at the point the snapshot is taken. @@ -6024,6 +6035,12 @@ class C2 extends C1 implements I2 { If the specified frame is a static method frame. + + When preview features are enabled and the specified frame is a + constructor frame whose declaring class or any of its superclasses has + + strictly-initializedPREVIEW instance fields. + Thread was not suspended and was not the current thread. diff --git a/src/hotspot/share/prims/jvmtiImpl.cpp b/src/hotspot/share/prims/jvmtiImpl.cpp index ec5b157d59c..b148e7b3c82 100644 --- a/src/hotspot/share/prims/jvmtiImpl.cpp +++ b/src/hotspot/share/prims/jvmtiImpl.cpp @@ -334,7 +334,6 @@ VM_BaseGetOrSetLocal::VM_BaseGetOrSetLocal(JavaThread* calling_thread, jint dept , _jvf(nullptr) , _set(set) , _self(self) - , _need_clone(false) , _result(JVMTI_ERROR_NONE) { } @@ -484,34 +483,6 @@ bool VM_BaseGetOrSetLocal::check_slot_type_no_lvt(javaVFrame* jvf) { return true; } -void VM_BaseGetOrSetLocal::check_and_clone_this_value_object() { - oop obj = JNIHandles::resolve(_value.l); - HandleMark hm(_calling_thread); - Handle obj_h(_calling_thread, obj); - - assert(_type == T_OBJECT, "sanity check"); - assert(obj != nullptr, "expected non-null oop"); - assert(obj_h()->is_value(), "expected value oop"); - assert(_index == 0, "expected slot 0 for THIS object"); - - ValueKlass* klass = ValueKlass::cast(obj_h()->klass()); - valueOop obj_copy = klass->allocate_instance(_calling_thread); - if (obj_copy == nullptr) { - _result = JVMTI_ERROR_OUT_OF_MEMORY; - } else { - valueOop thisObj = valueOop(obj_h()); - // copy object payload into the object snapshot - BufferedValuePayload src(thisObj); - BufferedValuePayload dst(obj_copy, klass); - src.copy_to(dst); - - // Must ensure the content of the buffered value is visible - // before publishing the buffered value oop - OrderAccess::storestore(); - } - _value.l = JNIHandles::make_local(_calling_thread, obj_copy); -} - static bool can_be_deoptimized(vframe* vf) { return (vf->is_compiled_frame() && vf->fr().can_be_deoptimized()); } @@ -649,8 +620,9 @@ void VM_BaseGetOrSetLocal::doit() { if (Arguments::is_valhalla_enabled()) { bool is_ctor = _jvf->method()->is_object_constructor(); - if (is_ctor && _index == 0 && obj != nullptr && obj->is_value()) { - _need_clone = true; // need to allocate an object snapshot in doit_epilogue + if (is_ctor && _index == 0 && _jvf->method()->method_holder()->has_strict_instance_fields_in_hierarchy()) { + _result = JVMTI_ERROR_OPAQUE_FRAME; // can't expose THIS object in Ctor frame with strict-init instance fields + return; } } _value.l = JNIHandles::make_local(_calling_thread, obj); @@ -662,12 +634,6 @@ void VM_BaseGetOrSetLocal::doit() { } } -void VM_BaseGetOrSetLocal::doit_epilogue() { - if (_need_clone) { - check_and_clone_this_value_object(); - } -} - bool VM_BaseGetOrSetLocal::allow_nested_vm_operations() const { return true; // May need to deoptimize } diff --git a/src/hotspot/share/prims/jvmtiImpl.hpp b/src/hotspot/share/prims/jvmtiImpl.hpp index 113684664e6..8bb814e5b5c 100644 --- a/src/hotspot/share/prims/jvmtiImpl.hpp +++ b/src/hotspot/share/prims/jvmtiImpl.hpp @@ -183,7 +183,6 @@ class VM_BaseGetOrSetLocal : public VM_Operation { javaVFrame* _jvf; bool _set; bool _self; - bool _need_clone; // THIS object is in a value object constructor static const jvalue _DEFAULT_VALUE; @@ -196,7 +195,6 @@ class VM_BaseGetOrSetLocal : public VM_Operation { virtual javaVFrame* get_java_vframe() = 0; bool check_slot_type_lvt(javaVFrame* vf); bool check_slot_type_no_lvt(javaVFrame* vf); - void check_and_clone_this_value_object(); public: VM_BaseGetOrSetLocal(JavaThread* calling_thread, jint depth, jint index, @@ -206,7 +204,6 @@ class VM_BaseGetOrSetLocal : public VM_Operation { jvmtiError result() { return _result; } void doit(); - void doit_epilogue(); bool allow_nested_vm_operations() const; virtual const char* name() const = 0; diff --git a/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/GetCtorLocalStrictInitFields.java b/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/GetCtorLocalStrictInitFields.java new file mode 100644 index 00000000000..03c0f8590e6 --- /dev/null +++ b/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/GetCtorLocalStrictInitFields.java @@ -0,0 +1,626 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8395356 + * @summary Test GetLocalInstance/GetLocalObject when the target thread's top frame is + * constructor or method of a class with strictly-initialized fields. + * @enablePreview + * @requires vm.jvmti + * @library /test/lib + * @build ${test.main.class} + * @run driver jdk.test.lib.helpers.StrictProcessor + * GetCtorLocalStrictInitFields$ConstructorBeforeAndAfterSuper1$TestClass + * GetCtorLocalStrictInitFields$ConstructorBeforeAndAfterSuper2$SuperClass + * GetCtorLocalStrictInitFields$ConstructorBeforeAndAfterSuper3$TestClass + * GetCtorLocalStrictInitFields$ConstructorBeforeAndAfterThis$TestClass + * GetCtorLocalStrictInitFields$MethodAfterSuper$TestClass + * GetCtorLocalStrictInitFields$MethodAfterInit$TestClass + * @run junit/othervm/native --enable-native-access=ALL-UNNAMED + * -XX:CompileCommand=exclude,GetCtorLocalStrictInitFields$ValueClassConstructor2$TestClass:: + * -agentlib:GetCtorLocalStrictInitFields ${test.main.class} + */ + +import java.lang.ref.Reference; +import jdk.test.lib.helpers.StrictInit; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import static org.junit.jupiter.api.Assertions.*; + +class GetCtorLocalStrictInitFields { + + private static final int JVMTI_ERROR_NONE = 0; + private static final int JVMTI_ERROR_OPAQUE_FRAME = 32; + + /** + * Base class to test GetLocalInstance/GetLocalObject. + */ + abstract class GetCtorLocalTest { + volatile boolean ready; + volatile boolean canContinue; + volatile Throwable exception; + + void checkException(Throwable t) { + if (t != null) { + throw new RuntimeException("target thread threw exception", t); + } + } + + /** + * Starts a thread to execute the given action. The action is expected to spin + * at the given class/method. Once spinning, the thread is suspended and testGetLocalInstance + * is invoked to attempt to test GetLocalInstance/GetLocalObject. + * @return the error code from testGetLocalInstance + */ + int test(Executable action, Class targetClass, String targetMethod) throws Exception { + assertFalse(ready, "Test already executed"); + Thread thread = Thread.ofPlatform().start(() -> { + try { + action.execute(); + } catch (Throwable ex) { + exception = ex; + } + }); + int err; + boolean suspended = false; + try { + // wait for target thread to spin + while (!ready) { + checkException(exception); + Thread.sleep(10); + } + assertEquals(JVMTI_ERROR_NONE, suspendThread(thread)); + suspended = true; + assertTopFrame(thread, targetClass, targetMethod); + err = testGetLocalInstance(thread); + } finally { + canContinue = true; + if (suspended) resumeThread(thread); + thread.join(); + } + checkException(exception); + return err; + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is the + * constructor of a class with a strictly-initialized instance field. + */ + @Nested + class ConstructorBeforeAndAfterSuper1 extends GetCtorLocalTest { + class TestClass { + @StrictInit + private int x; + + TestClass(GetCtorLocalTest test, int where) { + x = 100; + + // before super + if (where == 1) { + test.ready = true; + while (!test.canContinue) {} + } + + super(); + + // after super + if (where == 2) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + @Test + void testBeforeSuper() throws Exception { + int err = test(() -> new TestClass(this, 1), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testAfterSuper() throws Exception { + int err = test(() -> new TestClass(this, 2), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is the + * constructor or super-constructor of a class with a strictly-initialized + * instance field. The strict field is declared in the super class. + */ + @Nested + class ConstructorBeforeAndAfterSuper2 extends GetCtorLocalTest { + class SuperClass { + @StrictInit + private int x; + + SuperClass(GetCtorLocalTest test, int where) { + x = 100; + + // before super + if (where == 1) { + test.ready = true; + while (!test.canContinue) {} + } + + super(); + this.superClassMethod(test, where); + + // after super + if (where == 3) { + test.ready = true; + while (!test.canContinue) {} + } + } + + void superClassMethod(GetCtorLocalTest test, int where) { + if (where == 2) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + class TestClass extends SuperClass { + TestClass(GetCtorLocalTest test, int where) { + // before super + if (where == 4) { + test.ready = true; + while (!test.canContinue) {} + } + + super(test, where); + this.testClassMethod(test, where); + + // after super + if (where == 6) { + test.ready = true; + while (!test.canContinue) {} + } + } + + void testClassMethod(GetCtorLocalTest test, int where) { + if (where == 5) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + @Test + void testBeforeSuperSuper() throws Exception { + int err = test(() -> new TestClass(this, 1), SuperClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testSuperClassMethod() throws Exception { + int err = test(() -> new TestClass(this, 2), SuperClass.class, "superClassMethod"); + assertEquals(JVMTI_ERROR_NONE, err); + } + + @Test + void testAfterSuperSuper() throws Exception { + int err = test(() -> new TestClass(this, 3), SuperClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testBeforeSuper() throws Exception { + int err = test(() -> new TestClass(this, 4), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testTestClassMethod() throws Exception { + int err = test(() -> new TestClass(this, 5), TestClass.class, "testClassMethod"); + assertEquals(JVMTI_ERROR_NONE, err); + } + + @Test + void testAfterSuper() throws Exception { + int err = test(() -> new TestClass(this, 6), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is the + * constructor or super-constructor of a class with a strictly-initialized + * instance field. The strict field is declared in the sub class. + */ + @Nested + class ConstructorBeforeAndAfterSuper3 extends GetCtorLocalTest { + class SuperClass { + SuperClass(GetCtorLocalTest test, int where) { + // before super + if (where == 1) { + test.ready = true; + while (!test.canContinue) {} + } + + super(); + this.superClassMethod(test, where); + + // after super + if (where == 3) { + test.ready = true; + while (!test.canContinue) {} + } + } + + void superClassMethod(GetCtorLocalTest test, int where) { + if (where == 2) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + class TestClass extends SuperClass { + @StrictInit + private int x; + + TestClass(GetCtorLocalTest test, int where) { + x = 100; + + // before super + if (where == 4) { + test.ready = true; + while (!test.canContinue) {} + } + + super(test, where); + this.testClassMethod(test, where); + + // after super + if (where == 6) { + test.ready = true; + while (!test.canContinue) {} + } + } + + void testClassMethod(GetCtorLocalTest test, int where) { + if (where == 5) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + @Test + void testBeforeSuperSuper() throws Exception { + // no strict fields in SuperClass or its superclasses + int err = test(() -> new TestClass(this, 1), SuperClass.class, ""); + assertEquals(JVMTI_ERROR_NONE, err); + } + + @Test + void testSuperClassMethod() throws Exception { + int err = test(() -> new TestClass(this, 2), SuperClass.class, "superClassMethod"); + assertEquals(JVMTI_ERROR_NONE, err); + } + + @Test + void testAfterSuperSuper() throws Exception { + // no strict fields in SuperClass or its superclasses + int err = test(() -> new TestClass(this, 3), SuperClass.class, ""); + assertEquals(JVMTI_ERROR_NONE, err); + } + + @Test + void testBeforeSuper() throws Exception { + int err = test(() -> new TestClass(this, 4), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testTestClassMethod() throws Exception { + int err = test(() -> new TestClass(this, 5), TestClass.class, "testClassMethod"); + assertEquals(JVMTI_ERROR_NONE, err); + } + + @Test + void testAfterSuper() throws Exception { + int err = test(() -> new TestClass(this, 6), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is the + * constructor of a class with a strictly-initialized instance field + * before it chains to another constructor to set the field. + */ + @Nested + class ConstructorBeforeAndAfterThis extends GetCtorLocalTest { + class TestClass { + @StrictInit + private int x; + + TestClass() { + x = 100; + super(); + } + + TestClass(GetCtorLocalTest test, int where) { + // before this + if (where == 1) { + test.ready = true; + while (!test.canContinue) {} + } + + this(); + + // after this + if (where == 2) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + @Test + void testBeforeThis() throws Exception { + int err = test(() -> new TestClass(this, 1), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testAfterThis() throws Exception { + int err = test(() -> new TestClass(this, 2), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is the + * constructor of a value class with an instance field. Value classes + * rely upon strict field initialization. + */ + @Nested + class ValueClassConstructor1 extends GetCtorLocalTest { + value class TestClass { + private int x; + + TestClass(GetCtorLocalTest test, int where) { + x = 100; + + // before super + if (where == 1) { + test.ready = true; + while (!test.canContinue) {} + } + + super(); + + // after super + if (where == 2) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + @BeforeAll() + static void verifyPreconditions() throws Exception { + assertTrue(TestClass.class.getDeclaredField("x").isStrictInit(), + "expected to be strict field"); + } + + @Test + void testBeforeSuper() throws Exception { + int err = test(() -> new TestClass(this, 1), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testAfterSuper() throws Exception { + int err = test(() -> new TestClass(this, 2), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is the + * constructor of a value class with no instance fields. + */ + @Nested + class ValueClassConstructor2 extends GetCtorLocalTest { + static value class TestClass { + TestClass(GetCtorLocalTest test, int where) { + // before super + if (where == 1) { + test.ready = true; + while (!test.canContinue) {} + } + + super(); + + // after super + if (where == 2) { + test.ready = true; + while (!test.canContinue) {} + } + // The value class has no instance fields. + // JIT compiler can remove the THIS object as it is not used in the constructor. + // But it is needed in the call to testGetLocalInstance() which checks the value + // returned by the JVMTI GetLocalInstance() and GetLocalObject() for slot 0. + Reference.reachabilityFence(this); + } + } + + @Test + void testBeforeSuper() throws Exception { + // no strict fields + int err = test(() -> new TestClass(this, 1), TestClass.class, ""); + assertEquals(JVMTI_ERROR_NONE, err); + } + + @Test + void testAfterSuper() throws Exception { + // no strict fields + int err = test(() -> new TestClass(this, 2), TestClass.class, ""); + assertEquals(JVMTI_ERROR_NONE, err); + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is the + * constructor of a record with an instance field. Record fields are strict + * fields when compiled with preview features enabled. + */ + @Nested + class RecordConstructor extends GetCtorLocalTest { + record TestClass(int x) { + TestClass(GetCtorLocalTest test, int where, int x) { + // before this + if (where == 1) { + test.ready = true; + while (!test.canContinue) {} + } + + this(x); + + // after this + if (where == 2) { + test.ready = true; + while (!test.canContinue) {} + } + } + } + + @BeforeAll() + static void verifyPreconditions() throws Exception { + assertTrue(TestClass.class.getDeclaredField("x").isStrictInit(), + "expected to be strict field"); + } + + @Test + void testBeforeThis() throws Exception { + int err = test(() -> new TestClass(this, 1, 100), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + + @Test + void testAfterThis() throws Exception { + int err = test(() -> new TestClass(this, 2, 100), TestClass.class, ""); + assertEquals(JVMTI_ERROR_OPAQUE_FRAME, err); + } + } + + /** + * Test that GetLocalInstance/GetLocalObject can get the THIS object from an instance + * method invoked by a constructor after super(), even though the object's class + * has strictly-initialized fields and construction is ongoing. + */ + @Nested + class MethodAfterSuper extends GetCtorLocalTest { + static volatile boolean postInitFinished; + static volatile boolean initFinished; + + class TestClass { + @StrictInit + private int x; + + TestClass(MethodAfterSuper test) { + x = 100; + super(); + postInit(test); + initFinished = true; + } + + void postInit(MethodAfterSuper test) { + // spin here until testGetLocalInstance executes + test.ready = true; + while (!test.canContinue) {} + + postInitFinished = true; + } + } + + @Test + void test() throws Exception { + int err = test(() -> new TestClass(this), TestClass.class, "postInit"); + assertEquals(JVMTI_ERROR_NONE, err); + assertTrue(postInitFinished, "postInit method should not have returned early"); + assertTrue(initFinished, " did not finish"); + } + } + + /** + * Test GetLocalInstance/GetLocalObject when the target thread's top frame is a method of a + * class with a strictly-initialized instance field. This test ensures that + * GetLocalInstance/GetLocalObject return normally when the top frame is a method of + * a class with strictly-initialized fields. + */ + @Nested + class MethodAfterInit extends GetCtorLocalTest { + static volatile boolean runFinished; + + class TestClass { + @StrictInit + private int x; + + TestClass() { + x = 100; + super(); + } + + void run(MethodAfterInit test) { + // spin here until testGetLocalInstance executes + test.ready = true; + while (!test.canContinue) {} + + runFinished = true; + } + } + + @Test + void test() throws Exception { + var obj = new TestClass(); + int err = test(() -> obj.run(this), TestClass.class, "run"); + assertEquals(JVMTI_ERROR_NONE, err); + assertTrue(runFinished, "run method should not have returned early"); + } + } + + /** + * Asserts that the given thread's top frame is the expected class/method. + */ + static void assertTopFrame(Thread thread, Class clazz, String methodName) { + StackTraceElement[] stack = thread.getStackTrace(); + assertTrue(stack.length > 0); + assertEquals(clazz.getName(), stack[0].getClassName()); + assertEquals(methodName, stack[0].getMethodName()); + } + + static native int suspendThread(Thread thread); + static native int resumeThread(Thread thread); + static native int testGetLocalInstance(Thread thread); +} diff --git a/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libGetCtorLocalStrictInitFields.cpp b/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libGetCtorLocalStrictInitFields.cpp new file mode 100644 index 00000000000..329358e53d0 --- /dev/null +++ b/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libGetCtorLocalStrictInitFields.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include +#include "jni.h" +#include "jvmti.h" +#include "jvmti_common.hpp" + +static jvmtiEnv *jvmti; + +extern "C" { + +extern JNIEXPORT jint JNICALL +Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) { + jvmtiError err; + jvmtiCapabilities caps; + + if (jvm->GetEnv((void **) &jvmti, JVMTI_VERSION) != JNI_OK) { + return JNI_ERR; + } + + memset(&caps, 0, sizeof(caps)); + caps.can_suspend = 1; + caps.can_access_local_variables = 1; + err = jvmti->AddCapabilities( &caps); + if (err != JVMTI_ERROR_NONE) { + return JNI_ERR; + } + + return JNI_OK; +} + +JNIEXPORT jint JNICALL +Java_GetCtorLocalStrictInitFields_suspendThread(JNIEnv *jni, jclass ignore, jthread target) { + return (jint) jvmti->SuspendThread(target); +} + +JNIEXPORT jint JNICALL +Java_GetCtorLocalStrictInitFields_resumeThread(JNIEnv *jni, jclass ignore, jthread target) { + return (jint) jvmti->ResumeThread(target); +} + + +JNIEXPORT jint JNICALL +Java_GetCtorLocalStrictInitFields_testGetLocalInstance(JNIEnv *jni, jclass ignore, jthread thread) { + const jint depth = 0; + + jmethodID method = get_frame_method(jvmti, jni, thread, depth); + char* mname = get_method_name(jvmti, jni, method); + jobject obj_this = nullptr; + jobject obj0 = nullptr; + jobject obj1 = nullptr; + + LOG("\ntestGetLocalInstance: frame method: %s\n", mname); + + jvmtiError err = jvmti->GetLocalInstance(thread, depth, &obj_this); + LOG("testGetLocalInstance: GetLocalInstance returned error code: %s (%d)\n", TranslateError(err), err); + + jvmtiError err_obj = jvmti->GetLocalObject(thread, depth, 0, &obj0); + LOG("testGetLocalInstance: GetLocalObject for slot 0 returned error code: %s (%d)\n", TranslateError(err_obj), err_obj); + + jvmtiError err_obj1 = jvmti->GetLocalObject(thread, depth, 1, &obj1); + LOG("testGetLocalInstance: GetLocalObject for slot 1 returned error code: %s (%d)\n", TranslateError(err_obj1), err_obj1); + check_jvmti_status(jni, err_obj1, "GetLocalObject for slot 1"); + + if (err_obj != err) { + LOG("Failed: expected from GetLocalObject same error code as from GetLocalInstance: expected %s (%d), got: %s (%d)\n", + TranslateError(err), err, TranslateError(err_obj), err_obj); + + jni->FatalError("Failed: expected from GetLocalObject same error code as from GetLocalInstance"); + } + if (err == JVMTI_ERROR_NONE) { + if ((obj_this == nullptr || obj0 == nullptr)) { + LOG("Failed: expected non-null object refs from GetLocalInstance (%p) and GetLocalObject(%p)\n", obj_this, obj0); + jni->FatalError("Failed: expected non-null object refs from GetLocalInstance and GetLocalObject"); + } + if (!jni->IsSameObject(obj_this, obj0)) { + LOG("Failed: expected GetLocalInstance (%p) and GetLocalObject(%p) to return same object\n", obj_this, obj0); + jni->FatalError("Failed: GetLocalInstance and GetLocalObject returned different object refs"); + } + } + deallocate(jvmti, jni, (void*)mname); + return (jint)err; +} + +} diff --git a/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libValueGetCtorLocal.cpp b/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libValueGetCtorLocal.cpp index b1ac4fee5e0..472b8befd0a 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libValueGetCtorLocal.cpp +++ b/test/hotspot/jtreg/serviceability/jvmti/valhalla/GetCtorLocal/libValueGetCtorLocal.cpp @@ -32,7 +32,6 @@ extern "C" { #endif static jvmtiEnv *jvmti = nullptr; -static jobject cached_this = nullptr; JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) { @@ -60,28 +59,25 @@ Java_ValueGetCtorLocal_testCtorThis(JNIEnv *jni, jclass thisClass, jthread threa jmethodID method = get_frame_method(jvmti, jni, thread, depth); char* mname = get_method_name(jvmti, jni, method); + jobject obj0 = nullptr; + jobject obj_this = nullptr; + jvmtiError err; LOG("\ntestCtorThis: frame method: %s\n", mname); - jobject obj0 = get_local_object(jvmti, jni, thread, depth, 0); - jobject obj_this = get_local_instance(jvmti, jni, thread, depth); - // obj0 is expected to be equal to "this" - jboolean is_equal = jni->IsSameObject(obj0, obj_this); - LOG("testCtorThis: obj0: %p obj_this: %p objects are equal: %d\n", - (void*)obj0, (void*)obj_this, is_equal); - - if (!is_equal) { - fatal(jni, "Failed: obj0 != obj_this\n"); + err = jvmti->GetLocalObject(thread, depth, 0, & obj0); + if (err != JVMTI_ERROR_OPAQUE_FRAME) { + LOG("Failed: unexpected error from GetLocalObject: %s (%d), expected: JVMTI_ERROR_OPAQUE_FRAME\n", TranslateError(err), err); + jni->FatalError("Failed: expected JVMTI_ERROR_OPAQUE_FRAME from JVMTI GetLocalObject for THIS object in Ctor with strict-init instance fields"); } - if (cached_this == nullptr) { // first call to testCtorThis - cached_this = jni->NewGlobalRef(obj_this); - } else { - // cached_this must be a snapshot that does not mutate - // when the ctor changes field values - if (jni->IsSameObject(cached_this, obj_this)) { - fatal(jni, "Failed: unexpected: cached_this == obj_this\n"); - } + LOG("Got expected JVMTI_ERROR_OPAQUE_FRAME error code from GetLocalObject for THIS value object in construction\n"); + + err = jvmti->GetLocalInstance(thread, depth, & obj_this); + if (err != JVMTI_ERROR_OPAQUE_FRAME) { + LOG("Failed: unexpected error from GetLocalInstance: %s (%d), expected: JVMTI_ERROR_OPAQUE_FRAME\n", TranslateError(err), err); + jni->FatalError("Failed: expected JVMTI_ERROR_OPAQUE_FRAME from JVMTI GetLocalInstance for object in Ctor with strict-init instance fields"); } + LOG("Got expected JVMTI_ERROR_OPAQUE_FRAME error code from GetLocalInstance for object in Ctor with strict-init instance fields\n"); deallocate(jvmti, jni, (void*)mname); } diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/share/jpda/StratumUtils.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/share/jpda/StratumUtils.java index 1c398cbd449..7da3b79c42d 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/share/jpda/StratumUtils.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/share/jpda/StratumUtils.java @@ -73,10 +73,7 @@ public static StratumInfo parseStratumInfo(String stratumInfo) throws Exception } public static String getStrataStr(StackFrame sf) { - ObjectReference thisObject = sf.thisObject(); - if (thisObject == null) - return "(no strata)"; - return StratumUtils.getStrataStr(thisObject.referenceType()); + return StratumUtils.getStrataStr(sf.location().declaringType()); } public static String getStrataStr(ReferenceType ref) { diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index 4efaeb4e52f..ad79e57c903 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -530,6 +530,7 @@ javax/swing/plaf/synth/7158712/bug7158712.java 8324782 macosx-all # jdk_jdi com/sun/jdi/InvokeHangTest.java 8218463 linux-all +com/sun/jdi/valhalla/CtorDebuggingTest.java 8395763 generic-all ############################################################################ From 1eb06f3d709af3d39989acc6063cca8cf0d6764a Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Mon, 23 Nov 2026 19:47:34 +0000 Subject: [PATCH 51/95] 8397517: [Leyden] Use ciEnv::is_aot_compile() instead of AOTCodeCache::is_on_for_dump() during AOT compilation Reviewed-by: iveresov, asmehra, adinn --- .../cpu/aarch64/c1_LIRAssembler_aarch64.cpp | 4 ++-- .../gc/g1/g1BarrierSetAssembler_aarch64.cpp | 14 ++++++++++---- .../shenandoahBarrierSetAssembler_aarch64.cpp | 2 +- src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp | 5 +++-- .../templateInterpreterGenerator_aarch64.cpp | 2 +- src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp | 2 +- .../riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp | 14 ++++++++++---- .../shenandoahBarrierSetAssembler_riscv.cpp | 2 +- src/hotspot/cpu/riscv/macroAssembler_riscv.cpp | 3 ++- src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp | 4 ++-- .../cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp | 14 ++++++++++---- .../shenandoahBarrierSetAssembler_x86.cpp | 2 +- src/hotspot/cpu/x86/macroAssembler_x86.cpp | 6 ++++-- .../cpu/x86/templateInterpreterGenerator_x86.cpp | 2 +- src/hotspot/share/asm/macroAssembler_common.hpp | 2 +- .../share/gc/shared/c1/cardTableBarrierSetC1.cpp | 2 +- .../share/gc/shared/c2/cardTableBarrierSetC2.cpp | 2 +- src/hotspot/share/opto/compile.hpp | 2 +- src/hotspot/share/opto/memnode.cpp | 5 ++--- 19 files changed, 55 insertions(+), 34 deletions(-) diff --git a/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp index c7d4f35081f..18558431ac7 100644 --- a/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp @@ -493,7 +493,7 @@ void LIR_Assembler::return_op(LIR_Opr result, C1SafepointPollStub* code_stub) { if (vk->can_be_returned_as_fields()) { address unpack_handler = vk->unpack_handler(); assert(unpack_handler != nullptr, "must be"); - if (AOTCodeCache::is_on_for_dump()) { + if (compilation()->env()->is_aot_compile()) { // in AOT compiled code call the unpack handler indirectly // via the klass. The handler's blob does not currently get // saved to the archive. So, a direct call to the handler @@ -598,7 +598,7 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: { assert(patch_code == lir_patch_none, "no patching handled here"); - if (AOTCodeCache::is_on_for_dump()) { + if (compilation()->env()->is_aot_compile()) { address b = c->as_pointer(); if (b == (address)ThreadIdentifier::unsafe_offset()) { __ lea(dest->as_register_lo(), ExternalAddress(b)); diff --git a/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp index 9756de27c9b..ba726d53c04 100644 --- a/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp @@ -241,6 +241,7 @@ static void generate_post_barrier(MacroAssembler* masm, const Register tmp1, const Register tmp2, Label& done, + bool use_aot_runtime_const, bool new_val_may_be_null) { assert(thread == rthread, "must be"); assert_different_registers(store_addr, new_val, thread, tmp1, tmp2, noreg, rscratch1); @@ -249,7 +250,7 @@ static void generate_post_barrier(MacroAssembler* masm, // AOT code needs to load the barrier grain shift from the aot // runtime constants area in the code cache otherwise we can compile // it as an immediate operand - if (AOTCodeCache::is_on_for_dump()) { + if (INCLUDE_CDS && use_aot_runtime_const) { address grain_shift_address = (address)AOTRuntimeConstants::grain_shift_address(); __ eor(tmp1, store_addr, new_val); __ lea(tmp2, ExternalAddress(grain_shift_address)); @@ -288,7 +289,10 @@ void G1BarrierSetAssembler::g1_write_barrier_post(MacroAssembler* masm, Register tmp1, Register tmp2) { Label done; - generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, false /* new_val_may_be_null */); + // This method is used only for interpreter, adapter and stub code generation. + // Use the AOT cache dump state to determine the usage of AOT runtime constants. + bool use_aot_runtime_const = AOTCodeCache::is_on_for_dump(); + generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, use_aot_runtime_const, false /* new_val_may_be_null */); __ bind(done); } @@ -350,7 +354,8 @@ void G1BarrierSetAssembler::g1_write_barrier_post_c2(MacroAssembler* masm, Register tmp2, bool new_val_may_be_null) { Label done; - generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, new_val_may_be_null); + bool use_aot_runtime_const = Compile::current()->is_aot_compile(); + generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, use_aot_runtime_const, new_val_may_be_null); __ bind(done); } @@ -473,7 +478,8 @@ void G1BarrierSetAssembler::g1_write_barrier_post_c1(MacroAssembler* masm, Register tmp1, Register tmp2) { Label done; - generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, true /* new_val_may_be_null */); + bool use_aot_runtime_const = ciEnv::current()->is_aot_compile(); + generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, use_aot_runtime_const, true /* new_val_may_be_null */); masm->bind(done); } diff --git a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp index 1a491646022..2ebfe916015 100644 --- a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp @@ -954,7 +954,7 @@ void ShenandoahBarrierStubC2::lrb(MacroAssembler& masm) { } // Cset-check. Fall-through to slow if in collection set. - bool is_aot = AOTCodeCache::is_on_for_dump(); + const bool is_aot = Compile::current()->is_aot_compile(); if (!is_aot) { __ mov(_tmp1, ShenandoahHeap::in_cset_fast_test_addr()); if (_narrow) { diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp index b85f4aa4eeb..c9873057b21 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp @@ -5966,7 +5966,7 @@ void MacroAssembler::load_byte_map_base(Register reg) { void MacroAssembler::load_aotrc_address(Register reg, address a) { #if INCLUDE_CDS assert(AOTRuntimeConstants::contains(a), "address out of range for data area"); - if (AOTCodeCache::is_on_for_dump()) { + if (ciEnv::current()->is_aot_compile()) { // all aotrc field addresses should be registered in the AOTCodeCache address table lea(reg, ExternalAddress(a)); } else { @@ -7104,6 +7104,7 @@ void MacroAssembler::verified_entry(Compile* C, int sp_inc, bool do_stack_bang) int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_interpreter) { assert(ValueTypeReturnedAsFields, "Value types should never be returned as fields"); + assert(vk == nullptr || !from_interpreter, "Interpreter passes only nullptr for vk"); // A value type might be returned. If fields are in registers we // need to allocate a value type instance and initialize it with // the value of the fields. @@ -7165,7 +7166,7 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i } // 3. Initialize its fields with a value class specific handler if (vk != nullptr) { - if (AOTCodeCache::is_on_for_dump()) { + if (ciEnv::current()->is_aot_compile()) { // in AOT compiled code call the pack handler indirectly via // the klass. The handler's blob does not currently get saved // to the archive. So, a direct call to the handler address diff --git a/src/hotspot/cpu/aarch64/templateInterpreterGenerator_aarch64.cpp b/src/hotspot/cpu/aarch64/templateInterpreterGenerator_aarch64.cpp index eb12ab6c88d..e037ffc3fc4 100644 --- a/src/hotspot/cpu/aarch64/templateInterpreterGenerator_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/templateInterpreterGenerator_aarch64.cpp @@ -470,7 +470,7 @@ address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize)); if (state == atos && ValueTypeReturnedAsFields) { - __ store_value_type_fields_to_buf(nullptr, true); + __ store_value_type_fields_to_buf(nullptr, true /* from_interpreter */); } __ restore_bcp(); diff --git a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp index df2de59e677..7d4140a0c96 100644 --- a/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/c1_LIRAssembler_riscv.cpp @@ -445,7 +445,7 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: assert(patch_code == lir_patch_none, "no patching handled here"); - if (AOTCodeCache::is_on_for_dump()) { + if (compilation()->env()->is_aot_compile()) { address b = c->as_pointer(); if (b == (address)ThreadIdentifier::unsafe_offset()) { __ la(dest->as_register_lo(), ExternalAddress(b)); diff --git a/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp index 5cda49845c1..9b517f16e2f 100644 --- a/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/g1/g1BarrierSetAssembler_riscv.cpp @@ -254,6 +254,7 @@ static void generate_post_barrier(MacroAssembler* masm, const Register tmp1, const Register tmp2, Label& done, + bool use_aot_runtime_const, bool new_val_may_be_null) { assert(thread == xthread, "must be"); assert_different_registers(store_addr, new_val, thread, tmp1, tmp2, noreg); @@ -261,7 +262,7 @@ static void generate_post_barrier(MacroAssembler* masm, // AOT code needs to load the barrier grain shift from the aot // runtime constants area in the code cache otherwise we can compile // it as an immediate operand - if (AOTCodeCache::is_on_for_dump()) { + if (INCLUDE_CDS && use_aot_runtime_const) { __ xorr(tmp1, store_addr, new_val); __ lwu(tmp2, ExternalAddress(AOTRuntimeConstants::grain_shift_address())); __ srl(tmp1, tmp1, tmp2); @@ -309,7 +310,10 @@ void G1BarrierSetAssembler::g1_write_barrier_post(MacroAssembler* masm, Register tmp1, Register tmp2) { Label done; - generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, true /* new_val_may_be_null */); + // This method is used only for interpreter, adapter and stub code generation. + // Use the AOT cache dump state to determine the usage of AOT runtime constants. + bool use_aot_runtime_const = AOTCodeCache::is_on_for_dump(); + generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, use_aot_runtime_const, true /* new_val_may_be_null */); __ bind(done); } @@ -370,7 +374,8 @@ void G1BarrierSetAssembler::g1_write_barrier_post_c2(MacroAssembler* masm, Register tmp2, bool new_val_may_be_null) { Label done; - generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, new_val_may_be_null); + bool use_aot_runtime_const = Compile::current()->is_aot_compile(); + generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, use_aot_runtime_const, new_val_may_be_null); __ bind(done); } @@ -491,7 +496,8 @@ void G1BarrierSetAssembler::g1_write_barrier_post_c1(MacroAssembler* masm, Register tmp1, Register tmp2) { Label done; - generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, true /* new_val_may_be_null */); + bool use_aot_runtime_const = ciEnv::current()->is_aot_compile(); + generate_post_barrier(masm, store_addr, new_val, thread, tmp1, tmp2, done, use_aot_runtime_const, true /* new_val_may_be_null */); masm->bind(done); } diff --git a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp index fa4f6fc9ea6..07318e6604f 100644 --- a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp @@ -906,7 +906,7 @@ void ShenandoahBarrierStubC2::lrb(MacroAssembler& masm) { __ mv(_tmp2, _obj); } - if (AOTCodeCache::is_on_for_dump()) { + if (Compile::current()->is_aot_compile()) { __ lwu(_tmp1, ExternalAddress(AOTRuntimeConstants::grain_shift_address())); __ srl(_tmp2, _tmp2, _tmp1); __ ld(_tmp1, ExternalAddress(AOTRuntimeConstants::cset_base_address())); diff --git a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp index 3e527aba68e..00be7f9767b 100644 --- a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp @@ -27,6 +27,7 @@ #include "asm/assembler.hpp" #include "asm/assembler.inline.hpp" #include "cds/archiveBuilder.hpp" +#include "ci/ciEnv.hpp" #include "ci/ciValueKlass.hpp" #include "code/aotCodeCache.hpp" #include "code/compiledIC.hpp" @@ -5689,7 +5690,7 @@ void MacroAssembler::load_byte_map_base(Register reg) { void MacroAssembler::load_aotrc_address(Register reg, address a) { #if INCLUDE_CDS assert(AOTRuntimeConstants::contains(a), "address out of range for data area"); - if (AOTCodeCache::is_on_for_dump()) { + if (ciEnv::current()->is_aot_compile()) { // all aotrc field addresses should be registered in the AOTCodeCache address table la(reg, ExternalAddress(a)); } else { diff --git a/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp b/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp index 78abd13ba97..3d6768a260e 100644 --- a/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp @@ -484,7 +484,7 @@ void LIR_Assembler::return_op(LIR_Opr result, C1SafepointPollStub* code_stub) { if (vk->can_be_returned_as_fields()) { address unpack_handler = vk->unpack_handler(); assert(unpack_handler != nullptr, "must be"); - if (AOTCodeCache::is_on_for_dump()) { + if (compilation()->env()->is_aot_compile()) { // in AOT compiled code call the unpack handler indirectly // via the klass. The handler's blob does not currently get // saved to the archive. So, a direct call to the handler @@ -596,7 +596,7 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: { assert(patch_code == lir_patch_none, "no patching handled here"); - if (AOTCodeCache::is_on_for_dump()) { + if (compilation()->env()->is_aot_compile()) { address b = c->as_pointer(); if (b == (address)ThreadIdentifier::unsafe_offset()) { __ lea(dest->as_register_lo(), ExternalAddress(b)); diff --git a/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp index 4eefd10b7fc..439f273ad2b 100644 --- a/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp @@ -280,6 +280,7 @@ static void generate_post_barrier(MacroAssembler* masm, const Register store_addr, const Register new_val, const Register tmp1, + bool use_aot_runtime_const, bool new_val_may_be_null) { assert_different_registers(store_addr, new_val, tmp1, noreg); @@ -291,7 +292,7 @@ static void generate_post_barrier(MacroAssembler* masm, // AOT code needs to load the barrier grain shift from the aot // runtime constants area in the code cache otherwise we can compile // it as an immediate operand - if (AOTCodeCache::is_on_for_dump()) { + if (INCLUDE_CDS && use_aot_runtime_const) { address grain_shift_addr = AOTRuntimeConstants::grain_shift_address(); Register save = pick_different_reg(rcx, tmp1, new_val, store_addr); __ push(save); @@ -336,7 +337,10 @@ void G1BarrierSetAssembler::g1_write_barrier_post(MacroAssembler* masm, Register store_addr, Register new_val, Register tmp) { - generate_post_barrier(masm, store_addr, new_val, tmp, true /* new_val_may_be_null */); + // This method is used only for interpreter, adapter and stub code generation. + // Use the AOT cache dump state to determine the usage of AOT runtime constants. + bool use_aot_runtime_const = AOTCodeCache::is_on_for_dump(); + generate_post_barrier(masm, store_addr, new_val, tmp, use_aot_runtime_const, true /* new_val_may_be_null */); } #if defined(COMPILER2) @@ -397,7 +401,8 @@ void G1BarrierSetAssembler::g1_write_barrier_post_c2(MacroAssembler* masm, Register new_val, Register tmp, bool new_val_may_be_null) { - generate_post_barrier(masm, store_addr, new_val, tmp, new_val_may_be_null); + bool use_aot_runtime_const = Compile::current()->is_aot_compile(); + generate_post_barrier(masm, store_addr, new_val, tmp, use_aot_runtime_const, new_val_may_be_null); } #endif // COMPILER2 @@ -487,7 +492,8 @@ void G1BarrierSetAssembler::g1_write_barrier_post_c1(MacroAssembler* masm, Register thread, Register tmp1, Register tmp2 /* unused on x86 */) { - generate_post_barrier(masm, store_addr, new_val, tmp1, true /* new_val_may_be_null */); + bool use_aot_runtime_const = ciEnv::current()->is_aot_compile(); + generate_post_barrier(masm, store_addr, new_val, tmp1, use_aot_runtime_const, true /* new_val_may_be_null */); } #define __ sasm-> diff --git a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp index 364a1316569..e94e5f87e98 100644 --- a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp @@ -1003,7 +1003,7 @@ void ShenandoahBarrierStubC2::lrb(MacroAssembler& masm) { patchable_jump_if_gc_state(masm, state_to_check, noreg, noreg, &L_slow); } - bool is_aot = AOTCodeCache::is_on_for_dump(); + const bool is_aot = Compile::current()->is_aot_compile(); // Need temp to work, allocate one now. bool tmp_live; diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.cpp b/src/hotspot/cpu/x86/macroAssembler_x86.cpp index 88793061928..f06dcba8b18 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp @@ -24,6 +24,7 @@ #include "asm/assembler.hpp" #include "asm/assembler.inline.hpp" +#include "ci/ciEnv.hpp" #include "ci/ciValueKlass.hpp" #include "code/aotCodeCache.hpp" #include "code/compiledIC.hpp" @@ -6027,6 +6028,7 @@ void MacroAssembler::reinit_heapbase() { int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_interpreter) { assert(ValueTypeReturnedAsFields, "Value types should never be returned as fields"); + assert(vk == nullptr || !from_interpreter, "Interpreter passes only nullptr for vk"); // A value type might be returned. If fields are in registers we // need to allocate a value type instance and initialize it with // the value of the fields. @@ -6086,7 +6088,7 @@ int MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk, bool from_i } // 3. Initialize its fields with a value class specific handler if (vk != nullptr) { - if (AOTCodeCache::is_on_for_dump()) { + if (ciEnv::current()->is_aot_compile()) { // in AOT compiled code call the pack handler indirectly via // the klass. The handler's blob does not currently get saved // to the archive. So, a direct call to the handler address @@ -10771,7 +10773,7 @@ void MacroAssembler::restore_legacy_gprs() { void MacroAssembler::load_aotrc_address(Register reg, address a) { #if INCLUDE_CDS assert(AOTRuntimeConstants::contains(a), "address out of range for data area"); - if (AOTCodeCache::is_on_for_dump()) { + if (ciEnv::current()->is_aot_compile()) { // all aotrc field addresses should be registered in the AOTCodeCache address table lea(reg, ExternalAddress(a)); } else { diff --git a/src/hotspot/cpu/x86/templateInterpreterGenerator_x86.cpp b/src/hotspot/cpu/x86/templateInterpreterGenerator_x86.cpp index 319e91288c1..f1a84cf32a1 100644 --- a/src/hotspot/cpu/x86/templateInterpreterGenerator_x86.cpp +++ b/src/hotspot/cpu/x86/templateInterpreterGenerator_x86.cpp @@ -183,7 +183,7 @@ address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD); if (state == atos && ValueTypeReturnedAsFields) { - __ store_value_type_fields_to_buf(nullptr); + __ store_value_type_fields_to_buf(nullptr, true /* from_interpreter */); } __ restore_bcp(); diff --git a/src/hotspot/share/asm/macroAssembler_common.hpp b/src/hotspot/share/asm/macroAssembler_common.hpp index 0bb3996d6c6..5cabf0750b2 100644 --- a/src/hotspot/share/asm/macroAssembler_common.hpp +++ b/src/hotspot/share/asm/macroAssembler_common.hpp @@ -49,7 +49,7 @@ bool shuffle_value_args_spill(bool is_packing, const GrowableArray* sig, int sig_index, VMRegPair* regs_from, int from_index, int regs_from_count, RegState* reg_state); - int store_value_type_fields_to_buf(ciValueKlass* vk, bool from_interpreter = true); + int store_value_type_fields_to_buf(ciValueKlass* vk, bool from_interpreter); bool move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[]); bool unpack_value_helper(const GrowableArray* sig, int& sig_index, VMReg from, int& from_index, VMRegPair* to, int to_count, int& to_index, diff --git a/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp b/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp index f07b5f0b81d..76ce0a59a22 100644 --- a/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp +++ b/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp @@ -190,7 +190,7 @@ void CardTableBarrierSetC1::post_barrier(LIRAccess& access, LIR_Opr addr, LIR_Op } LIR_Address* card_addr; - if (AOTCodeCache::is_on_for_dump()) { + if (gen->compilation()->env()->is_aot_compile()) { // load the card table address from the AOT Runtime Constants area LIR_Opr byte_map_base_adr = LIR_OprFact::intptrConst(AOTRuntimeConstants::card_table_base_address()); LIR_Opr byte_map_base_reg = gen->new_pointer_register(); diff --git a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp index 47760ed9e75..c7981ec58dc 100644 --- a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp +++ b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp @@ -145,7 +145,7 @@ Node* CardTableBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access Node* CardTableBarrierSetC2::byte_map_base_node(IdealKit* kit) const { // Get base of card map - if (AOTCodeCache::is_on_for_dump()) { + if (Compile::current()->is_aot_compile()) { // load the card table address from the AOT Runtime Constants area Node* byte_map_base_adr = kit->makecon(TypeRawPtr::make(AOTRuntimeConstants::card_table_base_address())); return kit->load_aot_const(byte_map_base_adr, TypeRawPtr::NOTNULL); diff --git a/src/hotspot/share/opto/compile.hpp b/src/hotspot/share/opto/compile.hpp index 8ec53f3d787..b6cee5f4e53 100644 --- a/src/hotspot/share/opto/compile.hpp +++ b/src/hotspot/share/opto/compile.hpp @@ -615,7 +615,7 @@ class Compile : public Phase { bool do_superword() const { return _options._do_superword; } bool do_stringopts() const { return _options._do_stringopts; } - bool is_aot_compile() const { return _options._aot_compile; } + bool is_aot_compile() const { return CDS_ONLY(_options._aot_compile) NOT_CDS(false); } bool do_clinit_barriers() const { return _options._for_aot_preload; } bool for_aot_preload() const { return _options._for_aot_preload; } diff --git a/src/hotspot/share/opto/memnode.cpp b/src/hotspot/share/opto/memnode.cpp index b459ada7589..60e2d213e12 100644 --- a/src/hotspot/share/opto/memnode.cpp +++ b/src/hotspot/share/opto/memnode.cpp @@ -29,7 +29,6 @@ #include "classfile/javaClasses.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmIntrinsics.hpp" -#include "code/aotCodeCache.hpp" #include "compiler/compileLog.hpp" #include "gc/shared/barrierSet.hpp" #include "gc/shared/c2/barrierSetC2.hpp" @@ -2266,7 +2265,7 @@ const Type* LoadNode::load_array_final_field(const TypeKlassPtr *tkls, ciKlass* klass) const { assert(!UseCompactObjectHeaders || - AOTCodeCache::is_on_for_dump() || + Compile::current()->is_aot_compile() || tkls->offset() != in_bytes(Klass::prototype_header_offset()), "must not happen"); @@ -2491,7 +2490,7 @@ const Type* LoadNode::Value(PhaseGVN* phase) const { } // Class encoding and some class's values may change between runs. // Force loading them when AOT code is generated. - if (!AOTCodeCache::is_on_for_dump()) { + if (!C->is_aot_compile()) { if (UseCompactObjectHeaders && tkls->offset() == in_bytes(Klass::prototype_header_offset())) { // The field is Klass::_prototype_header. Return its (constant) value. assert(this->Opcode() == Op_LoadX, "must load a proper type from _prototype_header"); From 3ee1e3c18982dcf7ea3d022f092403a2cc086085 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Mon, 23 Nov 2026 21:20:43 +0000 Subject: [PATCH 52/95] 8397766: jdk/jfr/api/consumer/streaming/TestLatestEvent.java fails with Recording file is stuck in locked stream state Reviewed-by: mgronlun --- .../classes/jdk/jfr/internal/MetadataRepository.java | 10 ++++++++-- .../classes/jdk/jfr/internal/PlatformRecorder.java | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataRepository.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataRepository.java index 4047bb6c898..5b94b6b6f72 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataRepository.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataRepository.java @@ -297,6 +297,12 @@ synchronized void setStaleMetadata() { staleMetadata = true; } + synchronized Instant updateChunkStartTime(long nanos) { + Instant instant = Utils.epochNanosToInstant(nanos); + lastMillis = instant.toEpochMilli(); + return instant; + } + // Lock around setOutput ensures that other threads don't // emit events after setOutput and unregister the event class, before a call // to storeDescriptorInJVM @@ -310,7 +316,7 @@ synchronized Instant setOutput(String filename) { // is what RecordingInfo:getStopTime() returns. awaitEpochMilliShift(); JVM.setOutput(filename); - long chunkStart = JVMSupport.getChunkStartNanos(); + Instant timestamp = updateChunkStartTime(JVMSupport.getChunkStartNanos()); if (filename != null) { RepositoryFiles.notifyNewFile(); } @@ -321,7 +327,7 @@ synchronized Instant setOutput(String filename) { } unregistered = false; } - return Utils.epochNanosToInstant(chunkStart); + return timestamp; } private void awaitEpochMilliShift() { diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java index f48a3836e73..d2a098ce7a8 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java @@ -265,7 +265,7 @@ synchronized long start(PlatformRecording recording) { currentChunk = newChunk; JVM.beginRecording(); startNanos = JVMSupport.getChunkStartNanos(); - startTime = Utils.epochNanosToInstant(startNanos); + startTime = MetadataRepository.getInstance().updateChunkStartTime(startNanos); if (currentChunk != null) { currentChunk.setStartTime(startTime); } From 4b209cf835da07a1ead0894c9cf91f9b7595c5b8 Mon Sep 17 00:00:00 2001 From: Ashutosh Mehra Date: Tue, 24 Nov 2026 03:23:46 +0000 Subject: [PATCH 53/95] 8397857: Improve code for handling of ArchiveRelocationMode Reviewed-by: kvn, iklam --- src/hotspot/share/cds/aotMetaspace.cpp | 46 +++++++++---------- src/hotspot/share/cds/aotMetaspace.hpp | 8 ++++ .../jtreg/runtime/cds/SharedBaseAddress.java | 8 +++- .../cds/appcds/ArchiveRelocationTest.java | 35 ++++++++++++-- .../cds/appcds/StressArchiveUnmapping.java | 9 ++++ .../DynamicArchiveRelocationTest.java | 2 +- 6 files changed, 75 insertions(+), 33 deletions(-) diff --git a/src/hotspot/share/cds/aotMetaspace.cpp b/src/hotspot/share/cds/aotMetaspace.cpp index d8a895555b0..b61ea69f275 100644 --- a/src/hotspot/share/cds/aotMetaspace.cpp +++ b/src/hotspot/share/cds/aotMetaspace.cpp @@ -1575,13 +1575,24 @@ void AOTMetaspace::initialize_runtime_shared_and_meta_spaces() { aot_log_info(aot)("ArchiveRelocationMode: %d", ArchiveRelocationMode); - // First try to map at the requested address - result = map_archives(static_mapinfo, dynamic_mapinfo, true); - if (result == MAP_ARCHIVE_MMAP_FAILURE) { - // Mapping has failed (probably due to ASLR). Let's map at an address chosen - // by the OS. - aot_log_info(aot)("Try to map archive(s) at an alternative address"); + if (ArchiveRelocationMode == REQUESTED_ADDR_FALLBACK_OS_ADDR) { + bool use_requested_addr = static_mapinfo->requested_base_address() != nullptr; + result = map_archives(static_mapinfo, dynamic_mapinfo, use_requested_addr); + if ((result == MAP_ARCHIVE_MMAP_FAILURE) && use_requested_addr) { + // Mapping has failed (probably due to ASLR). Let's map at an address chosen + // by the OS. + result = map_archives(static_mapinfo, dynamic_mapinfo, false); + } + } else if (ArchiveRelocationMode == OS_ADDR_ONLY) { + aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); result = map_archives(static_mapinfo, dynamic_mapinfo, false); + } else if (ArchiveRelocationMode == REQUESTED_ADDR_ONLY) { + if (static_mapinfo->requested_base_address() != nullptr) { + aot_log_info(aot)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); + result = map_archives(static_mapinfo, dynamic_mapinfo, true); + } else { + report_loading_error("Cannot use ArchiveRelocationMode=2 when the archive was created with -XX:SharedBaseAddress=0"); + } } } @@ -1717,25 +1728,9 @@ FileMapInfo* AOTMetaspace::open_dynamic_archive() { // false = map at an alternative address picked by OS. MapArchiveResult AOTMetaspace::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo, bool use_requested_addr) { - if (use_requested_addr && static_mapinfo->requested_base_address() == nullptr) { - aot_log_info(aot)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address."); - return MAP_ARCHIVE_MMAP_FAILURE; + if (!use_requested_addr) { + aot_log_info(aot)("Try to map archive(s) at an alternative address"); } - - if (ArchiveRelocationMode == 1 && use_requested_addr) { - if (AOTStressArchiveUnmapping) { - aot_log_info(aot)("Map at requested address to stress test unmapping"); - } else { - aot_log_info(aot)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address"); - return MAP_ARCHIVE_MMAP_FAILURE; - } - } - - if (ArchiveRelocationMode == 2 && !use_requested_addr) { - aot_log_info(aot)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address"); - return MAP_ARCHIVE_MMAP_FAILURE; - }; - if (dynamic_mapinfo != nullptr) { // Ensure that the OS won't be able to allocate new memory spaces between the two // archives, or else it would mess up the simple comparison in MetaspaceObj::in_aot_cache(). @@ -1842,7 +1837,8 @@ MapArchiveResult AOTMetaspace::map_archives(FileMapInfo* static_mapinfo, FileMap MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ? map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE; - if (ArchiveRelocationMode == 1 && use_requested_addr && AOTStressArchiveUnmapping) { + if ((ArchiveRelocationMode == REQUESTED_ADDR_FALLBACK_OS_ADDR) && + use_requested_addr && AOTStressArchiveUnmapping) { // This is for simulating mmap failures at the requested address. We do it here // (after all archives have possibly been mapped), so we can thoroughly test the // code for failure handling (releasing all allocated resource, etc). diff --git a/src/hotspot/share/cds/aotMetaspace.hpp b/src/hotspot/share/cds/aotMetaspace.hpp index a0110a65e1b..d752e98c620 100644 --- a/src/hotspot/share/cds/aotMetaspace.hpp +++ b/src/hotspot/share/cds/aotMetaspace.hpp @@ -43,6 +43,14 @@ class StaticArchiveBuilder; template class Array; +// These enum values correspond to the possible values of ArchiveRelocationMode option. +// Do not change them, or else it will break functionality of ArchiveRelocationMode option. +enum ArchiveRelocationModeValue { + REQUESTED_ADDR_FALLBACK_OS_ADDR = 0, + OS_ADDR_ONLY = 1, + REQUESTED_ADDR_ONLY = 2 +}; + enum MapArchiveResult { MAP_ARCHIVE_SUCCESS, MAP_ARCHIVE_MMAP_FAILURE, diff --git a/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java b/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java index 49265680ef2..203f4a92d14 100644 --- a/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java +++ b/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java @@ -129,8 +129,13 @@ public static void test(String[] args, String[] testTable) throws Exception { String testEntry = testTable[i]; String filename = "SharedBaseAddress-base" + testEntry + ".jsa"; System.out.println("sharedBaseAddress = " + testEntry); + // Default value of ArchiveRelocationMode is 1 which implies always map the archive at OS provided address. + // SharedBaseAddress is ignored this scenario. Therefore, explicitly set ArchiveRelocationMode=0 which + // makes first attempt to map at the requested address, failing which it falls back to OS provided address. CDSOptions opts = (new CDSOptions()) .setArchiveName(filename) + .addPrefix("-XX:+UnlockDiagnosticVMOptions") + .addPrefix("-XX:ArchiveRelocationMode=0") .addPrefix("-XX:SharedBaseAddress=" + testEntry) .addPrefix("-Xlog:cds=debug") .addPrefix("-Xlog:cds+reloc=debug") @@ -152,8 +157,7 @@ public static void test(String[] args, String[] testTable) throws Exception { CDSTestUtils.createArchiveAndCheck(opts); OutputAnalyzer out = CDSTestUtils.runWithArchiveAndCheck(opts); if (testEntry.equals("0")) { - out.shouldContain("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.") - .shouldContain("Try to map archive(s) at an alternative address") + out.shouldContain("Try to map archive(s) at an alternative address") .shouldNotMatch(failedPattern); } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/ArchiveRelocationTest.java b/test/hotspot/jtreg/runtime/cds/appcds/ArchiveRelocationTest.java index baa519a42ae..99b360b305c 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/ArchiveRelocationTest.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/ArchiveRelocationTest.java @@ -43,6 +43,7 @@ public static void main(String... args) throws Exception { try { test(false); test(true); + testRelocMode2(); } catch (SkippedException s) { s.printStackTrace(); throw new RuntimeException("Archive mapping should always succeed after JDK-8231610 (did the machine run out of memory?)"); @@ -67,8 +68,7 @@ static void test(boolean run_reloc) throws Exception { String logArg = "-Xlog:cds=debug,cds+reloc=debug,aot+heap"; String unlockArg = "-XX:+UnlockDiagnosticVMOptions"; String nmtArg = "-XX:NativeMemoryTracking=detail"; - String relocMsg1 = "ArchiveRelocationMode == 1: always map archive(s) at an alternative address"; - String relocMsg2 = "Try to map archive(s) at an alternative address"; + String relocMsg = "ArchiveRelocationMode == 1: always map archive(s) at an alternative address"; OutputAnalyzer out = TestCommon.dump(appJar, TestCommon.list(mainClass), @@ -78,13 +78,38 @@ static void test(boolean run_reloc) throws Exception { TestCommon.run("-cp", appJar, unlockArg, runRelocArg, logArg, mainClass) .assertNormalExit(output -> { if (run_reloc) { - if (!output.contains(relocMsg1) && !output.contains(relocMsg2)) { - throw new RuntimeException("Relocation messages \"" + relocMsg1 + - "\" and \"" + relocMsg2 + "\" are missing from the output"); + if (!output.contains(relocMsg)) { + throw new RuntimeException("Relocation messages \"" + relocMsg + "\" is missing from the output"); } } else { output.shouldContain("ArchiveRelocationMode: 0"); } }); } + + // Create archive with SharedBaseAddress=0 to indicate JVM should map the archive at OS provided address during production run. + // Do production run with ArchiveRelocationMode=2 which forces JVM to always use the requested address. + // This combination should cause JVM to exit with error message. + static void testRelocMode2() throws Exception { + System.out.println("============================================================"); + System.out.println("testRelocMode2 with SharedBaseAddress=0"); + System.out.println("============================================================"); + String appJar = ClassFileInstaller.getJarPath("hello.jar"); + String mainClass = "Hello"; + String runRelocArg = "-XX:ArchiveRelocationMode=2"; + String logArg = "-Xlog:cds=debug,cds+reloc=debug,aot+heap"; + // SharedBaseAddress=0 forces JVM to map archive at OS selected address + String sharedBaseArg = "-XX:SharedBaseAddress=0"; + String unlockArg = "-XX:+UnlockDiagnosticVMOptions"; + String relocMsg = "Cannot use ArchiveRelocationMode=2 when the archive was created with -XX:SharedBaseAddress=0"; + + OutputAnalyzer out = TestCommon.dump(appJar, + TestCommon.list(mainClass), + unlockArg, sharedBaseArg, logArg); + out.shouldContain("Relocating archive from"); + TestCommon.run("-cp", appJar, unlockArg, runRelocArg, logArg, mainClass) + .assertAbnormalExit(output -> { + output.shouldContain(relocMsg); + }); + } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java b/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java index f3654b6dc24..827b6486f6e 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java @@ -43,9 +43,18 @@ public static void main(String... args) throws Exception { SimpleCDSAppTester.of("StressArchiveUnmapping") .classpath("app.jar") .addVmArgs("-XX:+UnlockDiagnosticVMOptions", + "-XX:ArchiveRelocationMode=0", "-XX:+AOTStressArchiveUnmapping", "-Xlog:aot,class+path") .appCommandLine("StressArchiveUnmappingApp") + .setAssemblyChecker((OutputAnalyzer out) -> { + out.shouldContain("Simulate mapping failure to stress test unmapping") + .shouldContain("Try to map archive(s) at an alternative address"); + }) + .setProductionChecker((OutputAnalyzer out) -> { + out.shouldContain("Simulate mapping failure to stress test unmapping") + .shouldContain("Try to map archive(s) at an alternative address"); + }) .runAOTWorkflow(); } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveRelocationTest.java b/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveRelocationTest.java index 6d257be13b1..6a95053d2c3 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveRelocationTest.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveRelocationTest.java @@ -91,7 +91,7 @@ static void doTest() throws Exception { String baseArchiveName = getNewArchiveName("base"); String topArchiveName = getNewArchiveName("top"); - String runtimeMsg = "Try to map archive(s) at an alternative address"; + String runtimeMsg = "ArchiveRelocationMode == 1: always map archive(s) at an alternative address"; String unlockArg = "-XX:+UnlockDiagnosticVMOptions"; String relocationModeMsg = "ArchiveRelocationMode: 0"; From 0062a42a9f3a29db1f88657c1cb5828abd477bd5 Mon Sep 17 00:00:00 2001 From: Yadong Wang Date: Tue, 24 Nov 2026 03:39:12 +0000 Subject: [PATCH 54/95] 8394923: RISC-V: Use slli+bgez for the ZGC load barrier Reviewed-by: dzhang, fyang --- .../cpu/riscv/gc/z/zAddress_riscv.inline.hpp | 4 +-- .../riscv/gc/z/zBarrierSetAssembler_riscv.cpp | 28 +++++++++++++++---- src/hotspot/cpu/riscv/gc/z/z_riscv.ad | 19 ++++++++++--- .../cpu/riscv/macroAssembler_riscv.hpp | 9 +++++- src/hotspot/share/gc/z/c1/zBarrierSetC1.cpp | 2 +- src/hotspot/share/gc/z/zAddress.hpp | 6 ++-- src/hotspot/share/gc/z/zAddress.inline.hpp | 2 +- 7 files changed, 52 insertions(+), 18 deletions(-) diff --git a/src/hotspot/cpu/riscv/gc/z/zAddress_riscv.inline.hpp b/src/hotspot/cpu/riscv/gc/z/zAddress_riscv.inline.hpp index 8992eadeb46..568c47bc450 100644 --- a/src/hotspot/cpu/riscv/gc/z/zAddress_riscv.inline.hpp +++ b/src/hotspot/cpu/riscv/gc/z/zAddress_riscv.inline.hpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2023, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2023, 2026, Huawei Technologies Co., Ltd. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,7 @@ #include "utilities/globalDefinitions.hpp" inline uintptr_t ZPointer::remap_bits(uintptr_t colored) { - return colored & ZPointerRemappedMask; + return (colored ^ ZPointerRemappedMask) & ZPointerRemappedMask; } inline constexpr int ZPointer::load_shift_lookup(uintptr_t value) { diff --git a/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp index db96f003416..4ace52d53d8 100644 --- a/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/z/zBarrierSetAssembler_riscv.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2020, 2023, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, 2026, Huawei Technologies Co., Ltd. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,7 @@ #include "runtime/sharedRuntime.hpp" #include "utilities/debug.hpp" #include "utilities/macros.hpp" +#include "utilities/powerOfTwo.hpp" #ifdef COMPILER1 #include "c1/c1_LIRAssembler.hpp" #include "c1/c1_MacroAssembler.hpp" @@ -650,10 +651,15 @@ void ZBarrierSetAssembler::patch_barrier_relocation(address addr, int format) { int bytes; switch (format) { case ZBarrierRelocationFormatLoadBadMask: + assert(MacroAssembler::is_slli_at(addr), "invalid zgc barrier"); + // Shift the load-bad bit into the sign bit for bgez. + Assembler::patch(addr, 25, 20, 63 - exact_log2(value)); + bytes = MacroAssembler::instruction_size; + break; case ZBarrierRelocationFormatMarkBadMask: case ZBarrierRelocationFormatStoreGoodBits: case ZBarrierRelocationFormatStoreBadMask: - assert(MacroAssembler::is_li16u_at(addr), "invalide zgc barrier"); + assert(MacroAssembler::is_li16u_at(addr), "invalid zgc barrier"); bytes = MacroAssembler::pd_patch_instruction_size(addr, (address)(uintptr_t)value); break; default: @@ -817,15 +823,26 @@ static void z_uncolor(LIR_Assembler* ce, LIR_Opr ref) { __ srli(ref->as_register(), ref->as_register(), ZPointerLoadShift); } -static void check_color(LIR_Assembler* ce, LIR_Opr ref, bool on_non_strong) { +static void check_color(LIR_Assembler* ce, LIR_Opr ref, bool on_non_strong, Label& good) { assert_different_registers(t0, xthread, ref->as_register()); int format = on_non_strong ? ZBarrierRelocationFormatMarkBadMask : ZBarrierRelocationFormatLoadBadMask; - Label good; + if (!on_non_strong) { + // The load bad mask is a single bit; shift it into the sign bit so the good check is a plain + // bgez. The GC patches the shamt field when the remapped bit changes. The raw _slli form must + // be used: for the zero unpatched shamt the slli wrapper emits a register move, leaving no + // shamt field for the patcher. + __ relocate(barrier_Relocation::spec(), [&] { + __ _slli(t0, ref->as_register(), barrier_Relocation::unpatched); + }, format); + __ bgez(t0, good); + return; + } __ relocate(barrier_Relocation::spec(), [&] { __ li16u(t0, barrier_Relocation::unpatched); }, format); __ andr(t0, ref->as_register(), t0); + __ beqz(t0, good); } void ZBarrierSetAssembler::generate_c1_color(LIR_Assembler* ce, LIR_Opr ref) const { @@ -841,8 +858,7 @@ void ZBarrierSetAssembler::generate_c1_load_barrier(LIR_Assembler* ce, ZLoadBarrierStubC1* stub, bool on_non_strong) const { Label good; - check_color(ce, ref, on_non_strong); - __ beqz(t0, good); + check_color(ce, ref, on_non_strong, good); __ j(*stub->entry()); __ bind(good); diff --git a/src/hotspot/cpu/riscv/gc/z/z_riscv.ad b/src/hotspot/cpu/riscv/gc/z/z_riscv.ad index e9cbb8a7cc3..7f311ae179a 100644 --- a/src/hotspot/cpu/riscv/gc/z/z_riscv.ad +++ b/src/hotspot/cpu/riscv/gc/z/z_riscv.ad @@ -1,6 +1,6 @@ // // Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. -// Copyright (c) 2020, 2023, Huawei Technologies Co., Ltd. All rights reserved. +// Copyright (c) 2020, 2026, Huawei Technologies Co., Ltd. All rights reserved. // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. // // This code is free software; you can redistribute it and/or modify it @@ -47,13 +47,25 @@ static void z_uncolor(MacroAssembler* masm, Register ref) { __ srli(ref, ref, ZPointerLoadShift); } -static void check_color(MacroAssembler* masm, Register ref, bool on_non_strong, Register result) { +static void check_color(MacroAssembler* masm, Register ref, bool on_non_strong, Register result, Label& good) { int format = on_non_strong ? ZBarrierRelocationFormatMarkBadMask : ZBarrierRelocationFormatLoadBadMask; + if (!on_non_strong) { + // The load bad mask is a single bit; shift it into the sign bit so the good check is a plain + // bgez. The GC patches the shamt field when the remapped bit changes. The raw _slli form must + // be used: for the zero unpatched shamt the slli wrapper emits a register move, leaving no + // shamt field for the patcher. + __ relocate(barrier_Relocation::spec(), [&] { + __ _slli(result, ref, barrier_Relocation::unpatched); + }, format); + __ bgez(result, good); + return; + } __ relocate(barrier_Relocation::spec(), [&] { __ li16u(result, barrier_Relocation::unpatched); }, format); __ andr(result, ref, result); + __ beqz(result, good); } static void z_load_barrier(MacroAssembler* masm, const MachNode* node, Address ref_addr, Register ref, Register tmp) { @@ -69,8 +81,7 @@ static void z_load_barrier(MacroAssembler* masm, const MachNode* node, Address r ZLoadBarrierStubC2* const stub = ZLoadBarrierStubC2::create(node, ref_addr, ref); Label good; - check_color(masm, ref, on_non_strong, tmp); - __ beqz(tmp, good); + check_color(masm, ref, on_non_strong, tmp, good); __ j(*stub->entry()); __ bind(good); diff --git a/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp b/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp index 78ca6f21664..d346a5c17dc 100644 --- a/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp +++ b/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp @@ -1,7 +1,7 @@ /* * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, 2020, Red Hat Inc. All rights reserved. - * Copyright (c) 2020, 2024, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020, 2026, Huawei Technologies Co., Ltd. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1813,6 +1813,13 @@ INSN(sd_release, sd, sd_rl); Assembler::extract(Assembler::ld_instr(instr), 31, 26) == 0b000000; } + static bool is_slli_at(address instr) { + assert_cond(instr != nullptr); + return extract_opcode(instr) == 0b0010011 && + extract_funct3(instr) == 0b001 && + Assembler::extract(Assembler::ld_instr(instr), 31, 26) == 0b000000; + } + static bool is_slli_shift_at(address instr, uint32_t shift) { assert_cond(instr != nullptr); return (extract_opcode(instr) == 0b0010011 && // opcode field diff --git a/src/hotspot/share/gc/z/c1/zBarrierSetC1.cpp b/src/hotspot/share/gc/z/c1/zBarrierSetC1.cpp index 8d5d8662ebc..8de36b35f8c 100644 --- a/src/hotspot/share/gc/z/c1/zBarrierSetC1.cpp +++ b/src/hotspot/share/gc/z/c1/zBarrierSetC1.cpp @@ -453,7 +453,7 @@ LIR_Opr ZBarrierSetC1::atomic_cmpxchg_at_resolved(LIRAccess& access, LIRItem& cm __ cas_obj(access.resolved_addr()->as_address_ptr()->base(), cmp_value_opr, new_value_zpointer, -#ifdef RISCV +#ifdef RISCV64 access.gen()->new_register(T_OBJECT), access.gen()->new_register(T_OBJECT), access.gen()->new_register(T_OBJECT)); diff --git a/src/hotspot/share/gc/z/zAddress.hpp b/src/hotspot/share/gc/z/zAddress.hpp index ca904f69277..206df404238 100644 --- a/src/hotspot/share/gc/z/zAddress.hpp +++ b/src/hotspot/share/gc/z/zAddress.hpp @@ -101,9 +101,9 @@ extern uint32_t ZBackingIndexMax; // minus the shift of the load metadata bit start encodes the numbers 0, 1, 2 and 3. // These numbers in binary correspond to 00, 01, 10 and 11. The low order bit in said // numbers correspond to the simulated RemappedYoung[0, 1] value, and the high order bit -// corresponds to the simulated RemappedOld[0, 1] value. On AArch64, the remap bits -// of zpointers are the complement of this bit. So there are 3 good bits and one bad bit -// instead. This lends itself better to AArch64 instructions. +// corresponds to the simulated RemappedOld[0, 1] value. On AArch64 and RISCV64, the remap +// bits of zpointers are the complement of this bit. So there are 3 good bits and one bad +// bit instead. This lends itself better to their instructions (tbz/tbnz and slli/bgez). // // We decide the bit to be taken by having the RemappedYoungMask and RemappedOldMask // variables, which alternate between what two bits they accept for their corresponding diff --git a/src/hotspot/share/gc/z/zAddress.inline.hpp b/src/hotspot/share/gc/z/zAddress.inline.hpp index 0b99802729b..8a0259aca47 100644 --- a/src/hotspot/share/gc/z/zAddress.inline.hpp +++ b/src/hotspot/share/gc/z/zAddress.inline.hpp @@ -330,7 +330,7 @@ inline bool is_valid(zpointer ptr, bool assert_on_failure = false) { } if ((value & ~ZPointerStoreMetadataMask) != 0) { -#ifndef AARCH64 +#if !defined(AARCH64) && !defined(RISCV64) const int index = ZPointer::load_shift_lookup_index(value); if (index != 0 && !is_power_of_2(index)) { report_is_valid_failure("Invalid remap bits"); From 17e3b72b0218468c99bd0a1ec7d87b53efcec776 Mon Sep 17 00:00:00 2001 From: Albert Mingkun Yang Date: Tue, 24 Nov 2026 05:40:02 +0000 Subject: [PATCH 55/95] 8397994: RISC-V: Remove redundant long-to-int conversion in masked widening Reviewed-by: fyang, gcao --- src/hotspot/cpu/riscv/riscv.ad | 27 +++++++++++++ src/hotspot/cpu/riscv/riscv_b.ad | 2 +- .../c2/riscv64/TestMaskedWidening.java | 38 ++++++++++++++++++- 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/src/hotspot/cpu/riscv/riscv.ad b/src/hotspot/cpu/riscv/riscv.ad index b2678333992..4d595d7b1bd 100644 --- a/src/hotspot/cpu/riscv/riscv.ad +++ b/src/hotspot/cpu/riscv/riscv.ad @@ -2864,6 +2864,16 @@ operand immI_simm12() interface(CONST_INTER); %} +// 12 bit signed value that is non-negative, i.e. 0 <= value <= 2047. +operand immI_simm12_nonneg() +%{ + predicate(Assembler::is_simm12((int64_t)n->get_int()) && n->get_int() >= 0); + match(ConI); + op_cost(0); + format %{ %} + interface(CONST_INTER); +%} + // 5 bit signed value. operand immI_simm5() %{ @@ -9028,6 +9038,23 @@ instruct convI2L_andI_reg_imm(iRegLNoSp dst, iRegI src, immI_simm12 mask) %{ ins_pipe(ialu_reg_imm); %} +// With a non-negative mask the 64-bit AND drops the high half itself, so the L2I +// is redundant. +instruct convI2L_andI_l2i_reg_imm(iRegLNoSp dst, iRegL src, immI_simm12_nonneg mask) %{ + match(Set dst (ConvI2L (AndI (ConvL2I src) mask))); + + ins_cost(ALU_COST); + format %{ "andi $dst, $src, $mask\t#@convI2L_andI_l2i_reg_imm" %} + + ins_encode %{ + __ andi(as_Register($dst$$reg), + as_Register($src$$reg), + (int32_t)($mask$$constant)); + %} + + ins_pipe(ialu_reg_imm); +%} + // Fused int-producer + ConvI2L rules. instruct convI2L_addI_reg_reg(iRegLNoSp dst, iRegIorL2I src1, iRegIorL2I src2) %{ match(Set dst (ConvI2L (AddI src1 src2))); diff --git a/src/hotspot/cpu/riscv/riscv_b.ad b/src/hotspot/cpu/riscv/riscv_b.ad index f0e07e67fd6..d90514b692f 100644 --- a/src/hotspot/cpu/riscv/riscv_b.ad +++ b/src/hotspot/cpu/riscv/riscv_b.ad @@ -171,7 +171,7 @@ instruct convS2UI_reg_reg_b(iRegINoSp dst, iRegIorL2I src, immI_16bits mask) %{ ins_pipe(ialu_reg); %} -instruct convI2L_andI_16bits_b(iRegLNoSp dst, iRegI src, immI_16bits mask) %{ +instruct convI2L_andI_16bits_b(iRegLNoSp dst, iRegIorL2I src, immI_16bits mask) %{ predicate(UseZbb); match(Set dst (ConvI2L (AndI src mask))); diff --git a/test/hotspot/jtreg/compiler/c2/riscv64/TestMaskedWidening.java b/test/hotspot/jtreg/compiler/c2/riscv64/TestMaskedWidening.java index d3424f7f384..0d621c5efd8 100644 --- a/test/hotspot/jtreg/compiler/c2/riscv64/TestMaskedWidening.java +++ b/test/hotspot/jtreg/compiler/c2/riscv64/TestMaskedWidening.java @@ -52,12 +52,18 @@ public class TestMaskedWidening { private static final String I2L = "convI2L_reg_reg"; private static final String I2L_ANDI = "convI2L_andI_reg_imm"; private static final String I2L_ZEXT_H = "convI2L_andI_16bits_b"; + private static final String I2L_L2I_ANDI = "convI2L_andI_l2i_reg_imm"; private static final int[] VALUES = { 0, 1, -1, Integer.MIN_VALUE, Integer.MAX_VALUE, 0x40000000, 0x80000001, 0x55555555, 0xaaaaaaaa }; + private static final long[] LONG_VALUES = { + 0L, 1L, -1L, Long.MIN_VALUE, Long.MAX_VALUE, + 0x1234_5678_9abc_def0L, 0xffff_ffff_8000_0000L + }; + public static void main(String[] args) { TestFramework.runWithFlags(args); } @@ -87,11 +93,34 @@ static long maskShort(int value) { return (long) (value & 0xffff); } - @Run(test = {"maskImmediate", "maskNegativeImmediate", "maskOutOfRangeImmediate", "maskShort"}) + @Test + @IR(counts = {I2L_L2I_ANDI, "1"}, failOn = {I2L}, phase = CompilePhase.FINAL_CODE) + static long maskImmediateFromLong(long value) { + return (int) value & 0x7ff; + } + + @Test + @IR(counts = {I2L_L2I_ANDI, "0"}, phase = CompilePhase.FINAL_CODE) + static long maskNegativeImmediateFromLong(long value) { + return (int) value & -2048; + } + + @Test + @IR(counts = {I2L_ZEXT_H, "1"}, failOn = {I2L}, + applyIf = {"UseZbb", "true"}, phase = CompilePhase.FINAL_CODE) + static long maskShortFromLong(long value) { + return (int) value & 0xffff; + } + + @Run(test = {"maskImmediate", "maskNegativeImmediate", "maskOutOfRangeImmediate", "maskShort", + "maskImmediateFromLong", "maskNegativeImmediateFromLong", "maskShortFromLong"}) static void runTests() { for (int value : VALUES) { verify(value); } + for (long value : LONG_VALUES) { + verifyFromLong(value); + } } @DontCompile @@ -101,4 +130,11 @@ static void verify(int value) { Asserts.assertEQ(maskOutOfRangeImmediate(value), (long) (value & 0xfff)); Asserts.assertEQ(maskShort(value), (long) (value & 0xffff)); } + + @DontCompile + static void verifyFromLong(long value) { + Asserts.assertEQ(maskImmediateFromLong(value), (long) ((int) value & 0x7ff)); + Asserts.assertEQ(maskNegativeImmediateFromLong(value), (long) ((int) value & -2048)); + Asserts.assertEQ(maskShortFromLong(value), (long) ((int) value & 0xffff)); + } } From 3502872803693c3b00a076b04517c4a10cf5703e Mon Sep 17 00:00:00 2001 From: TongChen PAN <2402365479@qq.com> Date: Tue, 24 Nov 2026 06:07:35 +0000 Subject: [PATCH 56/95] 8397023: RISC-V: Use sh1add in RVV String.indexOf(char) Reviewed-by: fyang, dzhang --- src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp index 178221ec7dd..40fa846743f 100644 --- a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp @@ -3155,6 +3155,7 @@ void C2_MacroAssembler::string_indexof_char_v(Register str1, Register cnt1, Register ch, Register result, Register tmp1, Register tmp2, bool isL) { + assert_different_registers(str1, cnt1, ch, result, tmp1, tmp2); mv(result, zr); Label loop, MATCH, DONE; @@ -3168,8 +3169,7 @@ void C2_MacroAssembler::string_indexof_char_v(Register str1, Register cnt1, add(result, result, tmp1); sub(cnt1, cnt1, tmp1); - if (!isL) slli(tmp1, tmp1, 1); - add(str1, str1, tmp1); + shift_left_add(str1, tmp1, str1, isL ? 0 : 1, tmp1); bnez(cnt1, loop); mv(result, -1); From 2bcc2a944dce4f09ef1ffb694fe4e78e36bd372b Mon Sep 17 00:00:00 2001 From: Azad Abdulov Date: Tue, 24 Nov 2026 10:42:09 +0000 Subject: [PATCH 57/95] 8396893: Slow allocation in sun.font.HBShaper.shape Reviewed-by: avu, prr --- .../classes/sun/font/SunLayoutEngine.java | 28 ++++- .../font/TextLayout/ShapingContextTest.java | 103 ++++++++++++++++++ .../bench/java/awt/font/TextLayoutBench.java | 84 ++++++++++++++ 3 files changed, 210 insertions(+), 5 deletions(-) create mode 100644 test/jdk/java/awt/font/TextLayout/ShapingContextTest.java create mode 100644 test/micro/org/openjdk/bench/java/awt/font/TextLayoutBench.java diff --git a/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java b/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java index d6937c667ef..eb63c175121 100644 --- a/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java +++ b/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java @@ -37,7 +37,7 @@ import java.awt.geom.Point2D; import java.lang.foreign.MemorySegment; -import java.util.concurrent.ConcurrentHashMap; +import java.util.Arrays; import java.util.WeakHashMap; public final class SunLayoutEngine { @@ -66,25 +66,43 @@ private static long getFacePtr(Font2D font2D) { useFFM = "true".equals(prop); } + // HarfBuzz keeps up to 5 code points (at most 10 UTF-16 chars) of context on each side. + // See hb_buffer_t::CONTEXT_LENGTH in hb-buffer.hh + // We use bigger margin to be on the safe side in case of a future change in HarfBuzz. + private static final int HB_CONTEXT_LENGTH = 1024; + public static void layout(Font2D font, int script, FontStrikeDesc desc, float[] mat, int gmask, int baseIndex, TextRecord tr, int typo_flags, Point2D.Float pt, GVData data) { FontStrike strike = font.getStrike(desc); + + char[] text = tr.text; + int start = tr.start; + int limit = tr.limit; + + int contextStart = Math.max(0, start - HB_CONTEXT_LENGTH); + int contextLimit = Math.min(text.length, limit + HB_CONTEXT_LENGTH); + if (0 < contextStart || contextLimit < text.length) { + text = Arrays.copyOfRange(text, contextStart, contextLimit); + start -= contextStart; + limit -= contextStart; + } + if (useFFM) { MemorySegment face = HBShaper.getFace(font); if (face != null) { HBShaper.shape(font, strike, mat, face, - tr.text, data, script, - tr.start, tr.limit, baseIndex, pt, + text, data, script, + start, limit, baseIndex, pt, typo_flags, gmask); } } else { long pFace = getFacePtr(font); if (pFace != 0) { shape(font, strike, mat, pFace, - tr.text, data, script, - tr.start, tr.limit, baseIndex, pt, + text, data, script, + start, limit, baseIndex, pt, typo_flags, gmask); } } diff --git a/test/jdk/java/awt/font/TextLayout/ShapingContextTest.java b/test/jdk/java/awt/font/TextLayout/ShapingContextTest.java new file mode 100644 index 00000000000..45beb6109cf --- /dev/null +++ b/test/jdk/java/awt/font/TextLayout/ShapingContextTest.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026, JetBrains s.r.o.. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8396893 + * @summary Checks that a shortened text is shaped the same way as a full text + * @run junit/othervm -Dsun.font.layout.ffm=true ${test.main.class} + * @run junit/othervm -Dsun.font.layout.ffm=false ${test.main.class} + */ + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.awt.Font; +import java.awt.GraphicsEnvironment; +import java.awt.font.FontRenderContext; +import java.awt.font.GlyphVector; +import java.util.Arrays; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@SuppressWarnings("UnnecessaryUnicodeEscape") +public class ShapingContextTest { + // The shape of each letter depends on both neighbours + private static final String DUAL_JOINING_LETTERS = "\u0628\u064a\u062a"; + + private static final FontRenderContext FRC = new FontRenderContext(null, true, true); + private static final char[] LONG_TEXT = DUAL_JOINING_LETTERS.repeat(1000).toCharArray(); + private static final int START = 1500; + private static final int LIMIT = 1506; + private static final int CONTEXT = 512; + private static final char[] UNCUT_TEXT = Arrays.copyOfRange(LONG_TEXT, START - CONTEXT, LIMIT + CONTEXT); + + private static Font font; + + @BeforeAll + static void findFont() { + font = Stream.concat( + Stream.of(Font.DIALOG), + Arrays.stream(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()) + ) + .map(fontFamily -> new Font(fontFamily, Font.PLAIN, 20)) + .filter(f -> f.canDisplayUpTo(UNCUT_TEXT, 0, UNCUT_TEXT.length) == -1) + // Some fonts like AAT fonts with morx on macOS or Arial on Windows are not joining letters + .filter(f -> !glyphsWithPrefix(f, "\u0628").equals(glyphsWithPrefix(f, ""))) + .findFirst() + .orElse(null); + assumeTrue(font != null, "No font to test joining letters"); + System.out.println("Using font " + font.getFontName()); + } + + @Test + void cutIsShapedAsUncut() { + String uncut = glyphsUncut(font); + String cut = glyphs(font, LONG_TEXT, START, LIMIT); + assertEquals(uncut, cut, "Context should properly affect joining symbols"); + } + + private static String glyphsUncut(Font font) { + return glyphs(font, UNCUT_TEXT, CONTEXT, UNCUT_TEXT.length - CONTEXT); + } + + private static String glyphsWithPrefix(Font font, String prefix) { + char[] text = (prefix + DUAL_JOINING_LETTERS).toCharArray(); + return glyphs(font, text, prefix.length(), text.length); + } + + /** + * Lays out {@code text[start, limit)} and lists glyphs in the resulting part. + */ + private static String glyphs(Font font, char[] text, int start, int limit) { + GlyphVector gv = font.layoutGlyphVector(FRC, text, start, limit, Font.LAYOUT_RIGHT_TO_LEFT); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < gv.getNumGlyphs(); ++i) { + int glyphCharIndex = gv.getGlyphCharIndex(i); + sb.append(gv.getGlyphCode(i)).append('@').append(glyphCharIndex).append(' '); + } + return sb.toString().trim(); + } +} diff --git a/test/micro/org/openjdk/bench/java/awt/font/TextLayoutBench.java b/test/micro/org/openjdk/bench/java/awt/font/TextLayoutBench.java new file mode 100644 index 00000000000..d2129d871e5 --- /dev/null +++ b/test/micro/org/openjdk/bench/java/awt/font/TextLayoutBench.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2026, JetBrains s.r.o.. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package org.openjdk.bench.java.awt.font; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +import java.awt.Font; +import java.awt.font.FontRenderContext; +import java.awt.font.TextAttribute; +import java.awt.font.TextLayout; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * JDK-8396893: measures {@code TextLayout} creation for text that HarfBuzz shapes in many runs. + *

+ * The text alternates Latin and Cyrillic words, so every word is a separate shaping run. + * Kerning makes {@code Graphics2D.drawString} take the same {@code TextLayout} path. + * Shaping time must grow linearly with the text length. + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(value = 2, jvmArgsAppend = "-Djava.awt.headless=true") +@State(Scope.Thread) +public class TextLayoutBench { + + @Param({"100", "10000", "100000"}) + private int length; + + private String text; + private Font font; + private FontRenderContext frc; + + @Setup + public void setup() { + String words = "hello привет "; + text = words.repeat(length / words.length() + 1).substring(0, length); + font = new Font(Map.of( + TextAttribute.FAMILY, Font.DIALOG, + TextAttribute.SIZE, 13f, + TextAttribute.KERNING, TextAttribute.KERNING_ON + )); + frc = new FontRenderContext(null, true, true); + } + + @Benchmark + public void createTextLayout(Blackhole bh) { + bh.consume(new TextLayout(text, font, frc)); + } +} From d0a05842517134d6a3909e74cfa5d2344dda4630 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Tue, 24 Nov 2026 10:58:01 +0000 Subject: [PATCH 58/95] 8385866: G1: IHOP target occupancy evaluation races with heap resizing Reviewed-by: tschatzl --- src/hotspot/share/gc/g1/g1IHOPControl.cpp | 38 ++++++++++++++--------- src/hotspot/share/gc/g1/g1IHOPControl.hpp | 5 +-- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/hotspot/share/gc/g1/g1IHOPControl.cpp b/src/hotspot/share/gc/g1/g1IHOPControl.cpp index 782cdadc13b..2c11bfd2cca 100644 --- a/src/hotspot/share/gc/g1/g1IHOPControl.cpp +++ b/src/hotspot/share/gc/g1/g1IHOPControl.cpp @@ -27,6 +27,7 @@ #include "gc/g1/g1Predictions.hpp" #include "gc/g1/g1Trace.hpp" #include "logging/log.hpp" +#include "runtime/safepoint.hpp" double G1IHOPControl::predict(const TruncatedSeq* seq) const { assert(_is_adaptive, "precondition"); @@ -41,7 +42,7 @@ bool G1IHOPControl::have_enough_data_for_prediction() const { ((size_t)_old_non_humongous_alloc_rate.num() >= G1AdaptiveIHOPNumInitialSamples); } -size_t G1IHOPControl::effective_target_occupancy() const { +size_t G1IHOPControl::effective_target_occupancy(size_t target_occupancy) const { assert(_is_adaptive, "precondition"); // The effective target occupancy takes the heap reserve and the expected waste in @@ -56,7 +57,7 @@ size_t G1IHOPControl::effective_target_occupancy() const { return (size_t)MIN2( G1CollectedHeap::heap()->max_capacity() * (100.0 - safe_total_heap_percentage) / 100.0, - _target_occupancy * (100.0 - _heap_waste_percent) / 100.0 + target_occupancy * (100.0 - _heap_waste_percent) / 100.0 ); } @@ -82,14 +83,17 @@ G1IHOPControl::G1IHOPControl(double ihop_percent, void G1IHOPControl::update_target_occupancy(size_t new_target_occupancy) { log_debug(gc, ihop)("Target occupancy update: old: %zuB, new: %zuB", - _target_occupancy, new_target_occupancy); - _target_occupancy = new_target_occupancy; + _target_occupancy.load_relaxed(), new_target_occupancy); + _target_occupancy.store_relaxed(new_target_occupancy); } void G1IHOPControl::report_statistics(G1NewTracer* new_tracer, size_t non_young_occupancy, size_t non_humongous_allocation, size_t peak_extra_humongous_occupancy) { + // _target_occupancy read more than once, consistent while heap resizing + // by mutators is excluded. + assert(SafepointSynchronize::is_at_safepoint(), "must be"); print_log(non_young_occupancy, non_humongous_allocation, peak_extra_humongous_occupancy); send_trace_event(new_tracer, non_young_occupancy, non_humongous_allocation, peak_extra_humongous_occupancy); @@ -114,10 +118,12 @@ void G1IHOPControl::record_concurrent_cycle(double marking_start_to_mixed_time_s // concurrent marking such that reclamation (first Mixed GC) begins // before the heap reaches a critical occupancy level. size_t G1IHOPControl::old_gen_threshold_for_conc_mark_start() const { - guarantee(_target_occupancy > 0, "Target occupancy must be initialized"); + // May race with heap resizing; use a single snapshot of the target occupancy + size_t target_occupancy = _target_occupancy.load_relaxed(); + guarantee(target_occupancy > 0, "Target occupancy must be initialized"); if (!_is_adaptive || !have_enough_data_for_prediction()) { - return (size_t)(_initial_ihop_percent * _target_occupancy / 100.0); + return (size_t)(_initial_ihop_percent * target_occupancy / 100.0); } // Between Concurrent Start GC and the first Mixed GC (i.e. concurrent cycle), @@ -144,7 +150,7 @@ size_t G1IHOPControl::old_gen_threshold_for_conc_mark_start() const { predict(&_peak_extra_humongous_occupancy_in_mark_cycle); size_t reserve_for_young_regions = _expected_young_gen_at_first_mixed_gc; - size_t target_heap_occupancy = effective_target_occupancy(); + size_t target_heap_occupancy = effective_target_occupancy(target_occupancy); size_t needed_for_concurrent_cycle = reserve_for_young_regions + old_non_humongous_alloc_bytes + @@ -158,20 +164,21 @@ size_t G1IHOPControl::old_gen_threshold_for_conc_mark_start() const { void G1IHOPControl::print_log(size_t non_young_occupancy, size_t non_humongous_allocation, size_t peak_extra_humongous_occupancy) { - assert(_target_occupancy > 0, "Target occupancy still not updated yet."); + size_t target_occupancy = _target_occupancy.load_relaxed(); + assert(target_occupancy > 0, "Target occupancy still not updated yet."); size_t old_gen_mark_start_threshold = old_gen_threshold_for_conc_mark_start(); log_debug(gc, ihop)("Basic information (value update), old-gen threshold: %zuB (%1.2f%%), target occupancy: %zuB, old-gen occupancy: %zuB (%1.2f%%)", old_gen_mark_start_threshold, - percent_of(old_gen_mark_start_threshold, _target_occupancy), - _target_occupancy, + percent_of(old_gen_mark_start_threshold, target_occupancy), + target_occupancy, non_young_occupancy, - percent_of(non_young_occupancy, _target_occupancy)); + percent_of(non_young_occupancy, target_occupancy)); if (!_is_adaptive || !have_enough_data_for_prediction()) { return; } - size_t effective_target = effective_target_occupancy(); + size_t effective_target = effective_target_occupancy(target_occupancy); log_debug(gc, ihop)("Adaptive IHOP information (value update), old-gen threshold: %zuB (%1.2f%%), internal target occupancy: %zuB, " "old-gen occupancy: %zuB (%1.2f%%), additional buffer size: %zuB, " "current non-humongous allocation: %zuB, current peak extra humongous occupancy: %zuB, " @@ -193,14 +200,15 @@ void G1IHOPControl::send_trace_event(G1NewTracer* tracer, size_t non_young_occupancy, size_t non_humongous_allocation, size_t peak_extra_humongous_occupancy) { - assert(_target_occupancy > 0, "Target occupancy still not updated yet."); + size_t target_occupancy = _target_occupancy.load_relaxed(); + assert(target_occupancy > 0, "Target occupancy still not updated yet."); tracer->report_basic_ihop_statistics(old_gen_threshold_for_conc_mark_start(), - _target_occupancy, + target_occupancy, non_young_occupancy); if (_is_adaptive) { tracer->report_adaptive_ihop_statistics(old_gen_threshold_for_conc_mark_start(), - effective_target_occupancy(), + effective_target_occupancy(target_occupancy), non_young_occupancy, _expected_young_gen_at_first_mixed_gc, non_humongous_allocation, diff --git a/src/hotspot/share/gc/g1/g1IHOPControl.hpp b/src/hotspot/share/gc/g1/g1IHOPControl.hpp index df92f31065f..044f2ccbb08 100644 --- a/src/hotspot/share/gc/g1/g1IHOPControl.hpp +++ b/src/hotspot/share/gc/g1/g1IHOPControl.hpp @@ -26,6 +26,7 @@ #define SHARE_GC_G1_G1IHOPCONTROL_HPP #include "memory/allocation.hpp" +#include "runtime/atomic.hpp" #include "utilities/numberSeq.hpp" class G1Predictions; @@ -44,7 +45,7 @@ class G1IHOPControl : public CHeapObj { // The target maximum occupancy of the heap. The target occupancy is the number // of bytes when marking should be finished and reclaim started. - size_t _target_occupancy; + Atomic _target_occupancy; // Percentage of maximum heap capacity we should avoid to touch const size_t _heap_reserve_percent; @@ -79,7 +80,7 @@ class G1IHOPControl : public CHeapObj { // The "effective" target occupancy the algorithm wants to keep until the start // of Mixed GCs. This is typically lower than the target occupancy, as the // algorithm needs to consider restrictions by the environment. - size_t effective_target_occupancy() const; + size_t effective_target_occupancy(size_t target_occupancy) const; void print_log(size_t non_young_occupancy, size_t non_humongous_allocation, From 1e4cf8b4b199b9204fd0754c1f44def4203ef4da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Gr=C3=B6nlund?= Date: Tue, 24 Nov 2026 11:29:28 +0000 Subject: [PATCH 59/95] 8397416: ClassLoadingService incorrectly counts scratch and discarded classes as loaded Reviewed-by: dholmes, sspitsyn --- .../share/classfile/classFileParser.cpp | 2 - .../share/classfile/systemDictionary.cpp | 4 - .../share/jfr/periodic/jfrPeriodic.cpp | 16 ++- src/hotspot/share/oops/instanceKlass.cpp | 1 + .../share/services/classLoadingService.cpp | 30 +++-- .../RedefinitionCounts.java | 112 ++++++++++++++++++ .../TestClassLoadingStatisticsEvent.java | 110 +++++++++++++++-- 7 files changed, 247 insertions(+), 28 deletions(-) create mode 100644 test/jdk/java/lang/management/ClassLoadingMXBean/RedefinitionCounts.java diff --git a/src/hotspot/share/classfile/classFileParser.cpp b/src/hotspot/share/classfile/classFileParser.cpp index ea36d68d397..4956dbfeeba 100644 --- a/src/hotspot/share/classfile/classFileParser.cpp +++ b/src/hotspot/share/classfile/classFileParser.cpp @@ -5766,8 +5766,6 @@ void ClassFileParser::fill_instance_klass(InstanceKlass* ik, create_acmp_maps(ik, CHECK); } - ClassLoadingService::notify_class_loaded(ik, false /* not shared class */); - if (!is_internal()) { ik->print_class_load_logging(_loader_data, module_entry, _stream); if (CDSConfig::is_dumping_archive()) { diff --git a/src/hotspot/share/classfile/systemDictionary.cpp b/src/hotspot/share/classfile/systemDictionary.cpp index 16bdb165a64..562ea7a64e2 100644 --- a/src/hotspot/share/classfile/systemDictionary.cpp +++ b/src/hotspot/share/classfile/systemDictionary.cpp @@ -79,7 +79,6 @@ #include "runtime/sharedRuntime.hpp" #include "runtime/signature.hpp" #include "runtime/synchronizer.hpp" -#include "services/classLoadingService.hpp" #include "services/diagnosticCommand.hpp" #include "services/finalizerService.hpp" #include "services/threadService.hpp" @@ -1282,9 +1281,6 @@ void SystemDictionary::load_shared_class_misc(InstanceKlass* ik, ClassLoaderData ik->set_classpath_index(path_index); } - // notify a class loaded from shared object - ClassLoadingService::notify_class_loaded(ik, true /* shared class */); - if (CDSConfig::is_dumping_with_input_archive()) { AOTSystemDictionary::init_dumptime_info_from_input_archive(ik); } diff --git a/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp b/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp index 83d58c704fc..dde698be025 100644 --- a/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp +++ b/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp @@ -58,6 +58,7 @@ #include "runtime/flags/jvmFlag.hpp" #include "runtime/globals.hpp" #include "runtime/interfaceSupport.inline.hpp" +#include "runtime/orderAccess.hpp" #include "runtime/os.hpp" #include "runtime/os_perf.hpp" #include "runtime/thread.inline.hpp" @@ -576,9 +577,20 @@ TRACE_REQUEST_FUNC(GCHeapMemoryPoolUsage) { TRACE_REQUEST_FUNC(ClassLoadingStatistics) { #if INCLUDE_MANAGEMENT + jlong loaded; + jlong unloaded; + do { + loaded = ClassLoadingService::loaded_class_count(); + unloaded = ClassLoadingService::unloaded_class_count(); + // Keep the initial reads before the validation reads. Both totals are + // cumulative, so unchanged values establish a consistent snapshot. + OrderAccess::loadload(); + } while (loaded != ClassLoadingService::loaded_class_count() || + unloaded != ClassLoadingService::unloaded_class_count()); + EventClassLoadingStatistics event; - event.set_loadedClassCount(ClassLoadingService::loaded_class_count()); - event.set_unloadedClassCount(ClassLoadingService::unloaded_class_count()); + event.set_loadedClassCount(loaded); + event.set_unloadedClassCount(unloaded); event.commit(); #else log_debug(jfr, system)("Unable to generate requestable event ClassLoadingStatistics. The required jvm feature 'management' is missing."); diff --git a/src/hotspot/share/oops/instanceKlass.cpp b/src/hotspot/share/oops/instanceKlass.cpp index bc64ab41b0e..0e809b22247 100644 --- a/src/hotspot/share/oops/instanceKlass.cpp +++ b/src/hotspot/share/oops/instanceKlass.cpp @@ -1780,6 +1780,7 @@ void InstanceKlass::add_to_hierarchy(JavaThread* current) { MutexLocker ml(current, Compile_lock); set_init_state(InstanceKlass::loaded); + ClassLoadingService::notify_class_loaded(this, in_aot_cache()); // make sure init_state store is already done. // The compiler reads the hierarchy outside of the Compile_lock. // Access ordering is used to add to hierarchy. diff --git a/src/hotspot/share/services/classLoadingService.cpp b/src/hotspot/share/services/classLoadingService.cpp index 3f4c1bf9b9f..f638749cd93 100644 --- a/src/hotspot/share/services/classLoadingService.cpp +++ b/src/hotspot/share/services/classLoadingService.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ #include "oops/instanceKlass.hpp" #include "oops/method.hpp" #include "oops/oop.inline.hpp" +#include "runtime/atomicAccess.hpp" #include "runtime/mutexLocker.hpp" #include "services/classLoadingService.hpp" #include "services/memoryService.hpp" @@ -151,12 +152,24 @@ void ClassLoadingService::reset_trace_class_unloading() { LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, unload)); } +// Class-count readers can run concurrently with loading and unloading. +static jlong read_class_count(PerfCounter* counter) { + return AtomicAccess::load(static_cast(counter->get_address())); +} + +// Loading increments are serialized by Compile_lock. +// Unloading increments run under ClassLoaderDataGraph_lock or at a safepoint. +static void increment_class_count(PerfCounter* counter) { + jlong* const address = static_cast(counter->get_address()); + AtomicAccess::store(address, AtomicAccess::load(address) + 1); +} + jlong ClassLoadingService::loaded_class_count() { - return _classes_loaded_count->get_value() + _shared_classes_loaded_count->get_value(); + return read_class_count(_classes_loaded_count) + read_class_count(_shared_classes_loaded_count); } jlong ClassLoadingService::unloaded_class_count() { - return _classes_unloaded_count->get_value() + _shared_classes_unloaded_count->get_value(); + return read_class_count(_classes_unloaded_count) + read_class_count(_shared_classes_unloaded_count); } jlong ClassLoadingService::loaded_class_bytes() { @@ -168,11 +181,11 @@ jlong ClassLoadingService::unloaded_class_bytes() { } jlong ClassLoadingService::loaded_shared_class_count() { - return _shared_classes_loaded_count->get_value(); + return read_class_count(_shared_classes_loaded_count); } jlong ClassLoadingService::unloaded_shared_class_count() { - return _shared_classes_unloaded_count->get_value(); + return read_class_count(_shared_classes_unloaded_count); } jlong ClassLoadingService::loaded_shared_class_bytes() { @@ -206,11 +219,13 @@ static size_t compute_class_size(InstanceKlass* k) { } void ClassLoadingService::notify_class_loaded(InstanceKlass* k, bool shared_class) { + assert_lock_strong(Compile_lock); + assert(k->init_state() == InstanceKlass::loaded, "invariant"); DTRACE_CLASSLOAD_PROBE(loaded, k, shared_class); PerfCounter* classes_counter = (shared_class ? _shared_classes_loaded_count : _classes_loaded_count); // increment the count - classes_counter->inc(); + increment_class_count(classes_counter); if (UsePerfData) { PerfCounter* classbytes_counter = (shared_class ? _shared_classbytes_loaded @@ -222,9 +237,10 @@ void ClassLoadingService::notify_class_loaded(InstanceKlass* k, bool shared_clas } void ClassLoadingService::notify_class_unloaded(InstanceKlass* k) { + assert_locked_or_safepoint(ClassLoaderDataGraph_lock); DTRACE_CLASSLOAD_PROBE(unloaded, k, false); // Classes that can be unloaded must be non-shared - _classes_unloaded_count->inc(); + increment_class_count(_classes_unloaded_count); if (UsePerfData) { // add the class size diff --git a/test/jdk/java/lang/management/ClassLoadingMXBean/RedefinitionCounts.java b/test/jdk/java/lang/management/ClassLoadingMXBean/RedefinitionCounts.java new file mode 100644 index 00000000000..0aca0750347 --- /dev/null +++ b/test/jdk/java/lang/management/ClassLoadingMXBean/RedefinitionCounts.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8397416 + * @summary Class loading counters must not include scratch classes created by redefinition + * @requires vm.flagless & vm.jvmti + * @library /test/lib + * @modules java.instrument java.management + * @build RedefinitionCounts + * @run driver jdk.test.lib.util.JavaAgentBuilder RedefinitionCounts RedefinitionCounts.jar + * @run main/othervm -javaagent:RedefinitionCounts.jar RedefinitionCounts retransform + * @run main/othervm -javaagent:RedefinitionCounts.jar RedefinitionCounts redefine + */ + +import java.io.InputStream; +import java.lang.instrument.ClassDefinition; +import java.lang.instrument.Instrumentation; +import java.lang.management.ClassLoadingMXBean; +import java.lang.management.ManagementFactory; + +import jdk.test.lib.Asserts; + +public class RedefinitionCounts { + private static final ClassLoadingMXBean CLASS_LOADING = ManagementFactory.getClassLoadingMXBean(); + private static Instrumentation instrumentation; + + public static class Target { + public static int value() { + return 4711; + } + } + + public static void premain(String arguments, Instrumentation agent) { + instrumentation = agent; + } + + private record Counts(long loaded, long total, long unloaded) {} + + public static void main(String[] arguments) throws Exception { + boolean retransform = arguments[0].equals("retransform"); + Class[] targets = { Target.class }; + ClassDefinition[] definitions; + try (InputStream stream = Target.class.getResourceAsStream("RedefinitionCounts$Target.class")) { + definitions = new ClassDefinition[] { new ClassDefinition(Target.class, stream.readAllBytes()) }; + } + Asserts.assertEquals(4711, Target.value()); + + for (int iteration = 0; iteration < 10; iteration++) { + transform(retransform, targets, definitions); + readCounts(); + } + + Counts before = readCounts(); + for (int iteration = 0; iteration < 100; iteration++) { + transform(retransform, targets, definitions); + } + Counts after = readCounts(); + + System.out.println("Mode: " + arguments[0]); + System.out.println("Before: " + before); + System.out.println("After: " + after); + + Asserts.assertEquals(before.total(), after.total(), + "Redefinition must not increase the total loaded class count"); + Asserts.assertEquals(before.unloaded() - after.unloaded(), after.loaded() - before.loaded(), + "Redefinition must not inflate the current loaded class count"); + Asserts.assertEquals(4711, Target.value()); + } + + private static void transform(boolean retransform, Class[] targets, + ClassDefinition[] definitions) throws Exception { + if (retransform) { + instrumentation.retransformClasses(targets); + } else { + instrumentation.redefineClasses(definitions); + } + } + + private static Counts readCounts() { + while (true) { + long total = CLASS_LOADING.getTotalLoadedClassCount(); + long unloaded = CLASS_LOADING.getUnloadedClassCount(); + int loaded = CLASS_LOADING.getLoadedClassCount(); + // Accept only if both cumulative counters stayed unchanged across the current-count read. + if (total == CLASS_LOADING.getTotalLoadedClassCount() && unloaded == CLASS_LOADING.getUnloadedClassCount()) { + return new Counts(loaded, total, unloaded); + } + } + } +} diff --git a/test/jdk/jdk/jfr/event/runtime/TestClassLoadingStatisticsEvent.java b/test/jdk/jdk/jfr/event/runtime/TestClassLoadingStatisticsEvent.java index 6184a6f627e..45153c8de4e 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestClassLoadingStatisticsEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestClassLoadingStatisticsEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ package jdk.jfr.event.runtime; +import java.io.InputStream; +import java.lang.instrument.ClassDefinition; +import java.lang.instrument.Instrumentation; import java.util.List; import jdk.jfr.Recording; @@ -33,7 +36,7 @@ import jdk.test.lib.jfr.TestClassLoader; /** - * @test + * @test id=loading * @requires vm.flagless * @requires vm.hasJFR * @library /test/lib /test/jdk @@ -41,6 +44,32 @@ * @build jdk.jfr.event.runtime.TestClasses * @run main/othervm jdk.jfr.event.runtime.TestClassLoadingStatisticsEvent */ +/* + * @test id=retransform + * @bug 8397416 + * @summary JFR class loading statistics must not include scratch classes created by retransformation + * @requires vm.flagless & vm.hasJFR & vm.jvmti + * @library /test/lib /test/jdk + * @modules java.instrument jdk.jfr + * @build jdk.jfr.event.runtime.TestClassLoadingStatisticsEvent + * @run driver jdk.test.lib.util.JavaAgentBuilder + * jdk.jfr.event.runtime.TestClassLoadingStatisticsEvent TestClassLoadingStatisticsEvent.jar + * @run main/othervm -javaagent:TestClassLoadingStatisticsEvent.jar + * jdk.jfr.event.runtime.TestClassLoadingStatisticsEvent retransform + */ +/* + * @test id=redefine + * @bug 8397416 + * @summary JFR class loading statistics must not include scratch classes created by redefinition + * @requires vm.flagless & vm.hasJFR & vm.jvmti + * @library /test/lib /test/jdk + * @modules java.instrument jdk.jfr + * @build jdk.jfr.event.runtime.TestClassLoadingStatisticsEvent + * @run driver jdk.test.lib.util.JavaAgentBuilder + * jdk.jfr.event.runtime.TestClassLoadingStatisticsEvent TestClassLoadingStatisticsEvent.jar + * @run main/othervm -javaagent:TestClassLoadingStatisticsEvent.jar + * jdk.jfr.event.runtime.TestClassLoadingStatisticsEvent redefine + */ /** * This test will load a number of classes. After each load step we verify that * the loadedClassCount and unloadedClassCount attributes are correct. @@ -62,7 +91,24 @@ public class TestClassLoadingStatisticsEvent { // to prevent the compiler to optimize away all unread writes public static TestClassLoader unloadableClassLoader; + private static Instrumentation instrumentation; + + public static class Target { + public static int value() { + return 4711; + } + } + + public static void premain(String arguments, Instrumentation agent) { + instrumentation = agent; + } + public static void main(String[] args) throws Throwable { + if (args.length != 0) { + testRedefinition(args[0].equals("retransform")); + return; + } + // Load twice to get more stable result. RecordedEvent event = getCurrentEvent(); event = getCurrentEvent(); @@ -109,24 +155,62 @@ public static void main(String[] args) throws Throwable { event = verifyCountDelta(event, 0, 2); } + private static void testRedefinition(boolean retransform) throws Throwable { + Class[] targets = { Target.class }; + ClassDefinition[] definitions; + try (InputStream stream = Target.class.getResourceAsStream("TestClassLoadingStatisticsEvent$Target.class")) { + definitions = new ClassDefinition[] { new ClassDefinition(Target.class, stream.readAllBytes()) }; + } + Asserts.assertEquals(4711, Target.value()); + + for (int iteration = 0; iteration < 10; iteration++) { + transform(retransform, targets, definitions); + getCurrentEvent(); + } + + RecordedEvent before = getCurrentEvent(); + for (int iteration = 0; iteration < 100; iteration++) { + transform(retransform, targets, definitions); + } + RecordedEvent after = getCurrentEvent(); + + System.out.println("Mode: " + (retransform ? "retransform" : "redefine")); + System.out.println(before); + System.out.println(after); + + Asserts.assertEquals(before.getLong("loadedClassCount"), after.getLong("loadedClassCount"), + "must not count scratch classes as loaded classes"); + Asserts.assertEquals(4711, Target.value()); + } + + private static void transform(boolean retransform, Class[] targets, + ClassDefinition[] definitions) throws Exception { + if (retransform) { + instrumentation.retransformClasses(targets); + } else { + instrumentation.redefineClasses(definitions); + } + } + private static RecordedEvent getCurrentEvent() throws Throwable { - Recording recording = new Recording(); - recording.enable(EVENT_PATH); - recording.start(); - recording.stop(); - List events = Events.fromRecording(recording); - Asserts.assertFalse(events.isEmpty(), "No events in recording"); - RecordedEvent event = events.getFirst(); - return event; + try (Recording recording = new Recording()) { + recording.enable(EVENT_PATH).with("period", "endChunk"); + recording.start(); + recording.stop(); + List events = Events.fromRecording(recording); + Asserts.assertFalse(events.isEmpty(), "No events in recording"); + RecordedEvent event = events.getFirst(); + Asserts.assertEquals(event.getEventType().getName(), EVENT_PATH); + return event; + } } - private static RecordedEvent verifyCountDelta( - RecordedEvent prevEvent, int loadDelta, int unloadDelta) throws Throwable { + private static RecordedEvent verifyCountDelta(RecordedEvent prevEvent, + int loadDelta, int unloadDelta) throws Throwable { RecordedEvent currEvent = null; try { long prevLoad = Events.assertField(prevEvent, "loadedClassCount").getValue(); long prevUnload = Events.assertField(prevEvent, "unloadedClassCount").getValue(); - currEvent = getCurrentEvent(); Events.assertField(currEvent, "loadedClassCount").atLeast(prevLoad + loadDelta); Events.assertField(currEvent, "unloadedClassCount").atLeast(prevUnload + unloadDelta); From 001844c0e984a7c799104eb749a8e4d3c9f70b72 Mon Sep 17 00:00:00 2001 From: Timofei Fedotov Date: Tue, 24 Nov 2026 11:39:38 +0000 Subject: [PATCH 60/95] 8397252: Native convolution reads before the kernel array for zero-sized kernels Reviewed-by: prr, asemenov --- .../classes/sun/awt/image/ImagingLib.java | 23 +++++-- .../libawt/awt/medialib/awt_ImagingLib.c | 24 +++---- .../awt/image/ConvolveOp/ConvolveTest.java | 67 +++++++++++++++++++ 3 files changed, 93 insertions(+), 21 deletions(-) create mode 100644 test/jdk/java/awt/image/ConvolveOp/ConvolveTest.java diff --git a/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java b/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java index fb2191c7ffc..e7150bbc26f 100644 --- a/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java +++ b/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java @@ -77,10 +77,23 @@ public static native int transformBI(BufferedImage src, BufferedImage dst, public static native int transformRaster(Raster src, Raster dst, double[] matrix, int interpType); - public static native int convolveBI(BufferedImage src, BufferedImage dst, - Kernel kernel, int edgeHint); - public static native int convolveRaster(Raster src, Raster dst, - Kernel kernel, int edgeHint); + private static native int convolveBINative(BufferedImage src, BufferedImage dst, + int width, int height, float[] data, int edgeHint); + public static int convolveBI(BufferedImage src, BufferedImage dst, + Kernel kernel, int edgeHint) { + return convolveBINative(src, dst, kernel.getWidth(), + kernel.getHeight(), kernel.getKernelData(null), edgeHint); + } + + private static native int convolveRasterNative(Raster src, Raster dst, + int width, int height, float[] data, int edgeHint); + + public static int convolveRaster(Raster src, Raster dst, + Kernel kernel, int edgeHint) { + return convolveRasterNative(src, dst, kernel.getWidth(), + kernel.getHeight(), kernel.getKernelData(null), edgeHint); + } + public static native int lookupByteBI(BufferedImage src, BufferedImage dst, byte[][] table); public static native int lookupByteRaster(Raster src, Raster dst, @@ -248,7 +261,7 @@ public static BufferedImage filter(BufferedImageOp op, BufferedImage src, case CONVOLVE_OP: ConvolveOp cOp = (ConvolveOp) op; if (convolveBI(src, dst, cOp.getKernel(), - cOp.getEdgeCondition()) > 0) { + cOp.getEdgeCondition()) > 0) { retBI = dst; } break; diff --git a/src/java.desktop/share/native/libawt/awt/medialib/awt_ImagingLib.c b/src/java.desktop/share/native/libawt/awt/medialib/awt_ImagingLib.c index dd282324df3..90fba87bcc4 100644 --- a/src/java.desktop/share/native/libawt/awt/medialib/awt_ImagingLib.c +++ b/src/java.desktop/share/native/libawt/awt/medialib/awt_ImagingLib.c @@ -275,9 +275,10 @@ static int setPixelsFormMlibImage(JNIEnv *env, RasterS_t *rasterP, mlib_image* i * External Functions * ***************************************************************************/ JNIEXPORT jint JNICALL -Java_sun_awt_image_ImagingLib_convolveBI(JNIEnv *env, jobject this, +Java_sun_awt_image_ImagingLib_convolveBINative(JNIEnv *env, jobject this, jobject jsrc, jobject jdst, - jobject jkernel, jint edgeHint) + jint kwidth, jint kheight, + jfloatArray jdata, jint edgeHint) { void *sdata, *ddata; mlib_image *src; @@ -292,9 +293,6 @@ Java_sun_awt_image_ImagingLib_convolveBI(JNIEnv *env, jobject this, int retStatus = 1; float *kern; BufImageS_t *srcImageP, *dstImageP; - jobject jdata; - int kwidth; - int kheight; int w, h; int x, y; mlibHintS_t hint; @@ -307,10 +305,8 @@ Java_sun_awt_image_ImagingLib_convolveBI(JNIEnv *env, jobject this, if (s_nomlib) return 0; if (s_timeIt) (*start_timer)(3600); - kwidth = (*env)->GetIntField(env, jkernel, g_KernelWidthID); - kheight = (*env)->GetIntField(env, jkernel, g_KernelHeightID); - jdata = (*env)->GetObjectField(env, jkernel, g_KernelDataID); klen = (*env)->GetArrayLength(env, jdata); + kern = (float *) (*env)->GetPrimitiveArrayCritical(env, jdata, NULL); if (kern == NULL) { /* out of memory exception already thrown */ @@ -516,9 +512,10 @@ Java_sun_awt_image_ImagingLib_convolveBI(JNIEnv *env, jobject this, } JNIEXPORT jint JNICALL -Java_sun_awt_image_ImagingLib_convolveRaster(JNIEnv *env, jobject this, +Java_sun_awt_image_ImagingLib_convolveRasterNative(JNIEnv *env, jobject this, jobject jsrc, jobject jdst, - jobject jkernel, jint edgeHint) + jint kwidth, jint kheight, + jfloatArray jdata, jint edgeHint) { mlib_image *src; mlib_image *dst; @@ -534,11 +531,8 @@ Java_sun_awt_image_ImagingLib_convolveRaster(JNIEnv *env, jobject this, void *ddata; RasterS_t *srcRasterP; RasterS_t *dstRasterP; - int kwidth; - int kheight; int w, h; int x, y; - jobject jdata; float *kern; /* This function requires a lot of local refs ??? Is 64 enough ??? */ @@ -548,10 +542,8 @@ Java_sun_awt_image_ImagingLib_convolveRaster(JNIEnv *env, jobject this, if (s_nomlib) return 0; if (s_timeIt) (*start_timer)(3600); - kwidth = (*env)->GetIntField(env, jkernel, g_KernelWidthID); - kheight = (*env)->GetIntField(env, jkernel, g_KernelHeightID); - jdata = (*env)->GetObjectField(env, jkernel, g_KernelDataID); klen = (*env)->GetArrayLength(env, jdata); + kern = (float *) (*env)->GetPrimitiveArrayCritical(env, jdata, NULL); if (kern == NULL) { /* out of memory exception already thrown */ diff --git a/test/jdk/java/awt/image/ConvolveOp/ConvolveTest.java b/test/jdk/java/awt/image/ConvolveOp/ConvolveTest.java new file mode 100644 index 00000000000..dc8e68f04fe --- /dev/null +++ b/test/jdk/java/awt/image/ConvolveOp/ConvolveTest.java @@ -0,0 +1,67 @@ + +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8397252 + * @summary Verify convolution after passing kernel data to JNI + * @run main ConvolveTest + */ + +import java.awt.image.BufferedImage; +import java.awt.image.ConvolveOp; +import java.awt.image.Kernel; +import java.awt.image.WritableRaster; + +public class ConvolveTest { + public static void main(String[] args) { + BufferedImage src = new BufferedImage( + 10, 10, BufferedImage.TYPE_INT_RGB); + + src.setRGB(5, 5, 0x123456); + + Kernel kernel = new Kernel(1, 1, new float[] {1.0f}); + ConvolveOp op = new ConvolveOp(kernel); + + BufferedImage dst = op.filter(src, null); + + if (dst.getRGB(5, 5) != src.getRGB(5, 5)) { + throw new RuntimeException( + "Unexpected BufferedImage convolution result"); + } + + WritableRaster srcRaster = src.getRaster(); + WritableRaster dstRaster = op.filter(srcRaster, null); + + for (int band = 0; band < srcRaster.getNumBands(); band++) { + int expected = srcRaster.getSample(5, 5, band); + int actual = dstRaster.getSample(5, 5, band); + + if (actual != expected) { + throw new RuntimeException( + "Unexpected Raster convolution result"); + } + } + } +} From 509a7a2f3e9654105b6d8e5428de6b5d5dfd0b8d Mon Sep 17 00:00:00 2001 From: Suchismith Roy Date: Tue, 24 Nov 2026 11:50:26 +0000 Subject: [PATCH 61/95] 8396867: [PPC64] use indirect memory operand for ZGC atomic nodes Reviewed-by: mdoerr, varadam --- src/hotspot/cpu/ppc/gc/z/z_ppc.ad | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/hotspot/cpu/ppc/gc/z/z_ppc.ad b/src/hotspot/cpu/ppc/gc/z/z_ppc.ad index 0872932ccb2..a660d554f3e 100644 --- a/src/hotspot/cpu/ppc/gc/z/z_ppc.ad +++ b/src/hotspot/cpu/ppc/gc/z/z_ppc.ad @@ -1,6 +1,6 @@ // -// Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. -// Copyright (c) 2025 SAP SE. All rights reserved. +// Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. +// Copyright (c) 2026 SAP SE. All rights reserved. // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. // // This code is free software; you can redistribute it and/or modify it @@ -209,7 +209,7 @@ instruct zStorePNull(memoryAlg4 mem, immP_0 zero, iRegPdst tmp, flagsRegCR0 cr0) ins_pipe(pipe_class_default); %} -instruct zCompareAndSwapP(iRegIdst res, iRegPdst mem, iRegPsrc oldval, iRegPsrc newval, +instruct zCompareAndSwapP(iRegIdst res, indirect mem, iRegPsrc oldval, iRegPsrc newval, iRegPdst tmp1, iRegPdst tmp2, flagsRegCR0 cr0) %{ match(Set res (CompareAndSwapP mem (Binary oldval newval))); match(Set res (WeakCompareAndSwapP mem (Binary oldval newval))); @@ -228,7 +228,7 @@ instruct zCompareAndSwapP(iRegIdst res, iRegPdst mem, iRegPsrc oldval, iRegPsrc ins_pipe(pipe_class_default); %} -instruct zCompareAndSwapP_acq(iRegIdst res, iRegPdst mem, iRegPsrc oldval, iRegPsrc newval, +instruct zCompareAndSwapP_acq(iRegIdst res, indirect mem, iRegPsrc oldval, iRegPsrc newval, iRegPdst tmp1, iRegPdst tmp2, flagsRegCR0 cr0) %{ match(Set res (CompareAndSwapP mem (Binary oldval newval))); match(Set res (WeakCompareAndSwapP mem (Binary oldval newval))); @@ -247,7 +247,7 @@ instruct zCompareAndSwapP_acq(iRegIdst res, iRegPdst mem, iRegPsrc oldval, iRegP ins_pipe(pipe_class_default); %} -instruct zCompareAndExchangeP(iRegPdst res, iRegPdst mem, iRegPsrc oldval, iRegPsrc newval, +instruct zCompareAndExchangeP(iRegPdst res, indirect mem, iRegPsrc oldval, iRegPsrc newval, iRegPdst tmp, flagsRegCR0 cr0) %{ match(Set res (CompareAndExchangeP mem (Binary oldval newval))); effect(TEMP_DEF res, TEMP tmp, KILL cr0); @@ -267,7 +267,7 @@ instruct zCompareAndExchangeP(iRegPdst res, iRegPdst mem, iRegPsrc oldval, iRegP ins_pipe(pipe_class_default); %} -instruct zCompareAndExchangeP_acq(iRegPdst res, iRegPdst mem, iRegPsrc oldval, iRegPsrc newval, +instruct zCompareAndExchangeP_acq(iRegPdst res, indirect mem, iRegPsrc oldval, iRegPsrc newval, iRegPdst tmp, flagsRegCR0 cr0) %{ match(Set res (CompareAndExchangeP mem (Binary oldval newval))); effect(TEMP_DEF res, TEMP tmp, KILL cr0); @@ -287,7 +287,7 @@ instruct zCompareAndExchangeP_acq(iRegPdst res, iRegPdst mem, iRegPsrc oldval, i ins_pipe(pipe_class_default); %} -instruct zGetAndSetP(iRegPdst res, iRegPdst mem, iRegPsrc newval, iRegPdst tmp, flagsRegCR0 cr0) %{ +instruct zGetAndSetP(iRegPdst res, indirect mem, iRegPsrc newval, iRegPdst tmp, flagsRegCR0 cr0) %{ match(Set res (GetAndSetP mem newval)); effect(TEMP_DEF res, TEMP tmp, KILL cr0); From 39fc7e1c14d3c133c0dc0de273d12320bd9a1e70 Mon Sep 17 00:00:00 2001 From: Frederic Parain Date: Tue, 24 Nov 2026 12:08:42 +0000 Subject: [PATCH 62/95] 8396080: C1 x86 port forces long shift count into register Reviewed-by: thartmann, dlong --- src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp b/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp index 61d351efcbf..6b50c744fed 100644 --- a/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp +++ b/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp @@ -585,10 +585,8 @@ void LIRGenerator::do_ShiftOp(ShiftOp* x) { LIRItem value(x->x(), this); LIRItem count(x->y(), this); - ValueTag elemType = x->type()->tag(); - bool must_load_count = !count.is_constant() || elemType == longTag; + bool must_load_count = !count.is_constant(); if (must_load_count) { - // count for long must be in register count.load_item_force(shiftCountOpr()); } else { count.dont_load_item(); From 4289d6059eb9ec94ffedc39d88eb67c8e4149287 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Tue, 24 Nov 2026 13:04:30 +0000 Subject: [PATCH 63/95] 8390642: [Valhalla] Shenandoah: Support compressed oops Reviewed-by: roland, kvn --- .../shenandoahBarrierSetAssembler_aarch64.cpp | 58 ++++++++- .../shenandoahBarrierSetAssembler_aarch64.hpp | 2 + .../gc/shenandoah/shenandoah_aarch64.ad | 62 ++++++++++ .../shenandoahBarrierSetAssembler_ppc.cpp | 53 +++++++- .../shenandoahBarrierSetAssembler_ppc.hpp | 5 + .../cpu/ppc/gc/shenandoah/shenandoah_ppc.ad | 61 +++++++++ .../shenandoahBarrierSetAssembler_riscv.cpp | 57 ++++++++- .../shenandoahBarrierSetAssembler_riscv.hpp | 4 + .../riscv/gc/shenandoah/shenandoah_riscv.ad | 54 ++++++++ .../shenandoahBarrierSetAssembler_x86.cpp | 57 ++++++++- .../shenandoahBarrierSetAssembler_x86.hpp | 4 + .../x86/gc/shenandoah/shenandoah_x86_64.ad | 56 +++++++++ src/hotspot/share/adlc/forms.cpp | 3 +- src/hotspot/share/adlc/formssel.cpp | 2 +- src/hotspot/share/c1/c1_LIRGenerator.cpp | 17 +-- src/hotspot/share/c1/c1_LIRGenerator.hpp | 2 +- .../share/gc/shared/c2/barrierSetC2.cpp | 5 +- .../shenandoah/c1/shenandoahBarrierSetC1.cpp | 87 +++++++++++-- .../shenandoah/c2/shenandoahBarrierSetC2.cpp | 47 +++++-- .../shenandoah/c2/shenandoahBarrierSetC2.hpp | 10 +- .../gc/shenandoah/shenandoahArguments.cpp | 11 -- .../shenandoahObjArrayAllocator.cpp | 9 +- src/hotspot/share/opto/classes.hpp | 1 + src/hotspot/share/opto/compile.cpp | 1 + src/hotspot/share/opto/graphKit.cpp | 5 +- src/hotspot/share/opto/graphKit.hpp | 2 +- src/hotspot/share/opto/lcm.cpp | 1 + src/hotspot/share/opto/memnode.cpp | 19 ++- src/hotspot/share/opto/memnode.hpp | 20 ++- src/hotspot/share/opto/valuetypenode.cpp | 116 +++++++++++++----- src/hotspot/share/opto/valuetypenode.hpp | 1 + 31 files changed, 747 insertions(+), 85 deletions(-) diff --git a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp index 2ebfe916015..c8165e516a1 100644 --- a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.cpp @@ -630,7 +630,37 @@ void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler } } - ShenandoahBarrierStubC2::load_post(masm, node, dst, src, tmp1, tmp2, is_narrow); + ShenandoahBarrierStubC2::load_post(masm, node, dst, src, tmp1, tmp2, is_narrow, noreg); +} + +void ShenandoahBarrierSetAssembler::load_c2_special(const MachNode* node, MacroAssembler* masm, + Register dst, Address src, int offset, + Register tmp1, Register tmp2, Register tmp3) { + assert(src.index() == noreg, "Base register only"); + assert(src.offset() == 0, "Base register only"); + Register src_base = src.base(); + + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + // Do the actual load. This load is the candidate for implicit null check, and MUST come first. + // We must perform a single load for atomicity reasons. + __ ldr(dst, Address(src_base)); + + // Separate words into tmp and dst. + __ uxtw(tmp1, dst); + __ lsr(dst, dst, 32); + + // Do barriers if needed. + if (first_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, tmp1, Address(src_base), tmp2, tmp3, /* narrow = */ true, dst); + } + if (second_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, dst, Address(src_base, 4), tmp2, tmp3, /* narrow = */ true, tmp1); + } + + // Recombine barrier results into dst. + __ orr(dst, tmp1, dst, Assembler::LSL, 32); } void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm, Address dst, bool dst_narrow, @@ -670,6 +700,32 @@ void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssemble ShenandoahBarrierStubC2::store_post(masm, node, dst, tmp2, tmp3); } +void ShenandoahBarrierSetAssembler::store_c2_special(const MachNode* node, MacroAssembler* masm, + Address dst, Register src, int offset, + Register tmp1, Register tmp2, Register tmp3) { + assert(dst.index() == noreg, "Base register only"); + assert(dst.offset() == 0, "Base register only"); + Register dst_base = dst.base(); + + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + if (first_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst_base), tmp1, tmp2, tmp3, true); + } + if (second_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst_base, 4), tmp1, tmp2, tmp3, true); + } + + // Do the actual store + __ str(src, Address(dst_base)); + + if (first_oop || second_oop) { + // Since the atomic store is aligned, we can update one card for both oops. + ShenandoahBarrierStubC2::store_post(masm, node, Address(dst_base), tmp1, tmp2); + } +} + void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr, Register oldval, Register newval, Register tmp1, Register tmp2, Register tmp3, bool exchange, bool narrow, bool weak, bool acquire) { Assembler::operand_size op_size = narrow ? Assembler::word : Assembler::xword; diff --git a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.hpp b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.hpp index 4d12a53154e..2759cca8594 100644 --- a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoahBarrierSetAssembler_aarch64.hpp @@ -94,7 +94,9 @@ class ShenandoahBarrierSetAssembler: public BarrierSetAssembler { #ifdef COMPILER2 // Entry points from Matcher void load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Address addr, Register tmp1, Register tmp2, bool is_narrow, bool is_acquire); + void load_c2_special(const MachNode* node, MacroAssembler* masm, Register dst, Address src, int offset, Register tmp1, Register tmp2, Register tmp3); void store_c2(const MachNode* node, MacroAssembler* masm, Address dst, bool dst_narrow, Register src, bool src_narrow, Register tmp1, Register tmp2, Register tmp3, bool is_volatile); + void store_c2_special(const MachNode* node, MacroAssembler* masm, Address dst, Register src, int offset, Register tmp1, Register tmp2, Register tmp3); void compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr, Register oldval, Register newval, Register tmp1, Register tmp2, Register tmp3, bool exchange, bool narrow, bool weak, bool acquire); void get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register preval, Register newval, Register addr, Register tmp1, Register tmp2, Register tmp3, bool acquire); diff --git a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoah_aarch64.ad b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoah_aarch64.ad index 9ee2fe22c53..a347196ef9f 100644 --- a/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoah_aarch64.ad +++ b/src/hotspot/cpu/aarch64/gc/shenandoah/shenandoah_aarch64.ad @@ -123,6 +123,28 @@ instruct load_N_Volatile_shenandoah(iRegNNoSp dst, indirect mem, rFlagsReg cr) ins_pipe(pipe_class_memory); %} +instruct loadLSpecial_shenandoah(iRegLNoSp dst, immI off, indirect mem, iRegPNoSp tmp, rFlagsReg cr) +%{ + match(Set dst (LoadLSpecial mem off)); + predicate(UseShenandoahGC); + effect(TEMP_DEF dst, TEMP tmp, KILL cr); + // The main load is a candidate to implement implicit null checks. + ins_is_late_expanded_null_check_candidate(true); + format %{ "shenandoah_load_special $dst, $mem" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->load_c2_special(this, masm, + $dst$$Register, + Address($mem$$Register), + $off$$constant, + $tmp$$Register, + rscratch1, + rscratch2 + ); + %} + ins_cost(3*INSN_COST); + ins_pipe(pipe_class_memory); +%} + // ---------------------------------- STORES --------------------------------------- // @@ -243,6 +265,46 @@ instruct encodePAndStoreN_Volatile_shenandoah(indirect mem, iRegP src, iRegPNoSp ins_pipe(pipe_class_memory); %} +instruct storeLSpecial_both_shenandoah(indirect mem, iRegL src, iRegLNoSp tmp, rFlagsReg cr) +%{ + match(Set mem (StoreLSpecial mem src)); + predicate(UseShenandoahGC); + effect(TEMP tmp, KILL cr); + format %{ "shenandoah_store_special $mem, $src\t# both oops" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + Address($mem$$Register), + $src$$Register, + (int)-1, + $tmp$$Register, + rscratch1, + rscratch2 + ); + %} + ins_cost(4*INSN_COST); + ins_pipe(pipe_class_memory); +%} + +instruct storeLSpecial_single_shenandoah(indirect mem, iRegL src, immI off, iRegLNoSp tmp, rFlagsReg cr) +%{ + match(Set mem (StoreLSpecial mem (Binary src off))); + predicate(UseShenandoahGC); + effect(TEMP tmp, KILL cr); + format %{ "shenandoah_store_special $mem, $src\t# single oop" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + Address($mem$$Register), + $src$$Register, + (int)$off$$constant, + $tmp$$Register, + rscratch1, + rscratch2 + ); + %} + ins_cost(4*INSN_COST); + ins_pipe(pipe_class_memory); +%} + // ---------------------- LOAD-STORES ----------------------------------- // diff --git a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp index baeff520d73..13e796a7116 100644 --- a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp +++ b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.cpp @@ -888,7 +888,36 @@ void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler __ isync(); } - ShenandoahBarrierStubC2::load_post(masm, node, dst, Address(addr, disp), tmp1, tmp2, is_narrow); + ShenandoahBarrierStubC2::load_post(masm, node, dst, Address(addr, disp), tmp1, tmp2, is_narrow, noreg); +} + +void ShenandoahBarrierSetAssembler::load_c2_special(const MachNode* node, MacroAssembler* masm, + Register dst, Register addr, int offset, + Register tmp1, Register tmp2, Register tmp3) { + BIG_ENDIAN_ONLY(fatal("This code assumes little-endian machine")); + + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + // Do the actual load. This load is the candidate for implicit null check, and MUST come first. + // We must perform a single load for atomicity reasons. + __ ld(dst, 0, addr); + + // Separate words into tmp and dst. + __ clrldi(tmp1, dst, 32); + __ srdi(dst, dst, 32); + + // Do barriers if needed. + if (first_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, tmp1, Address(addr, 0), tmp2, tmp3, /* narrow = */ true, dst); + } + if (second_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, dst, Address(addr, 4), tmp2, tmp3, /* narrow = */ true, tmp1); + } + + // Recombine barrier results into dst. + __ sldi(dst, dst, 32); + __ orr(dst, dst, tmp1); } void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm, @@ -913,6 +942,28 @@ void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssemble ShenandoahBarrierStubC2::store_post(masm, node, Address(dst, disp), tmp1, tmp2); } +void ShenandoahBarrierSetAssembler::store_c2_special(const MachNode* node, MacroAssembler* masm, + Register dst, Register src, int offset, + Register tmp1, Register tmp2, Register tmp3) { + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + if (first_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst, 0), tmp1, tmp2, tmp3, true); + } + if (second_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst, 4), tmp1, tmp2, tmp3, true); + } + + // Do the actual store + __ std(src, 0, dst); + + if (first_oop || second_oop) { + // Since the atomic store is aligned, we can update one card for both oops. + ShenandoahBarrierStubC2::store_post(masm, node, Address(dst), tmp1, tmp2); + } +} + void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr, Register oldval, Register newval, Register tmp1, Register tmp2, bool exchange, bool narrow, bool weak, bool acquire) { diff --git a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.hpp b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.hpp index 9513e4b314d..91251e248d2 100644 --- a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.hpp +++ b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoahBarrierSetAssembler_ppc.hpp @@ -138,9 +138,14 @@ class ShenandoahBarrierSetAssembler: public BarrierSetAssembler { // Entry points from Matcher void load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Register addr, int disp, Register tmp1, Register tmp2, bool narrow, bool acquire); + void load_c2_special(const MachNode* node, MacroAssembler* masm, Register dst, Register addr, int offset, Register tmp1, Register tmp2, Register tmp3); + void store_c2(const MachNode* node, MacroAssembler* masm, Register dst, int disp, bool dst_narrow, Register src, bool src_narrow, Register tmp1, Register tmp2, Register tmp3); + void store_c2_special(const MachNode* node, MacroAssembler* masm, + Register dst, Register src, int offset, Register tmp1, Register tmp2, Register tmp3); + void compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr, Register oldval, Register newval, Register tmp1, Register tmp2, bool exchange, bool narrow, bool weak, bool acquire); diff --git a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoah_ppc.ad b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoah_ppc.ad index d766a03c699..a3d41aa7db5 100644 --- a/src/hotspot/cpu/ppc/gc/shenandoah/shenandoah_ppc.ad +++ b/src/hotspot/cpu/ppc/gc/shenandoah/shenandoah_ppc.ad @@ -133,6 +133,28 @@ instruct loadP_acq_shenandoah(iRegPdst dst, memoryAlg4 mem, iRegPdstNoScratch tm ins_pipe(pipe_class_memory); %} +instruct loadLSpecial_shenandoah(iRegLdst dst, indirect mem, immI off, iRegPdstNoScratch tmp1, iRegPdstNoScratch tmp2, iRegPdstNoScratch tmp3, flagsRegCR0 cr0) %{ + match(Set dst (LoadLSpecial mem off)); + effect(TEMP_DEF dst, TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr0); + predicate(UseShenandoahGC); + // The main load is a candidate to implement implicit null checks. + ins_is_late_expanded_null_check_candidate(true); + format %{ "shenandoah_load_special $dst, $mem" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->load_c2_special(this, masm, + $dst$$Register, + $mem$$base$$Register, + $off$$constant, + $tmp1$$Register, + $tmp2$$Register, + $tmp3$$Register + ); + %} + ins_cost(MEMORY_REF_COST); + ins_pipe(pipe_class_memory); +%} + + // ---------------------------------- STORES --------------------------------------- // @@ -199,6 +221,45 @@ instruct encodePAndStoreN_shenandoah(memory dst, iRegPsrc src, iRegPdstNoScratch ins_pipe(pipe_class_memory); %} +instruct storeLSpecial_both_shenandoah(indirect dst, iRegLsrc src, iRegPdstNoScratch tmp1, iRegPdstNoScratch tmp2, iRegPdstNoScratch tmp3, flagsRegCR0 cr0) %{ + match(Set dst (StoreLSpecial dst src)); + predicate(UseShenandoahGC); + effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr0); + format %{ "shenandoah_store_special $dst, $src" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + $dst$$base$$Register, + $src$$Register, + -1, + $tmp1$$Register, + $tmp2$$Register, + $tmp3$$Register + ); + %} + ins_cost(MEMORY_REF_COST); + ins_pipe(pipe_class_memory); +%} + +instruct storeLSpecial_single_shenandoah(indirect dst, iRegLsrc src, immI off, iRegPdstNoScratch tmp1, iRegPdstNoScratch tmp2, iRegPdstNoScratch tmp3, flagsRegCR0 cr0) %{ + match(Set dst (StoreLSpecial dst (Binary src off))); + predicate(UseShenandoahGC); + effect(TEMP tmp1, TEMP tmp2, TEMP tmp3, KILL cr0); + format %{ "shenandoah_store_special $dst, $src" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + $dst$$base$$Register, + $src$$Register, + (int)$off$$constant, + $tmp1$$Register, + $tmp2$$Register, + $tmp3$$Register + ); + %} + ins_cost(MEMORY_REF_COST); + ins_pipe(pipe_class_memory); +%} + + // ---------------------- LOAD-STORES ----------------------------------- // diff --git a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp index 07318e6604f..032d484921b 100644 --- a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.cpp @@ -653,7 +653,37 @@ void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler } } - ShenandoahBarrierStubC2::load_post(masm, node, dst, src, tmp1, tmp2, is_narrow); + ShenandoahBarrierStubC2::load_post(masm, node, dst, src, tmp1, tmp2, is_narrow, noreg); +} + +void ShenandoahBarrierSetAssembler::load_c2_special(const MachNode* node, MacroAssembler* masm, Register dst, Address src, int offset, + Register tmp1, Register tmp2, Register tmp3) { + assert(src.index() == noreg, "Base register only"); + assert(src.offset() == 0, "Base register only"); + Register src_base = src.base(); + + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + // Do the actual load. This load is the candidate for implicit null check, and MUST come first. + // We must perform a single load for atomicity reasons. + __ ld(dst, Address(src_base)); + + // Separate words into tmp and dst. + __ zext(tmp1, dst, 32); + __ srli(dst, dst, 32); + + // Do barriers if needed. + if (first_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, tmp1, Address(src_base), tmp2, tmp3, /* narrow = */ true, dst); + } + if (second_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, dst, Address(src_base, 4), tmp2, tmp3, /* narrow = */ true, tmp1); + } + + // Recombine barrier results into dst. + __ slli(dst, dst, 32); + __ orr(dst, dst, tmp1); } void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm, Address dst, bool dst_narrow, @@ -695,6 +725,31 @@ void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssemble ShenandoahBarrierStubC2::store_post(masm, node, dst, tmp2, tmp3); } +void ShenandoahBarrierSetAssembler::store_c2_special(const MachNode* node, MacroAssembler* masm, Address dst, Register src, int offset, + Register tmp1, Register tmp2, Register tmp3) { + assert(dst.index() == noreg, "Base register only"); + assert(dst.offset() == 0, "Base register only"); + Register dst_base = dst.base(); + + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + if (first_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst_base), tmp1, tmp2, tmp3, true); + } + if (second_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst_base, 4), tmp1, tmp2, tmp3, true); + } + + // Do the actual store + __ sd(src, Address(dst_base)); + + if (first_oop || second_oop) { + // Since the atomic store is aligned, we can update one card for both oops. + ShenandoahBarrierStubC2::store_post(masm, node, Address(dst_base), tmp1, tmp2); + } +} + void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr, Register oldval, Register newval, Register tmp1, Register tmp2, Register tmp3, bool exchange, bool narrow, bool is_acquire) { const atomic_memory_order order = is_acquire ? memory_order_seq_cst : memory_order_release; diff --git a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.hpp b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.hpp index 5299d26027e..2bcc0820813 100644 --- a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.hpp +++ b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoahBarrierSetAssembler_riscv.hpp @@ -100,8 +100,12 @@ class ShenandoahBarrierSetAssembler: public BarrierSetAssembler { // Entry points from Matcher void load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Address addr, Register tmp1, Register tmp2, bool is_narrow, bool is_acquire); + void load_c2_special(const MachNode* node, MacroAssembler* masm, Register dst, Address addr, int offset, + Register tmp1, Register tmp2, Register tmp3); void store_c2(const MachNode* node, MacroAssembler* masm, Address dst, bool dst_narrow, Register src, bool src_narrow, Register tmp1, Register tmp2, Register tmp3, bool is_volatile); + void store_c2_special(const MachNode* node, MacroAssembler* masm, Address dst, Register src, int offset, + Register tmp1, Register tmp2, Register tmp3); void compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Register addr, Register oldval, Register newval, Register tmp1, Register tmp2, Register tmp3, bool exchange, bool narrow, bool is_acquire); void get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register preval, Register newval, diff --git a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoah_riscv.ad b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoah_riscv.ad index b02429ace54..aa398064165 100644 --- a/src/hotspot/cpu/riscv/gc/shenandoah/shenandoah_riscv.ad +++ b/src/hotspot/cpu/riscv/gc/shenandoah/shenandoah_riscv.ad @@ -97,6 +97,22 @@ instruct load_N_volatile_shenandoah(iRegNNoSp dst, indirect mem, rFlagsReg cr) ins_pipe(pipe_serial); %} +instruct loadLSpecial_shenandoah(iRegLNoSp dst, indirect mem, immI off, iRegLNoSp tmp, rFlagsReg cr) +%{ + match(Set dst (LoadLSpecial mem off)); + predicate(UseShenandoahGC); + effect(TEMP_DEF dst, TEMP tmp, KILL cr); + // The main load is a candidate to implement implicit null checks. + ins_is_late_expanded_null_check_candidate(true); + format %{ "ld $dst, $mem\t# compressed ptr, shenandoah late-barrier, #@loadLSpecial_shenandoah" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->load_c2_special(this, masm, as_Register($dst$$reg), + Address(as_Register($mem$$base), $mem$$disp), $off$$constant, as_Register($tmp$$reg), t0, t1); + %} + ins_cost(3 * LOAD_COST); + ins_pipe(iload_reg_mem); +%} + instruct storeP_shenandoah(iRegP src, memory mem, iRegPNoSp tmp, rFlagsReg cr) %{ match(Set mem (StoreP mem src)); @@ -217,6 +233,44 @@ instruct encodePAndStoreN_volatile_shenandoah(iRegP src, indirect mem, iRegPNoSp ins_pipe(pipe_serial); %} +instruct storeLSpecial_both_shenandoah(iRegLNoSp src, indirect mem, iRegPNoSp tmp, rFlagsReg cr) +%{ + match(Set mem (StoreLSpecial mem src)); + predicate(UseShenandoahGC); + effect(TEMP tmp, KILL cr); + format %{ "sd $src, $mem\t# shenandoah late-barrier, both oops #@storeLSpecial_shenandoah" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + Address(as_Register($mem$$base), $mem$$disp), + as_Register($src$$reg), + -1, + as_Register($tmp$$reg), + t0, + t1); + %} + ins_cost(3 * STORE_COST); + ins_pipe(istore_reg_mem); +%} + +instruct storeLSpecial_single_shenandoah(iRegLNoSp src, immI off, indirect mem, iRegPNoSp tmp, rFlagsReg cr) +%{ + match(Set mem (StoreLSpecial mem (Binary src off))); + predicate(UseShenandoahGC); + effect(TEMP tmp, KILL cr); + format %{ "sd $src, $mem\t# shenandoah late-barrier, single oop #@storeLSpecial_shenandoah" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + Address(as_Register($mem$$base), $mem$$disp), + as_Register($src$$reg), + (int)$off$$constant, + as_Register($tmp$$reg), + t0, + t1); + %} + ins_cost(3 * STORE_COST); + ins_pipe(istore_reg_mem); +%} + instruct compareAndSwap_P_A_shenandoah(iRegINoSp res, indirect mem, iRegPNoSp oldval, iRegP newval, iRegPNoSp tmp, rFlagsReg cr) %{ match(Set res (CompareAndSwapP mem (Binary oldval newval))); predicate(UseShenandoahGC && needs_acquiring_load_reserved(n) && n->as_LoadStore()->barrier_data() != 0); diff --git a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp index e94e5f87e98..1ab0a008756 100644 --- a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.cpp @@ -723,7 +723,37 @@ void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler __ movq(dst, src); } - ShenandoahBarrierStubC2::load_post(masm, node, dst, src, noreg, noreg, narrow); + ShenandoahBarrierStubC2::load_post(masm, node, dst, src, noreg, noreg, narrow, noreg); +} + +void ShenandoahBarrierSetAssembler::load_c2_special(const MachNode* node, MacroAssembler* masm, + Register dst, Address src, int offset, Register tmp) { + assert(src.index() == noreg, "Base register only"); + assert(src.disp() == 0, "Base register only"); + Register src_base = src.base(); + + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + // Do the actual load. This load is the candidate for implicit null check, and MUST come first. + // We must perform a single load for atomicity reasons. + __ movq(dst, Address(src_base)); + + // Separate words into tmp and dst. + __ movl(tmp, dst); + __ shrq(dst, 32); + + // Do barriers if needed. + if (first_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, tmp, Address(src_base), noreg, noreg, /* narrow = */ true, dst); + } + if (second_oop) { + ShenandoahBarrierStubC2::load_post(masm, node, dst, Address(src_base, 4), noreg, noreg, /* narrow = */ true, tmp); + } + + // Recombine barrier results into dst. + __ shlq(dst, 32); + __ orq(dst, tmp); } void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm, @@ -754,6 +784,31 @@ void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssemble ShenandoahBarrierStubC2::store_post(masm, node, dst, tmp, noreg); } +void ShenandoahBarrierSetAssembler::store_c2_special(const MachNode* node, MacroAssembler* masm, + Address dst, Register src, int offset, Register tmp) { + assert(dst.index() == noreg, "Base register only"); + assert(dst.disp() == 0, "Base register only"); + Register dst_base = dst.base(); + + bool first_oop = offset == 0 || offset == -1; + bool second_oop = offset == 4 || offset == -1; + + if (first_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst_base), tmp, noreg, noreg, true); + } + if (second_oop) { + ShenandoahBarrierStubC2::store_pre(masm, node, Address(dst_base, 4), tmp, noreg, noreg, true); + } + + // Do the actual store + __ movq(Address(dst_base), src); + + if (first_oop || second_oop) { + // Since the atomic store is aligned, we can update one card for both oops. + ShenandoahBarrierStubC2::store_post(masm, node, Address(dst_base), tmp, noreg); + } +} + void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Address addr, Register oldval, Register newval, Register tmp, diff --git a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.hpp b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.hpp index a6d9b814174..234d3a86e3e 100644 --- a/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.hpp +++ b/src/hotspot/cpu/x86/gc/shenandoah/shenandoahBarrierSetAssembler_x86.hpp @@ -91,8 +91,12 @@ class ShenandoahBarrierSetAssembler: public BarrierSetAssembler { #ifdef COMPILER2 // Entry points from Matcher void load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Address src, bool narrow); + void load_c2_special(const MachNode* node, MacroAssembler* masm, + Register dst, Address src, int offset, Register tmp); void store_c2(const MachNode* node, MacroAssembler* masm, Address dst, bool dst_narrow, Register src, bool src_narrow, Register tmp); + void store_c2_special(const MachNode* node, MacroAssembler* masm, + Address dst, Register src, int offset, Register tmp); void compare_and_set_c2(const MachNode* node, MacroAssembler* masm, Register res, Address addr, Register oldval, Register newval, Register tmp, bool narrow); void get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register newval, Address addr, Register tmp, bool narrow); diff --git a/src/hotspot/cpu/x86/gc/shenandoah/shenandoah_x86_64.ad b/src/hotspot/cpu/x86/gc/shenandoah/shenandoah_x86_64.ad index 0301e5f77db..c5d92b14cf0 100644 --- a/src/hotspot/cpu/x86/gc/shenandoah/shenandoah_x86_64.ad +++ b/src/hotspot/cpu/x86/gc/shenandoah/shenandoah_x86_64.ad @@ -69,6 +69,26 @@ instruct loadN_shenandoah(rRegN dst, memory mem, rFlagsReg cr) ins_pipe(ialu_cr_reg_mem); %} +instruct loadLSpecial_shenandoah(indirect mem, immI off, rRegL dst, rRegP tmp, rFlagsReg cr) +%{ + match(Set dst (LoadLSpecial mem off)); + predicate(UseShenandoahGC); + effect(TEMP_DEF dst, TEMP tmp, KILL cr); + // The main load is a candidate to implement implicit null checks. + ins_is_late_expanded_null_check_candidate(true); + format %{ "shenandoah_load_special $dst, $mem" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->load_c2_special(this, masm, + $dst$$Register, + $mem$$Address, + $off$$constant, + $tmp$$Register + ); + %} + ins_cost(125); + ins_pipe(ialu_cr_reg_mem); +%} + // ---------------------------------- STORES --------------------------------------- // @@ -122,6 +142,42 @@ instruct encodePAndStoreN_shenandoah(memory mem, any_RegP src, rRegP tmp, rFlags ins_pipe(ialu_cr_reg_mem); %} +instruct storeLSpecial_both_shenandoah(indirect mem, rRegL src, rRegP tmp, rFlagsReg cr) +%{ + match(Set mem (StoreLSpecial mem src)); + predicate(UseShenandoahGC); + effect(TEMP tmp, KILL cr); + format %{ "shenandoah_store_special $mem, $src\t# two oops" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + $mem$$Address, + $src$$Register, + (int)-1, + $tmp$$Register + ); + %} + ins_cost(125); + ins_pipe(ialu_cr_reg_mem); +%} + +instruct storeLSpecial_single_shenandoah(indirect mem, rRegL src, immI off, rRegP tmp, rFlagsReg cr) +%{ + match(Set mem (StoreLSpecial mem (Binary src off))); + predicate(UseShenandoahGC); + effect(TEMP tmp, KILL cr); + format %{ "shenandoah_store_special $mem, $src\t# single oop" %} + ins_encode %{ + ShenandoahBarrierSet::assembler()->store_c2_special(this, masm, + $mem$$Address, + $src$$Register, + (int)$off$$constant, + $tmp$$Register + ); + %} + ins_cost(125); + ins_pipe(ialu_cr_reg_mem); +%} + // ---------------------- LOAD-STORES ----------------------------------- instruct compareAndSwapP_shenandoah(rRegI res, memory mem, rRegP tmp, rax_RegP oldval, rRegP newval, rFlagsReg cr) diff --git a/src/hotspot/share/adlc/forms.cpp b/src/hotspot/share/adlc/forms.cpp index ddcec91c4ab..53e0ddbbc34 100644 --- a/src/hotspot/share/adlc/forms.cpp +++ b/src/hotspot/share/adlc/forms.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -263,6 +263,7 @@ Form::DataType Form::is_load_from_memory(const char *opType) const { if( strcmp(opType,"LoadNKlass")==0 ) return Form::idealNKlass; if( strcmp(opType,"LoadL")==0 ) return Form::idealL; if( strcmp(opType,"LoadL_unaligned")==0 ) return Form::idealL; + if( strcmp(opType,"LoadLSpecial")==0) return Form::idealL; if( strcmp(opType,"LoadP")==0 ) return Form::idealP; if( strcmp(opType,"LoadN")==0 ) return Form::idealN; if( strcmp(opType,"LoadRange")==0 ) return Form::idealI; diff --git a/src/hotspot/share/adlc/formssel.cpp b/src/hotspot/share/adlc/formssel.cpp index 644dd237ed7..95e6a0a4072 100644 --- a/src/hotspot/share/adlc/formssel.cpp +++ b/src/hotspot/share/adlc/formssel.cpp @@ -3597,7 +3597,7 @@ int MatchNode::needs_ideal_memory_edge(FormDict &globals) const { static const char *needs_ideal_memory_list[] = { "StoreI","StoreL","StoreLSpecial","StoreP","StoreN","StoreNKlass","StoreD","StoreF" , "StoreB","StoreC","Store" ,"StoreFP", - "LoadI", "LoadL", "LoadP" ,"LoadN", "LoadD" ,"LoadF" , + "LoadI", "LoadL", "LoadLSpecial", "LoadP" ,"LoadN", "LoadD" ,"LoadF" , "LoadB" , "LoadUB", "LoadUS" ,"LoadS" ,"Load" , "StoreVector", "LoadVector", "LoadVectorMasked", "StoreVectorMasked", "LoadVectorGather", "StoreVectorScatter", "LoadVectorGatherMasked", "StoreVectorScatterMasked", diff --git a/src/hotspot/share/c1/c1_LIRGenerator.cpp b/src/hotspot/share/c1/c1_LIRGenerator.cpp index f22acc6e3bd..c87fcc0728f 100644 --- a/src/hotspot/share/c1/c1_LIRGenerator.cpp +++ b/src/hotspot/share/c1/c1_LIRGenerator.cpp @@ -1712,7 +1712,7 @@ void LIRGenerator::do_StoreField(StoreField* x) { } // Load payload (if not empty) and set null marker (if not null-free) if (!vk->is_empty()) { - access_load_at(decorators, bt, value, LIR_OprFact::intConst(vk->payload_offset()), payload); + access_load_at(decorators, bt, value, LIR_OprFact::intConst(vk->payload_offset()), payload, nullptr, nullptr, vk); } if (!field->is_null_free()) { __ logical_or(payload, null_marker_mask(bt, field), payload); @@ -1814,7 +1814,7 @@ LIR_Opr LIRGenerator::access_flat_array(bool is_load, LIRItem& array, LIRItem& i LIRItem elm_item(elm_resolved_addr, this); DecoratorSet decorators = IN_HEAP; if (is_load) { - access_load_at(decorators, bt, elm_item, LIR_OprFact::intConst(0), payload, nullptr, nullptr); + access_load_at(decorators, bt, elm_item, LIR_OprFact::intConst(0), payload, nullptr, nullptr, elem_klass); access_store_at(decorators, bt, obj_item, LIR_OprFact::intConst(elem_klass->payload_offset()), payload, nullptr, nullptr, elem_klass); // Null check is performed in the caller @@ -1825,7 +1825,8 @@ LIR_Opr LIRGenerator::access_flat_array(bool is_load, LIRItem& array, LIRItem& i if (null_free) { if (!elem_klass->is_empty()) { - access_load_at(decorators, bt, obj_item, LIR_OprFact::intConst(elem_klass->payload_offset()), payload); + access_load_at(decorators, bt, obj_item, LIR_OprFact::intConst(elem_klass->payload_offset()), payload, + nullptr, nullptr, elem_klass); } } else { bool is_constant_null = obj_item.is_constant() && obj_item.value()->is_null_obj(); @@ -1838,7 +1839,8 @@ LIR_Opr LIRGenerator::access_flat_array(bool is_load, LIRItem& array, LIRItem& i } // Load payload (if not empty) and set null marker. if (!elem_klass->is_empty()) { - access_load_at(decorators, bt, obj_item, LIR_OprFact::intConst(elem_klass->payload_offset()), payload); + access_load_at(decorators, bt, obj_item, LIR_OprFact::intConst(elem_klass->payload_offset()), payload, + nullptr, nullptr, elem_klass); } __ logical_or(payload, null_marker_mask(bt, elem_klass->null_marker_offset_in_payload()), payload); if (needs_null_check) { @@ -2059,9 +2061,10 @@ void LIRGenerator::do_StoreIndexed(StoreIndexed* x) { void LIRGenerator::access_load_at(DecoratorSet decorators, BasicType type, LIRItem& base, LIR_Opr offset, LIR_Opr result, - CodeEmitInfo* patch_info, CodeEmitInfo* load_emit_info) { + CodeEmitInfo* patch_info, CodeEmitInfo* load_emit_info, + ciValueKlass* vk) { decorators |= ACCESS_READ; - LIRAccess access(this, decorators, base, offset, type, patch_info, load_emit_info); + LIRAccess access(this, decorators, base, offset, type, patch_info, load_emit_info, vk); if (access.is_raw()) { _barrier_set->BarrierSetC1::load_at(access, result); } else { @@ -2213,7 +2216,7 @@ void LIRGenerator::do_LoadField(LoadField* x) { LIR_Opr payload = new_register((bt == T_LONG) ? bt : T_INT); access_load_at(decorators, bt, object, LIR_OprFact::intConst(field->offset_in_bytes()), payload, // Make sure to emit an implicit null check - info ? new CodeEmitInfo(info) : nullptr, info); + info ? new CodeEmitInfo(info) : nullptr, info, vk); if (assert_null) { // Deoptimize on non-null because buffering requires the value class to be initialized diff --git a/src/hotspot/share/c1/c1_LIRGenerator.hpp b/src/hotspot/share/c1/c1_LIRGenerator.hpp index 9328ce4a26a..a902721f8a7 100644 --- a/src/hotspot/share/c1/c1_LIRGenerator.hpp +++ b/src/hotspot/share/c1/c1_LIRGenerator.hpp @@ -308,7 +308,7 @@ class LIRGenerator: public InstructionVisitor, public BlockClosure { void access_load_at(DecoratorSet decorators, BasicType type, LIRItem& base, LIR_Opr offset, LIR_Opr result, - CodeEmitInfo* patch_info = nullptr, CodeEmitInfo* load_emit_info = nullptr); + CodeEmitInfo* patch_info = nullptr, CodeEmitInfo* load_emit_info = nullptr, ciValueKlass* vk = nullptr); void access_load(DecoratorSet decorators, BasicType type, LIR_Opr addr, LIR_Opr result); diff --git a/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp b/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp index dd696599a60..4c1886a49f6 100644 --- a/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp +++ b/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp @@ -204,6 +204,7 @@ Node* BarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) con bool unknown_control = (decorators & C2_UNKNOWN_CONTROL_LOAD) != 0; bool unsafe = (decorators & C2_UNSAFE_ACCESS) != 0; bool immutable = (decorators & C2_IMMUTABLE_MEMORY) != 0; + bool special = (decorators & C2_SPECIAL_ACCESS) != 0; MemNode::MemOrd mo = access.mem_node_mo(); LoadNode::ControlDependency dep = unknown_control ? LoadNode::UnknownControl : LoadNode::DependsOnlyOnTest; @@ -215,6 +216,7 @@ Node* BarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) con Node* control = control_dependent ? parse_access.control() : nullptr; if (immutable) { + assert(!special, "Special loads are not immutable"); Compile* C = Compile::current(); Node* mem = kit->immutable_memory(); load = LoadNode::make(kit->gvn(), control, mem, adr, @@ -224,10 +226,11 @@ Node* BarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) con } else { load = kit->make_load(control, adr, val_type, access.type(), mo, dep, requires_atomic_access, unaligned, mismatched, unsafe, - access.barrier_data()); + access.barrier_data(), special); } } else { assert(access.is_opt_access(), "either parse or opt access"); + assert(!special, "Special loads are only parse accesses"); C2OptAccess& opt_access = static_cast(access); Node* control = control_dependent ? opt_access.ctl() : nullptr; MergeMemNode* mm = opt_access.mem(); diff --git a/src/hotspot/share/gc/shenandoah/c1/shenandoahBarrierSetC1.cpp b/src/hotspot/share/gc/shenandoah/c1/shenandoahBarrierSetC1.cpp index 26c4ab99c19..582f9f40684 100644 --- a/src/hotspot/share/gc/shenandoah/c1/shenandoahBarrierSetC1.cpp +++ b/src/hotspot/share/gc/shenandoah/c1/shenandoahBarrierSetC1.cpp @@ -1,7 +1,7 @@ /* * Copyright (c) 2018, 2024, Red Hat, Inc. All rights reserved. * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ */ #include "c1/c1_IR.hpp" +#include "ci/ciValueKlass.hpp" #include "gc/shared/satbMarkQueue.hpp" #include "gc/shenandoah/c1/shenandoahBarrierSetC1.hpp" #include "gc/shenandoah/mode/shenandoahMode.hpp" @@ -172,6 +173,49 @@ void ShenandoahBarrierSetC1::store_at_resolved(LIRAccess& access, LIR_Opr value) DecoratorSet decorators = access.decorators(); LIRGenerator* gen = access.gen(); + bool is_array = (decorators & IS_ARRAY) != 0; + bool on_anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0; + bool precise = is_array || on_anonymous; + LIR_Opr post_addr = precise ? access.resolved_addr() : access.base().opr(); + + ciValueKlass* vk = access.vk(); + if (vk != nullptr && vk->has_object_fields()) { + // This is potentially atomic access to flat object, which needs separate barriers + // for each individual flattened oop field. + assert(!access.is_oop(), "Taking over the real oop barriers"); + + for (int i = 0; i < vk->nof_nonstatic_fields(); i++) { + ciField* field = vk->nonstatic_field_at(i); + if (!field->type()->is_primitive_type()) { + int off = access.offset().opr().as_jint() + field->offset_in_bytes() - vk->payload_offset(); + CodeEmitInfo* info = access.patch_emit_info(); + if (info != nullptr) { + info = new CodeEmitInfo(info); + } + CodeEmitInfo* access_info = access.access_emit_info(); + if (access_info != nullptr) { + access_info = new CodeEmitInfo(access_info); + } + LIRAccess inner_access(access.gen(), decorators, access.base(), LIR_OprFact::intConst(off), field->type()->basic_type(), info, access_info); + LIR_Opr addr = resolve_address(inner_access, false); + inner_access.set_resolved_addr(addr); + + LIR_Opr tmp = gen->new_register(T_OBJECT); + if (ShenandoahSATBBarrier || ShenandoahCardBarrier) { + BarrierSetC1::load_at_resolved(inner_access, tmp); + if (ShenandoahSATBBarrier) { + keepalive_barrier(gen, /* obj = */ tmp, /* addr = */ LIR_OprFact::illegalOpr, nullptr, decorators); + } + if (ShenandoahCardBarrier) { + // Card barriers are usually *post*-barriers, but in current Shenandoah we can perform + // this barrier before the actual store to simplify this code. + card_barrier(gen, post_addr, decorators); + } + } + } + } + } + if (ShenandoahSATBBarrier && access.is_oop()) { CodeEmitInfo* info = access.access_emit_info(); if (info != nullptr) { @@ -182,11 +226,6 @@ void ShenandoahBarrierSetC1::store_at_resolved(LIRAccess& access, LIR_Opr value) BarrierSetC1::store_at_resolved(access, value); if (ShenandoahCardBarrier && access.is_oop()) { - bool is_array = (decorators & IS_ARRAY) != 0; - bool on_anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0; - - bool precise = is_array || on_anonymous; - LIR_Opr post_addr = precise ? access.resolved_addr() : access.base().opr(); card_barrier(gen, post_addr, decorators); } } @@ -200,14 +239,44 @@ LIR_Opr ShenandoahBarrierSetC1::resolve_address(LIRAccess& access, bool resolve_ } void ShenandoahBarrierSetC1::load_at_resolved(LIRAccess& access, LIR_Opr result) { + LIRGenerator* gen = access.gen(); + DecoratorSet decorators = access.decorators(); + + // 0: Handle flat classes, which need separate barriers for each individual flattened oop field. + ciValueKlass* vk = access.vk(); + if (ShenandoahLoadRefBarrier && vk != nullptr && vk->has_object_fields()) { + assert(!access.is_oop(), "Taking over the real oop barriers"); + + for (int i = 0; i < vk->nof_nonstatic_fields(); i++) { + ciField* field = vk->nonstatic_field_at(i); + if (!field->type()->is_primitive_type()) { + int off = access.offset().opr().as_jint() + field->offset_in_bytes() - vk->payload_offset(); + CodeEmitInfo *info = access.patch_emit_info(); + if (info != nullptr) { + info = new CodeEmitInfo(info); + } + CodeEmitInfo* access_info = access.access_emit_info(); + if (access_info != nullptr) { + access_info = new CodeEmitInfo(access_info); + } + LIRAccess inner_access(access.gen(), decorators, access.base(), LIR_OprFact::intConst(off), field->type()->basic_type(), info, access_info); + LIR_Opr addr = resolve_address(inner_access, false); + inner_access.set_resolved_addr(addr); + + // Executing this LRB for the sake of in-memory fixups. + LIR_Opr tmp = gen->new_register(T_OBJECT); + BarrierSetC1::load_at_resolved(inner_access, tmp); + load_reference_barrier(gen, tmp, addr, decorators); + } + } + } + // 1: non-reference load, no additional barrier is needed if (!access.is_oop()) { BarrierSetC1::load_at_resolved(access, result); return; } - LIRGenerator* gen = access.gen(); - DecoratorSet decorators = access.decorators(); BasicType type = access.type(); // 2: load a reference from src location and apply LRB if ShenandoahLoadRefBarrier is set @@ -358,6 +427,7 @@ void ShenandoahBarrierSetC1::card_barrier(LIRGenerator* gen, LIR_Opr addr, Decor LIR_Opr ShenandoahBarrierSetC1::atomic_cmpxchg_at_resolved(LIRAccess& access, LIRItem& cmp_value, LIRItem& new_value) { if (!access.is_oop()) { + assert(access.vk() == nullptr, "Unhandled value object"); return BarrierSetC1::atomic_cmpxchg_at_resolved(access, cmp_value, new_value); } @@ -391,6 +461,7 @@ LIR_Opr ShenandoahBarrierSetC1::atomic_cmpxchg_at_resolved(LIRAccess& access, LI LIR_Opr ShenandoahBarrierSetC1::atomic_xchg_at_resolved(LIRAccess& access, LIRItem& value) { if (!access.is_oop()) { + assert(access.vk() == nullptr, "Unhandled value object"); return BarrierSetC1::atomic_xchg_at_resolved(access, value); } diff --git a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp index 20061cb2647..9a52d0a51ee 100644 --- a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp +++ b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.cpp @@ -158,6 +158,7 @@ bool ShenandoahBarrierSetC2::is_Load(int opcode) { switch (opcode) { case Op_LoadN: case Op_LoadP: + case Op_LoadLSpecial: return true; default: return false; @@ -168,6 +169,7 @@ bool ShenandoahBarrierSetC2::is_Store(int opcode) { switch (opcode) { case Op_StoreN: case Op_StoreP: + case Op_StoreLSpecial: return true; default: return false; @@ -190,6 +192,16 @@ bool ShenandoahBarrierSetC2::is_LoadStore(int opcode) { } } +bool ShenandoahBarrierSetC2::is_Special(int opcode) { + switch (opcode) { + case Op_LoadLSpecial: + case Op_StoreLSpecial: + return true; + default: + return false; + } +} + bool ShenandoahBarrierSetC2::can_remove_load_barrier(Node* root) { // Check if all outs feed into nodes that do not expose the oops to the rest // of the runtime system. In this case, we can elide the LRB barrier. We bail @@ -297,6 +309,11 @@ uint8_t ShenandoahBarrierSetC2::refine_load(Node* n, uint8_t bd) { assert(ShenandoahElideIdealBarriers, "Checked by caller"); assert(bd != 0, "Checked by caller"); + if (n->Opcode() == Op_LoadLSpecial) { + // Skip any refinement for special nodes for now. + return bd; + } + // Do not touch weak loads at all: they are responsible for shielding from // Reference.referent resurrection. if ((bd & (ShenandoahBitWeak | ShenandoahBitPhantom)) != 0) { @@ -315,6 +332,11 @@ uint8_t ShenandoahBarrierSetC2::refine_store(Node* n, uint8_t bd) { assert(bd != 0, "Checked by caller"); assert(n->is_Mem() || n->is_LoadStore(), "Sanity"); + if (n->Opcode() == Op_StoreLSpecial) { + // Skip any refinement for special nodes for now. + return bd; + } + const Node* newval = n->in(MemNode::ValueIn); assert(newval != nullptr, "Should be present"); @@ -428,6 +450,11 @@ void ShenandoahBarrierSetC2::elide_dominated_barrier(MachNode* node, MachNode* d uint8_t bd = orig_bd; int node_opcode = node->ideal_Opcode(); + if (is_Special(node_opcode)) { + // Do not eliminate barriers on special nodes for now. + return; + } + if (dominator == nullptr) { // Must be allocation node. if (is_Load(node_opcode) || is_LoadStore(node_opcode)) { @@ -446,6 +473,11 @@ void ShenandoahBarrierSetC2::elide_dominated_barrier(MachNode* node, MachNode* d int dom_opcode = dominator->ideal_Opcode(); uint8_t dom_bd = dominator->barrier_data(); + if (is_Special(dom_opcode)) { + // Do not eliminate barriers from special node dominators for now. + return; + } + if (is_Load(dom_opcode) || is_LoadStore(dom_opcode)) { // If dominating load is set up to perform LRB fixups, no further LRB is needed. if ((dom_bd & ShenandoahBitStrong) != 0) { @@ -536,7 +568,8 @@ uint ShenandoahBarrierSetC2::estimated_barrier_size(const Node* node) const { if ((bd & ~ShenandoahBitCardMark) != 0) { // Hot-patched GC state checks are either a single nop or a jump. - nodes += 1; + // Pessimistically assume special nodes have barriers for each offset. + nodes += is_Special(node->Opcode()) ? 2 : 1; } if ((bd & ShenandoahBitCardMark) != 0) { @@ -920,19 +953,19 @@ void ShenandoahBarrierStubC2::register_stub(ShenandoahBarrierStubC2* stub) { } } -ShenandoahBarrierStubC2* ShenandoahBarrierStubC2::create(const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, bool do_load) { - auto* stub = new (Compile::current()->comp_arena()) ShenandoahBarrierStubC2(node, obj, addr, tmp1, tmp2, narrow, do_load); +ShenandoahBarrierStubC2* ShenandoahBarrierStubC2::create(const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, bool do_load, Register preserve1) { + auto* stub = new (Compile::current()->comp_arena()) ShenandoahBarrierStubC2(node, obj, addr, tmp1, tmp2, narrow, do_load, preserve1); register_stub(stub); return stub; } -void ShenandoahBarrierStubC2::load_post(MacroAssembler* masm, const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow) { +void ShenandoahBarrierStubC2::load_post(MacroAssembler* masm, const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, Register preserve1) { // Load post-barrier: // a. Satisfies the need for LRB for normal loads // b. Passes a weak load through LRB-weak // c. Keep-alives a weak load if (needs_slow_barrier(node)) { - ShenandoahBarrierStubC2* const stub = create(node, obj, addr, tmp1, tmp2, narrow, /* do_load = */ false); + ShenandoahBarrierStubC2* const stub = create(node, obj, addr, tmp1, tmp2, narrow, /* do_load = */ false, preserve1); char check = 0; check |= needs_keep_alive_barrier(node) ? ShenandoahHeap::MARKING : 0; check |= needs_load_ref_barrier(node) ? ShenandoahHeap::HAS_FORWARDED : 0; @@ -945,7 +978,7 @@ void ShenandoahBarrierStubC2::store_pre(MacroAssembler* masm, const MachNode* no // Store pre-barrier: SATB, keep-alive the current memory value. if (needs_slow_barrier(node)) { assert(!needs_load_ref_barrier(node), "Should not be required for stores"); - ShenandoahBarrierStubC2* const stub = create(node, tmp1, addr, tmp2, tmp3, narrow, /* do_load = */ true); + ShenandoahBarrierStubC2* const stub = create(node, tmp1, addr, tmp2, tmp3, narrow, /* do_load = */ true, noreg); stub->enter_if_gc_state(*masm, ShenandoahHeap::MARKING, tmp1, tmp2); } } @@ -959,7 +992,7 @@ void ShenandoahBarrierStubC2::load_store_pre(MacroAssembler* masm, const MachNod // (a) and (b) are covered because load barrier does memory location fixup. // (c) is covered by KA on the current memory value. if (needs_slow_barrier(node)) { - ShenandoahBarrierStubC2* const stub = create(node, tmp1, addr, tmp2, tmp3, narrow, /* do_load = */ true); + ShenandoahBarrierStubC2* const stub = create(node, tmp1, addr, tmp2, tmp3, narrow, /* do_load = */ true, noreg); char check = 0; check |= needs_keep_alive_barrier(node) ? ShenandoahHeap::MARKING : 0; check |= needs_load_ref_barrier(node) ? ShenandoahHeap::HAS_FORWARDED : 0; diff --git a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.hpp b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.hpp index c0a8938526c..a36389388e6 100644 --- a/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.hpp +++ b/src/hotspot/share/gc/shenandoah/c2/shenandoahBarrierSetC2.hpp @@ -99,6 +99,7 @@ class ShenandoahBarrierSetC2 : public BarrierSetC2 { static bool is_Load(int opcode); static bool is_Store(int opcode); static bool is_LoadStore(int opcode); + static bool is_Special(int opcode); protected: virtual Node* load_at_resolved(C2Access& access, const Type* val_type) const; @@ -187,10 +188,10 @@ class ShenandoahBarrierStubC2 : public BarrierStubC2 { address keepalive_runtime_entry_addr(); address lrb_runtime_entry_addr(); - static ShenandoahBarrierStubC2* create(const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, bool do_load); + static ShenandoahBarrierStubC2* create(const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, bool do_load, Register preserve1); void post_init(); - ShenandoahBarrierStubC2(const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, bool do_load) : + ShenandoahBarrierStubC2(const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, bool do_load, Register preserve1) : BarrierStubC2(node), _obj(obj), _addr(addr), @@ -209,6 +210,9 @@ class ShenandoahBarrierStubC2 : public BarrierStubC2 { assert(_tmp1 == _tmp2, "should both be noreg"); assert_different_registers(_obj, _addr.base(), _addr.index()); } + if (preserve1 != noreg) { + preserve(preserve1); + } post_init(); } @@ -233,7 +237,7 @@ class ShenandoahBarrierStubC2 : public BarrierStubC2 { return needs_load_ref_barrier(node) || needs_keep_alive_barrier(node); } - static void load_post(MacroAssembler* masm, const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow); + static void load_post(MacroAssembler* masm, const MachNode* node, Register obj, Address addr, Register tmp1, Register tmp2, bool narrow, Register preserve1); static void store_pre(MacroAssembler* masm, const MachNode* node, Address addr, Register tmp1, Register tmp2, Register tmp3, bool narrow); static void store_post(MacroAssembler* masm, const MachNode* node, Address addr, Register tmp1, Register tmp2); static void load_store_pre(MacroAssembler* masm, const MachNode* node, Address addr, Register tmp1, Register tmp2, Register tmp3, bool narrow); diff --git a/src/hotspot/share/gc/shenandoah/shenandoahArguments.cpp b/src/hotspot/share/gc/shenandoah/shenandoahArguments.cpp index d5b6063a659..eebd6d9f9bf 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahArguments.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahArguments.cpp @@ -181,17 +181,6 @@ void ShenandoahArguments::initialize() { ShenandoahAllocRateSampleWindow)); } -#ifdef _LP64 - if (Arguments::is_valhalla_enabled()) { - // Flat atomic payloads may contain embedded oops. Current Valhalla code does not handle - // it well, missing the GC barriers. As the temporary kludge, disable compressed oops: - // this would make flat atomic payloads contain at most one oop, which would be treated - // as the single oop field. - log_warning(gc)("Shenandoah disables compressed oops to avoid breaking with Valhalla"); - FLAG_SET_ERGO(UseCompressedOops, false); - } -#endif - FullGCForwarding::initialize_flags(MaxHeapSize); } diff --git a/src/hotspot/share/gc/shenandoah/shenandoahObjArrayAllocator.cpp b/src/hotspot/share/gc/shenandoah/shenandoahObjArrayAllocator.cpp index 964dada3b38..310cc75e8dd 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahObjArrayAllocator.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahObjArrayAllocator.cpp @@ -31,6 +31,7 @@ #include "memory/universe.hpp" #include "oops/arrayKlass.hpp" #include "oops/arrayOop.hpp" +#include "oops/flatArrayKlass.hpp" #include "runtime/interfaceSupport.inline.hpp" #include "utilities/copy.hpp" #include "utilities/globalDefinitions.hpp" @@ -50,7 +51,9 @@ oop ShenandoahObjArrayAllocator::initialize(HeapWord* mem) const { // Fast path: delegate to base class for small arrays or no-zero case. // In no-zero case(_do_zero is false), the content of the array won't be zeroed, therefore no need to fall into slow-path. - if (!_do_zero || _word_size <= THRESHOLD) { + // For flat arrays containing oops, we cannot fill the array efficiently. + if (!_do_zero || _word_size <= THRESHOLD || + (_klass->is_flatArray_klass() && FlatArrayKlass::cast(_klass)->contains_oops())) { return ObjArrayAllocator::initialize(mem); } @@ -72,8 +75,8 @@ oop ShenandoahObjArrayAllocator::initialize(HeapWord* mem) const { // For obj array, the header will be corrected to object array after clearing the memory. Klass* filling_klass = _klass; - // Flat arrays containing oops are not supported and only contain primitives - // from here on out. + assert(!_klass->is_flatArray_klass() || !FlatArrayKlass::cast(_klass)->contains_oops(), + "Flat arrays containing oops are not supported"); const bool is_ref_type = (element_type != T_FLAT_ELEMENT) && is_reference_type(element_type); if (is_ref_type) { diff --git a/src/hotspot/share/opto/classes.hpp b/src/hotspot/share/opto/classes.hpp index 089c9bab680..e88d4d02c6b 100644 --- a/src/hotspot/share/opto/classes.hpp +++ b/src/hotspot/share/opto/classes.hpp @@ -219,6 +219,7 @@ macro(LoadKlass) macro(LoadNKlass) macro(LoadL) macro(LoadL_unaligned) +macro(LoadLSpecial) macro(LoadP) macro(LoadN) macro(LoadRange) diff --git a/src/hotspot/share/opto/compile.cpp b/src/hotspot/share/opto/compile.cpp index 994d900c734..e65489f80c4 100644 --- a/src/hotspot/share/opto/compile.cpp +++ b/src/hotspot/share/opto/compile.cpp @@ -4257,6 +4257,7 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f case Op_LoadNKlass: case Op_LoadL: case Op_LoadL_unaligned: + case Op_LoadLSpecial: case Op_LoadP: case Op_LoadN: case Op_LoadRange: diff --git a/src/hotspot/share/opto/graphKit.cpp b/src/hotspot/share/opto/graphKit.cpp index c532adae0df..b72e8959330 100644 --- a/src/hotspot/share/opto/graphKit.cpp +++ b/src/hotspot/share/opto/graphKit.cpp @@ -1699,13 +1699,14 @@ Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, bool unaligned, bool mismatched, bool unsafe, - uint8_t barrier_data) { + uint8_t barrier_data, + bool special) { int adr_idx = C->get_alias_index(_gvn.type(adr)->isa_ptr()); assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" ); const TypePtr* adr_type = nullptr; // debug-mode-only argument DEBUG_ONLY(adr_type = C->get_adr_type(adr_idx)); Node* mem = memory(adr_idx); - Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data); + Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data, special); ld = _gvn.transform(ld); if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) { diff --git a/src/hotspot/share/opto/graphKit.hpp b/src/hotspot/share/opto/graphKit.hpp index 0776932fed9..22afafa6bb9 100644 --- a/src/hotspot/share/opto/graphKit.hpp +++ b/src/hotspot/share/opto/graphKit.hpp @@ -574,7 +574,7 @@ class GraphKit : public Phase { Node* make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, MemNode::MemOrd mo, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest, bool require_atomic_access = false, bool unaligned = false, - bool mismatched = false, bool unsafe = false, uint8_t barrier_data = 0); + bool mismatched = false, bool unsafe = false, uint8_t barrier_data = 0, bool special = false); // Create & transform a StoreNode and store the effect into the // parser's memory state. diff --git a/src/hotspot/share/opto/lcm.cpp b/src/hotspot/share/opto/lcm.cpp index c3bce2d9808..5bcde0d80cc 100644 --- a/src/hotspot/share/opto/lcm.cpp +++ b/src/hotspot/share/opto/lcm.cpp @@ -212,6 +212,7 @@ void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allo case Op_LoadRange: case Op_LoadD_unaligned: case Op_LoadL_unaligned: + case Op_LoadLSpecial: assert(mach->in(2) == val, "should be address"); break; case Op_StoreB: diff --git a/src/hotspot/share/opto/memnode.cpp b/src/hotspot/share/opto/memnode.cpp index 60e2d213e12..97e6edef84d 100644 --- a/src/hotspot/share/opto/memnode.cpp +++ b/src/hotspot/share/opto/memnode.cpp @@ -1122,7 +1122,7 @@ bool LoadNode::is_immutable_value(Node* adr) { //----------------------------LoadNode::make----------------------------------- // Polymorphic factory method: Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, BasicType bt, MemOrd mo, - ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) { + ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data, bool special) { Compile* C = gvn.C; assert(adr->is_top() || C->get_alias_index(gvn.type(adr)->as_ptr(), true) == C->get_alias_index(adr_type, true), "adr and adr_type must agree"); @@ -1138,6 +1138,8 @@ Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypeP // oop will be recorded in oop map if load crosses safepoint rt->is_oopptr() || is_immutable_value(adr), "raw memory operations should have control edge"); + assert(!special || bt == T_LONG, "Special loads are T_LONG"); + LoadNode* load = nullptr; switch (bt) { case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; @@ -1145,10 +1147,17 @@ Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypeP case T_INT: load = new LoadINode (ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; case T_CHAR: load = new LoadUSNode(ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; case T_SHORT: load = new LoadSNode (ctl, mem, adr, adr_type, rt->as_int(), mo, control_dependency); break; - case T_LONG: load = new LoadLNode (ctl, mem, adr, adr_type, rt->as_long(), mo, control_dependency, require_atomic_access); break; case T_FLOAT: load = new LoadFNode (ctl, mem, adr, adr_type, rt, mo, control_dependency); break; case T_DOUBLE: load = new LoadDNode (ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic_access); break; case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->as_ptr(), mo, control_dependency); break; + case T_LONG: { + if (special) { + load = new LoadLSpecialNode(ctl, mem, adr, adr_type, mo, control_dependency); + } else { + load = new LoadLNode (ctl, mem, adr, adr_type, rt->as_long(), mo, control_dependency, require_atomic_access); + } + break; + } case T_ARRAY: case T_OBJECT: case T_NARROWOOP: @@ -1886,8 +1895,10 @@ bool LoadNode::can_split_through_phi_base(PhaseGVN* phase) { // Split instance or boxed field load through Phi. Node* LoadNode::split_through_phi(PhaseGVN* phase, bool ignore_missing_instance_id) { if (req() > 3) { - assert(is_LoadVector() && Opcode() != Op_LoadVector, "load has too many inputs"); - // LoadVector subclasses such as LoadVectorMasked have extra inputs that the logic below doesn't take into account + assert(Opcode() == Op_LoadLSpecial || + (is_LoadVector() && Opcode() != Op_LoadVector), "load has too many inputs"); + // LoadVector subclasses such as LoadVectorMasked and LoadLSpecial + // have extra inputs that the logic below doesn't take into account return nullptr; } Node* mem = in(Memory); diff --git a/src/hotspot/share/opto/memnode.hpp b/src/hotspot/share/opto/memnode.hpp index 0fc52277c19..827117f11bc 100644 --- a/src/hotspot/share/opto/memnode.hpp +++ b/src/hotspot/share/opto/memnode.hpp @@ -298,7 +298,7 @@ class LoadNode : public MemNode { const TypePtr* at, const Type* rt, BasicType bt, MemOrd mo, ControlDependency control_dependency = DependsOnlyOnTest, bool require_atomic_access = false, bool unaligned = false, bool mismatched = false, bool unsafe = false, - uint8_t barrier_data = 0); + uint8_t barrier_data = 0, bool special = false); virtual uint hash() const; // Check the type @@ -509,6 +509,24 @@ class LoadL_unalignedNode : public LoadLNode { virtual int Opcode() const; }; +//------------------------------LoadLSpecialNode-------------------------------------- +// Special LoadL for flat loads that emits GC barriers for field in backend. +class LoadLSpecialNode : public LoadNode { +public: + LoadLSpecialNode(Node *c, Node *mem, Node *adr, const TypePtr* at, + MemOrd mo, ControlDependency control_dependency = DependsOnlyOnTest) + : LoadNode(c, mem, adr, at, TypeLong::LONG, mo, control_dependency) { + set_mismatched_access(); + } + virtual int Opcode() const; + virtual BasicType value_basic_type() const { return T_LONG; } + + virtual int store_Opcode() const { return Op_StoreLSpecial; } + + virtual uint match_edge(uint idx) const { return idx == MemNode::Address || + idx == MemNode::ValueIn; } +}; + //------------------------------LoadFNode-------------------------------------- // Load a float (64 bits) from memory class LoadFNode : public LoadNode { diff --git a/src/hotspot/share/opto/valuetypenode.cpp b/src/hotspot/share/opto/valuetypenode.cpp index 7f92bf3c575..d43d9c83d9a 100644 --- a/src/hotspot/share/opto/valuetypenode.cpp +++ b/src/hotspot/share/opto/valuetypenode.cpp @@ -2170,10 +2170,40 @@ void LoadFlatNode::expand_atomic(PhaseIterGVN& igvn) const { Node* base = this->base(); Node* ptr = this->ptr(); + int oop_off_1 = -1; + int oop_off_2 = -1; + collect_oop_offsets(_vk, oop_off_1, oop_off_2); + + assert((oop_off_1 == -1 && oop_off_2 == -1) || // No oops + (oop_off_1 == 0 && oop_off_2 == -1) || // One oop at either offset + (oop_off_1 == 4 && oop_off_2 == -1) || + (oop_off_1 == 0 && oop_off_2 == 4) || // Two oops at either offsets + (oop_off_1 == 4 && oop_off_2 == 0), + "invalid layout for %s: oop_off_1=%d, oop_off_2=%d", + _vk->name()->as_utf8(), oop_off_1, oop_off_2); + + bool has_oops = (oop_off_1 != -1); + + // Epsilon: does not care about oop loads. + // Serial/Parallel: do not care about oop loads. + // G1: does not care about oop loads. + // Shenandoah: LBE, needs special handling. + // Z: does not produce flat atomics on this shape. + assert(!has_oops || !UseZGC, "ZGC does not have special loads with oops"); + bool needs_special = has_oops && UseShenandoahGC; + BasicType payload_bt = _vk->atomic_size_to_basic_type(_null_free); + assert(!needs_special || payload_bt == T_LONG, "Unexpected payload type"); + kit.insert_mem_bar(Op_MemBarCPUOrder); - Node* payload = kit.access_load_at(base, ptr, TypeRawPtr::BOTTOM, Type::get_const_basic_type(payload_bt), payload_bt, - _decorators | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD, kit.control()); + Node* load = kit.access_load_at(base, ptr, TypeRawPtr::BOTTOM, Type::get_const_basic_type(payload_bt), payload_bt, + _decorators | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD | (needs_special ? C2_SPECIAL_ACCESS : 0), + kit.control()); + if (needs_special) { + assert(load->Opcode() == Op_LoadLSpecial, "must be special"); + Node* oop_offset_node = (oop_off_2 == -1) ? igvn.intcon(oop_off_1) : igvn.intcon(-1); + load->add_req(oop_offset_node); + } kit.insert_mem_bar(Op_MemBarCPUOrder); Node* old_ctrl = proj_out_or_null(TypeFunc::Control); @@ -2186,7 +2216,29 @@ void LoadFlatNode::expand_atomic(PhaseIterGVN& igvn) const { igvn.replace_node(old_mem, new_mem); } - expand_projs_atomic(igvn, kit.control(), payload); + expand_projs_atomic(igvn, kit.control(), load); +} + +void LoadFlatNode::collect_oop_offsets(ciValueKlass* vk, int& oop_off_1, int& oop_off_2) { + oop_off_1 = -1; + oop_off_2 = -1; + + // Iterate over the fields and find oops + for (int i = 0; i < vk->nof_nonstatic_fields(); i++) { + ciField* field = vk->nonstatic_field_at(i); + int field_offset_in_payload = field->offset_in_bytes() - vk->payload_offset(); + if (!field->type()->is_primitive_type()) { + // Narrow oop field + assert(UseCompressedOops, "Naturally atomic"); + assert(field_offset_in_payload == 0 || field_offset_in_payload == 4, "Unexpected oop offset. field_offset_in_payload=%d", field_offset_in_payload); + if (oop_off_1 == -1) { + oop_off_1 = field_offset_in_payload; + } else { + assert(oop_off_2 == -1, "already set"); + oop_off_2 = field_offset_in_payload; + } + } + } } void LoadFlatNode::collect_field_types(ciValueKlass* vk, const Type** field_types, int idx, int limit, bool null_free, bool trust_null_free_oop) { @@ -2387,38 +2439,42 @@ void StoreFlatNode::expand_atomic(PhaseIterGVN& igvn) const { Node* payload = convert_to_payload(igvn, kit.control(), value, _null_free, oop_off_1, oop_1, oop_off_2, oop_2); ciValueKlass* vk = igvn.type(value)->value_klass(); - // convert_to_payload should give us the offsets of up to 2 oops of vk in oop_off_1 and oop_off_2. The following holds: - // - they must be valid offsets for oops (0 or 4) or -1 (no oop) - // - if there is at least one oop, oop_off_1 != oop_off_2, i.e. oop_off_1 == oop_off_2 only if they are both -1, i.e. offsets are distincts - // - in case there is only one oop, its offset is stored in oop_off_1, and oop_off_2 == -1 - // - oop_off_{i} == -1 <=> oop_{i} == nullptr; - assert(oop_off_1 == -1 || oop_off_1 == 0 || oop_off_1 == 4, "invalid layout for %s, first oop at offset %d", vk->name()->as_utf8(), oop_off_1); - assert(oop_off_2 == -1 || oop_off_2 == 0 || oop_off_2 == 4, "invalid layout for %s, second oop at offset %d", vk->name()->as_utf8(), oop_off_2); - assert(oop_off_1 != oop_off_2 || oop_off_1 == -1, "we should have: oop_off_1 == oop_off_2 => oop_off_1 == -1. But oop_off_1=oop_off_2=%d", oop_off_1); - assert(oop_off_1 != -1 || oop_off_2 == -1, "we should have: oop_off_1 == -1 => oop_off_2 == -1. But oop_off_1=%d, oop_off_2=%d", oop_off_1, oop_off_2); + + assert((oop_off_1 == -1 && oop_off_2 == -1) || // No oops + (oop_off_1 == 0 && oop_off_2 == -1) || // One oop at either offset + (oop_off_1 == 4 && oop_off_2 == -1) || + (oop_off_1 == 0 && oop_off_2 == 4) || // Two oops at either offsets + (oop_off_1 == 4 && oop_off_2 == 0), + "invalid layout for %s: oop_off_1=%d, oop_off_2=%d", + vk->name()->as_utf8(), oop_off_1, oop_off_2); + assert((oop_off_1 == -1) == oop_1->is_top(), "oop_off_1 == -1 iff. oop_1 is top, but oop_off_1=%d, is oop_1 top=%d", oop_off_1, oop_1->is_top()); assert((oop_off_2 == -1) == oop_2->is_top(), "oop_off_2 == -1 iff. oop_2 is top, but oop_off_2=%d, is oop_2 top=%d", oop_off_2, oop_2->is_top()); + + bool has_oops = (oop_off_1 != -1); + + // Epsilon: does not care about oop stores. + // Serial/Parallel: handle it separately. + // G1: LBE, needs special handling. + // Shenandoah: LBE, needs special handling. + // Z: does not produce flat atomics on this shape. + assert(!has_oops || !UseZGC, "ZGC does not have special stores with oops"); + bool needs_special = has_oops && (UseG1GC || UseShenandoahGC); + BasicType payload_bt = vk->atomic_size_to_basic_type(_null_free); + assert(!needs_special || payload_bt == T_LONG, "Unexpected payload type"); + kit.insert_mem_bar(Op_MemBarCPUOrder); - if (!UseG1GC || oop_off_1 == -1) { - // No oop fields or no late barrier expansion. Emit an atomic store of the payload and add GC barriers if needed. - assert(oop_off_2 == -1 || !UseG1GC, "sanity"); - // ZGC does not support compressed oops, so only one oop can be in the payload which is written by a "normal" oop store. - assert((oop_off_1 == -1 && oop_off_2 == -1) || !UseZGC, "ZGC does not support embedded oops in flat fields"); - kit.access_store_at(base, ptr, TypeRawPtr::BOTTOM, payload, Type::get_const_basic_type(payload_bt), payload_bt, _decorators | C2_MISMATCHED, true, value); - } else { - // Contains oops and requires late barrier expansion. Emit a special store node that allows to emit GC barriers in the backend. - assert(UseG1GC, "Unexpected GC"); - assert(payload_bt == T_LONG, "Unexpected payload type"); - Node* store_special = kit.access_store_at(base, ptr, TypeRawPtr::BOTTOM, payload, TypeLong::LONG, T_LONG, _decorators | C2_MISMATCHED | C2_SPECIAL_ACCESS, true, value); - assert(store_special->Opcode() == Op_StoreLSpecial, "must be special"); - - // If one oop, set the offset (if no offset is set, two oops are assumed by the backend) - Node* oop_offset = (oop_off_2 == -1) ? igvn.intcon(oop_off_1) : igvn.C->top(); - store_special->add_req(oop_offset); + Node* store = kit.access_store_at(base, ptr, TypeRawPtr::BOTTOM, payload, Type::get_const_basic_type(payload_bt), payload_bt, + _decorators | C2_MISMATCHED | (needs_special ? C2_SPECIAL_ACCESS : 0), + true, value); + if (needs_special) { + assert(store->Opcode() == Op_StoreLSpecial, "must be special"); assert(!oop_1->is_top(), "if no oop, the store shouldn't be special"); - store_special->add_req(oop_1); - store_special->add_req(oop_2); + Node* oop_offset_node = (oop_off_2 == -1) ? igvn.intcon(oop_off_1) : igvn.C->top(); + store->add_req(oop_offset_node); + store->add_req(oop_1); + store->add_req(oop_2); } kit.insert_mem_bar(Op_MemBarCPUOrder); diff --git a/src/hotspot/share/opto/valuetypenode.hpp b/src/hotspot/share/opto/valuetypenode.hpp index 9bfabbb657f..e7af77b6ed5 100644 --- a/src/hotspot/share/opto/valuetypenode.hpp +++ b/src/hotspot/share/opto/valuetypenode.hpp @@ -213,6 +213,7 @@ class LoadFlatNode final : public SafePointNode { Compile::current()->add_flat_access(this); } + static void collect_oop_offsets(ciValueKlass* vk, int& oop_off_1, int& oop_off_2); static void collect_field_types(ciValueKlass* vk, const Type** field_types, int idx, int limit, bool null_free, bool trust_null_free_oop); ValueTypeNode* collect_projs(GraphKit* kit, ciValueKlass* vk, int proj_con, bool null_free); void expand_projs_atomic(PhaseIterGVN& gvn, Node* ctrl, Node* payload) const; From ba5855ab6465986a0ca3386e1d4422dbe37345d4 Mon Sep 17 00:00:00 2001 From: Yunbo Zhang Date: Tue, 24 Nov 2026 13:27:54 +0000 Subject: [PATCH 64/95] 8394693: ZGC: `ZMountPoint::find_preferred_mountpoint` does not respect the preferred order Reviewed-by: stefank, eosterlund --- .../os/linux/gc/z/zMountPoint_linux.cpp | 8 +- .../os/linux/gc/z/zMountPoint_linux.hpp | 4 +- .../gc/z/zPhysicalMemoryBacking_linux.cpp | 4 +- .../gtest/gc/z/test_zMountPoint_linux.cpp | 84 +++++++++++++++++++ 4 files changed, 93 insertions(+), 7 deletions(-) create mode 100644 test/hotspot/gtest/gc/z/test_zMountPoint_linux.cpp diff --git a/src/hotspot/os/linux/gc/z/zMountPoint_linux.cpp b/src/hotspot/os/linux/gc/z/zMountPoint_linux.cpp index 92c5cb713ac..2905973d77d 100644 --- a/src/hotspot/os/linux/gc/z/zMountPoint_linux.cpp +++ b/src/hotspot/os/linux/gc/z/zMountPoint_linux.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -107,9 +107,9 @@ char* ZMountPoint::find_preferred_mountpoint(const char* filesystem, ZArray* mountpoints, const char** preferred_mountpoints) const { // Find preferred mount point - ZArrayIterator iter1(mountpoints); - for (char* mountpoint; iter1.next(&mountpoint);) { - for (const char** preferred = preferred_mountpoints; *preferred != nullptr; preferred++) { + for (const char** preferred = preferred_mountpoints; *preferred != nullptr; preferred++) { + ZArrayIterator iter1(mountpoints); + for (char* mountpoint; iter1.next(&mountpoint);) { if (!strcmp(mountpoint, *preferred)) { // Preferred mount point found return os::strdup(mountpoint, mtGC); diff --git a/src/hotspot/os/linux/gc/z/zMountPoint_linux.hpp b/src/hotspot/os/linux/gc/z/zMountPoint_linux.hpp index 26c2d989fce..484e6d574ea 100644 --- a/src/hotspot/os/linux/gc/z/zMountPoint_linux.hpp +++ b/src/hotspot/os/linux/gc/z/zMountPoint_linux.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,8 @@ #include "memory/allocation.hpp" class ZMountPoint : public StackObj { + friend class ZMountPointTest; + private: char* _path; diff --git a/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp b/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp index f6b92d746f3..be131a478a7 100644 --- a/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp +++ b/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp @@ -103,14 +103,14 @@ #define ZFILENAME_HEAP "java_heap" // Preferred tmpfs mount points, ordered by priority -static const char* ZPreferredTmpfsMountpoints[] = { +const char* ZPreferredTmpfsMountpoints[] = { "/dev/shm", "/run/shm", nullptr }; // Preferred hugetlbfs mount points, ordered by priority -static const char* ZPreferredHugetlbfsMountpoints[] = { +const char* ZPreferredHugetlbfsMountpoints[] = { "/dev/hugepages", "/hugepages", nullptr diff --git a/test/hotspot/gtest/gc/z/test_zMountPoint_linux.cpp b/test/hotspot/gtest/gc/z/test_zMountPoint_linux.cpp new file mode 100644 index 00000000000..c230e415055 --- /dev/null +++ b/test/hotspot/gtest/gc/z/test_zMountPoint_linux.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#ifdef LINUX + +#include "gc/z/zArray.inline.hpp" +#include "gc/z/zMountPoint_linux.hpp" +#include "runtime/globals.hpp" +#include "runtime/os.hpp" +#include "utilities/autoRestore.hpp" +#include "unittest.hpp" + +extern const char* ZPreferredTmpfsMountpoints[]; +extern const char* ZPreferredHugetlbfsMountpoints[]; + +class ZMountPointTest { + static void check(const ZMountPoint& mountpoint, + const char* filesystem, + const char** preferred, + const char** available, + const char* expected) { + ZArray mountpoints; + for (const char** p = available; *p != nullptr; p++) { + mountpoints.append(const_cast(*p)); + } + + char* const result = mountpoint.find_preferred_mountpoint(filesystem, &mountpoints, preferred); + EXPECT_STREQ(expected, result); + os::free(result); + } + +public: + static void test(const char* filesystem, const char* first, const char* second) { + // Avoid consulting the host's mount table during construction + AutoModifyRestore path(AllocateHeapAt, "unused-for-mountpoint-test"); + const char* preferred[] = { first, second, nullptr }; + ZMountPoint mountpoint(filesystem, preferred); + + const char* forward[] = { first, second, nullptr }; + check(mountpoint, filesystem, preferred, forward, first); + + const char* reverse[] = { second, first, nullptr }; + check(mountpoint, filesystem, preferred, reverse, first); + + const char* second_only[] = { "/unrelated", second, nullptr }; + check(mountpoint, filesystem, preferred, second_only, second); + + const char* mixed[] = { "/unrelated", second, first, nullptr }; + check(mountpoint, filesystem, preferred, mixed, first); + + const char* unmatched[] = { "/unrelated", "/another", nullptr }; + check(mountpoint, filesystem, preferred, unmatched, nullptr); + } +}; + +TEST_VM(ZMountPoint, preferred_tmpfs_order) { + ZMountPointTest::test("tmpfs", ZPreferredTmpfsMountpoints[0], ZPreferredTmpfsMountpoints[1]); +} + +TEST_VM(ZMountPoint, preferred_hugetlbfs_order) { + ZMountPointTest::test("hugetlbfs", ZPreferredHugetlbfsMountpoints[0], ZPreferredHugetlbfsMountpoints[1]); +} + +#endif // LINUX From 82485577c7db9e8c1656b008f166b14be3aacbee Mon Sep 17 00:00:00 2001 From: David Carlier Date: Tue, 24 Nov 2026 13:29:00 +0000 Subject: [PATCH 65/95] 8394679: ZGC: `ZRelocateWork::update_remset_promoted` iterates invisible arrays Reviewed-by: stefank, eosterlund --- src/hotspot/share/gc/z/zRelocate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hotspot/share/gc/z/zRelocate.cpp b/src/hotspot/share/gc/z/zRelocate.cpp index 6cfcb40ccaf..fb691cc5f99 100644 --- a/src/hotspot/share/gc/z/zRelocate.cpp +++ b/src/hotspot/share/gc/z/zRelocate.cpp @@ -984,7 +984,7 @@ class ZRelocateWork : public StackObj { } void update_remset_promoted(zaddress to_addr) const { - ZIterator::basic_oop_iterate(to_oop(to_addr), update_remset_promoted_filter_and_remap_per_field); + ZIterator::basic_oop_iterate_safe(to_oop(to_addr), update_remset_promoted_filter_and_remap_per_field); } void update_remset_for_fields(zaddress from_addr, zaddress to_addr) const { From 99bec664cde9783be19ec58a8de826699a6d1001 Mon Sep 17 00:00:00 2001 From: Yunbo Zhang Date: Tue, 24 Nov 2026 13:32:40 +0000 Subject: [PATCH 66/95] 8394684: ZGC: Startup sampler-list sort can corrupt a JFR checkpoint Reviewed-by: stefank, eosterlund --- src/hotspot/share/gc/z/zStat.cpp | 7 +++++-- src/hotspot/share/gc/z/zStat.hpp | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/hotspot/share/gc/z/zStat.cpp b/src/hotspot/share/gc/z/zStat.cpp index 09818e76497..de2d4caf693 100644 --- a/src/hotspot/share/gc/z/zStat.cpp +++ b/src/hotspot/share/gc/z/zStat.cpp @@ -429,6 +429,10 @@ void ZStatIterableValue::sort() { // // Stat sampler // +void ZStatSampler::initialize() { + sort(); +} + ZStatSampler::ZStatSampler(const char* group, const char* name, ZStatUnitPrinter printer) : ZStatIterableValue(group, name, sizeof(ZStatSamplerData)), _printer(printer) {} @@ -1104,6 +1108,7 @@ ZStat::ZStat() : _metronome(SampleHz) { set_name("ZStat"); create_and_start(); + ZStatSampler::initialize(); ZStatMutatorAllocRate::initialize(); } @@ -1155,8 +1160,6 @@ void ZStat::run_thread() { ZStatSamplerHistory* const history = new ZStatSamplerHistory[ZStatSampler::count()]; LogTarget(Debug, gc, stats) log; - ZStatSampler::sort(); - // Main loop while (_metronome.wait_for_tick()) { sample_and_collect(history); diff --git a/src/hotspot/share/gc/z/zStat.hpp b/src/hotspot/share/gc/z/zStat.hpp index 42477424b64..1204378eadd 100644 --- a/src/hotspot/share/gc/z/zStat.hpp +++ b/src/hotspot/share/gc/z/zStat.hpp @@ -132,6 +132,8 @@ class ZStatSampler : public ZStatIterableValue { const ZStatUnitPrinter _printer; public: + static void initialize(); + ZStatSampler(const char* group, const char* name, ZStatUnitPrinter printer); From 98dd001c88c669d21c040b4f959c43b1350ec95f Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Tue, 24 Nov 2026 14:22:12 +0000 Subject: [PATCH 67/95] 8397903: Java_apple_security_KeychainStore__1addItemToKeychain add CFRelease to early errOut jumps Reviewed-by: weijun, clanger --- .../native/libosxsecurity/KeystoreImpl.m | 39 ++++++++++--------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m index 59cf725c49f..03a408890d5 100644 --- a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m +++ b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m @@ -762,26 +762,11 @@ static void addCertificatesToKeystoreRoot(JNIEnv *env, jobject keyStore, NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; \ @try { - jsize dataSize = (*env)->GetArrayLength(env, rawDataObj); - jbyte *rawData = (*env)->GetByteArrayElements(env, rawDataObj, NULL); - if (rawData == NULL) { - goto errOut; - } - - CFDataRef cfDataToImport = CFDataCreate(kCFAllocatorDefault, (UInt8 *)rawData, dataSize); - CFArrayRef createdItems = NULL; - - SecKeychainRef defaultKeychain = NULL; - SecKeychainCopyDefault(&defaultKeychain); - - SecExternalFormat dataFormat = (isCertificate == JNI_TRUE ? kSecFormatX509Cert : kSecFormatWrappedPKCS8); - // Convert the password obj into a CFStringRef that the keychain importer can use for encryption. - SecKeyImportExportParameters paramBlock; CFStringRef passwordStrRef = NULL; - jsize passwordLen = 0; jchar *passwordChars = NULL; + jbyte *rawData = NULL; if (passwordObj) { passwordLen = (*env)->GetArrayLength(env, passwordObj); @@ -799,6 +784,24 @@ static void addCertificatesToKeystoreRoot(JNIEnv *env, jobject keyStore, } } + jsize dataSize = (*env)->GetArrayLength(env, rawDataObj); + rawData = (*env)->GetByteArrayElements(env, rawDataObj, NULL); + if (rawData == NULL) { + goto errOut; + } + + CFDataRef cfDataToImport = CFDataCreate(kCFAllocatorDefault, (UInt8 *)rawData, dataSize); + CFArrayRef createdItems = NULL; + if (cfDataToImport == NULL) { + goto errOut; + } + + SecKeychainRef defaultKeychain = NULL; + SecKeychainCopyDefault(&defaultKeychain); + + SecExternalFormat dataFormat = (isCertificate == JNI_TRUE ? kSecFormatX509Cert : kSecFormatWrappedPKCS8); + SecKeyImportExportParameters paramBlock; + paramBlock.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; // Note that setting the flags field **requires** you to pass in a password of some kind. The keychain will not prompt you. paramBlock.flags = 0; @@ -811,9 +814,7 @@ static void addCertificatesToKeystoreRoot(JNIEnv *env, jobject keyStore, err = SecKeychainItemImport(cfDataToImport, NULL, &dataFormat, NULL, 0, ¶mBlock, defaultKeychain, &createdItems); - if (cfDataToImport != NULL) { - CFRelease(cfDataToImport); - } + CFRelease(cfDataToImport); if (err == noErr) { SecKeychainItemRef anItem = (SecKeychainItemRef)CFArrayGetValueAtIndex(createdItems, 0); From e107e4ebbd6b9d2217261172a9b1af19654c8ddb Mon Sep 17 00:00:00 2001 From: Jorn Vernee Date: Tue, 24 Nov 2026 16:53:09 +0000 Subject: [PATCH 68/95] 8336664: Add sign information to value layouts Reviewed-by: mdoerr, amitkumar --- .../classes/java/lang/foreign/Linker.java | 18 ++- .../java/lang/foreign/MemoryLayout.java | 6 +- .../java/lang/foreign/ValueLayout.java | 133 +++++++++++++++--- .../internal/foreign/abi/AbstractLinker.java | 56 +++++--- .../jdk/internal/foreign/abi/Binding.java | 76 ++++++++-- .../foreign/abi/BindingSpecializer.java | 22 ++- .../jdk/internal/foreign/abi/SharedUtils.java | 20 ++- .../foreign/abi/aarch64/CallArranger.java | 5 +- .../abi/aarch64/linux/LinuxAArch64Linker.java | 5 +- .../abi/aarch64/macos/MacOsAArch64Linker.java | 12 +- .../aarch64/windows/WindowsAArch64Linker.java | 5 +- .../foreign/abi/fallback/FFIType.java | 91 ++++++------ .../foreign/abi/fallback/FallbackLinker.java | 63 ++++++--- .../foreign/abi/fallback/LibFallback.java | 13 ++ .../foreign/abi/ppc64/CallArranger.java | 15 +- .../foreign/abi/ppc64/aix/AixPPC64Linker.java | 12 +- .../abi/ppc64/linux/LinuxPPC64Linker.java | 12 +- .../abi/ppc64/linux/LinuxPPC64leLinker.java | 12 +- .../linux/LinuxRISCV64CallArranger.java | 19 +-- .../abi/riscv64/linux/LinuxRISCV64Linker.java | 12 +- .../abi/s390/linux/LinuxS390CallArranger.java | 27 ++-- .../abi/s390/linux/LinuxS390Linker.java | 12 +- .../foreign/abi/x64/sysv/CallArranger.java | 6 +- .../foreign/abi/x64/sysv/SysVx64Linker.java | 12 +- .../abi/x64/windows/Windowsx64Linker.java | 5 +- .../internal/foreign/layout/ValueLayouts.java | 112 +++++++++++---- .../native/libfallbackLinker/fallbackLinker.c | 17 +++ test/jdk/TEST.groups | 1 + .../MemoryLayoutTypeRetentionTest.java | 17 ++- test/jdk/java/foreign/NativeTestHelper.java | 9 +- test/jdk/java/foreign/TestIllegalLink.java | 3 +- test/jdk/java/foreign/TestNulls.java | 1 + .../callarranger/TestLayoutEquality.java | 3 + .../TestCanonicalLayouts.java | 125 ++++++++++++++++ .../canonicallayouts/libCanonicalLayouts.c | 83 +++++++++++ .../foreign/normalize/TestZeroExtendInt.java | 90 ++++++++++++ .../foreign/normalize/TestZeroExtendLong.java | 95 +++++++++++++ .../invoke/VarHandles/VarHandleTestExact.java | 29 ++-- 38 files changed, 1031 insertions(+), 223 deletions(-) create mode 100644 test/jdk/java/foreign/canonicallayouts/TestCanonicalLayouts.java create mode 100644 test/jdk/java/foreign/canonicallayouts/libCanonicalLayouts.c create mode 100644 test/jdk/java/foreign/normalize/TestZeroExtendInt.java create mode 100644 test/jdk/java/foreign/normalize/TestZeroExtendLong.java diff --git a/src/java.base/share/classes/java/lang/foreign/Linker.java b/src/java.base/share/classes/java/lang/foreign/Linker.java index 30a7c24560a..4dd870a9530 100644 --- a/src/java.base/share/classes/java/lang/foreign/Linker.java +++ b/src/java.base/share/classes/java/lang/foreign/Linker.java @@ -138,15 +138,28 @@ *

    *
  • {@code bool}
  • *
  • {@code char}
  • + *
  • {@code unsigned char}
  • *
  • {@code short}
  • + *
  • {@code unsigned short}
  • *
  • {@code int}
  • + *
  • {@code unsigned int}
  • *
  • {@code long}
  • + *
  • {@code unsigned long}
  • *
  • {@code long long}
  • + *
  • {@code unsigned long long}
  • *
  • {@code float}
  • *
  • {@code double}
  • *
  • {@code size_t}
  • *
  • {@code wchar_t}
  • *
  • {@code void*}
  • + *
  • {@code int8_t}
  • + *
  • {@code int16_t}
  • + *
  • {@code int32_t}
  • + *
  • {@code int64_t}
  • + *
  • {@code uint8_t}
  • + *
  • {@code uint16_t}
  • + *
  • {@code uint32_t}
  • + *
  • {@code uint64_t}
  • *
* As noted above, the specific canonical layout associated with each type can vary, * depending on the data model supported by a given ABI. For instance, the canonical @@ -156,11 +169,6 @@ * {@link ValueLayout.OfLong} on 64-bit platforms, and a {@link ValueLayout.OfInt} * on 32-bit platforms. *

- * A native linker typically does not provide canonical layouts for C's unsigned integral - * types. Instead, they are modeled using the canonical layouts associated with their - * corresponding signed integral types. For instance, the C type {@code unsigned long} - * maps to the canonical layout for {@code long}. - *

* The following table shows some examples of how C types are modeled in Linux/x64 * according to the "System V Application Binary Interface" * (all the examples provided here will assume these platform-dependent mappings): diff --git a/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java b/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java index f55deba6e7f..745b7d6dc73 100644 --- a/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java +++ b/src/java.base/share/classes/java/lang/foreign/MemoryLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -994,7 +994,9 @@ static PathElement dereferenceElement() { * {@linkplain ValueLayout#order() order}, and * {@linkplain ValueLayout#carrier() carrier}. Additionally, two address * layouts are considered equal if they also have the same - * {@linkplain AddressLayout#targetLayout() target layout}; + * {@linkplain AddressLayout#targetLayout() target layout}. Additionally, + * two integral layouts are consider equal if they also have the same + * {@linkplain ValueLayout.OfIntegral#isSigned() signedness}; *

  • two sequence layouts are considered equal if they have the same element * count (see {@link SequenceLayout#elementCount()}), and if their element * layouts (see {@link SequenceLayout#elementLayout()}) are also equal;
  • diff --git a/src/java.base/share/classes/java/lang/foreign/ValueLayout.java b/src/java.base/share/classes/java/lang/foreign/ValueLayout.java index d81a624e598..ca69ec5bd81 100644 --- a/src/java.base/share/classes/java/lang/foreign/ValueLayout.java +++ b/src/java.base/share/classes/java/lang/foreign/ValueLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,9 +56,8 @@ * @since 22 */ public sealed interface ValueLayout extends MemoryLayout - permits ValueLayout.OfBoolean, ValueLayout.OfByte, ValueLayout.OfChar, - ValueLayout.OfShort, ValueLayout.OfInt, ValueLayout.OfFloat, - ValueLayout.OfLong, ValueLayout.OfDouble, AddressLayout { + permits ValueLayout.OfBoolean, ValueLayout.OfIntegral, ValueLayout.OfChar, + ValueLayout.OfFloat, ValueLayout.OfDouble, AddressLayout { /** * {@return the value's byte order} @@ -123,13 +122,75 @@ public sealed interface ValueLayout extends MemoryLayout */ VarHandle varHandle(); + /** + * An integral value layout models an integral data type. + *

    + * Integral value layouts have a signedness. That is, they can + * be either signed or unsigned to reflect the + * signedness of the values they are associated with. The + * signedness of an integral value layout has no effect on the + * memory access operations involving that integral layout. + * However, signedness is relevant when values associated with + * integral layouts are widened. For example, when an {@code int} + * is widened to a {@code long}, the signedness determines whether + * the value should be sign extended as specified by {@jls 5.1.2}, + * or zero extended as specified by the {@link Integer#toUnsignedLong(int)} + * method. As such, the signedness of an integral value layout + * allows clients to select the correct widening mode for values + * associated with that layout. + * + * @sealedGraph + * @since 28 + */ + sealed interface OfIntegral extends ValueLayout permits ValueLayout.OfByte, + ValueLayout.OfShort, ValueLayout.OfInt, ValueLayout.OfLong { + /** + * {@return {@code true} if the value represented by this layout is signed} + */ + boolean isSigned(); + + /** + * {@return an integral value layout with the same characteristics as this layout, + * but with the given signedness} + * + * @param signed {@code true} for a signed layout, {@code false} for an unsigned layouts. + */ + OfIntegral withSignedness(boolean signed); + + /** + * {@inheritDoc} + */ + @Override + OfIntegral withName(String name); + + /** + * {@inheritDoc} + */ + @Override + OfIntegral withoutName(); + + /** + * {@inheritDoc} + * @throws IllegalArgumentException {@inheritDoc} + */ + @Override + OfIntegral withByteAlignment(long byteAlignment); + + /** + * {@inheritDoc} + */ + @Override + OfIntegral withOrder(ByteOrder order); + + } + /** * A value layout whose carrier is {@code boolean.class}. * * @see #JAVA_BOOLEAN * @since 22 */ - sealed interface OfBoolean extends ValueLayout permits ValueLayouts.OfBooleanImpl { + sealed interface OfBoolean extends ValueLayout permits ValueLayouts.OfBooleanImpl { /** * {@inheritDoc} @@ -164,7 +225,7 @@ sealed interface OfBoolean extends ValueLayout permits ValueLayouts.OfBooleanImp * @see #JAVA_BYTE * @since 22 */ - sealed interface OfByte extends ValueLayout permits ValueLayouts.OfByteImpl { + sealed interface OfByte extends OfIntegral permits ValueLayouts.OfByteImpl { /** * {@inheritDoc} @@ -191,6 +252,13 @@ sealed interface OfByte extends ValueLayout permits ValueLayouts.OfByteImpl { @Override OfByte withOrder(ByteOrder order); + /** + * {@inheritDoc} + * @since 28 + */ + @Override + OfByte withSignedness(boolean signed); + } /** @@ -200,7 +268,7 @@ sealed interface OfByte extends ValueLayout permits ValueLayouts.OfByteImpl { * @see #JAVA_CHAR_UNALIGNED * @since 22 */ - sealed interface OfChar extends ValueLayout permits ValueLayouts.OfCharImpl { + sealed interface OfChar extends ValueLayout permits ValueLayouts.OfCharImpl { /** * {@inheritDoc} @@ -236,7 +304,7 @@ sealed interface OfChar extends ValueLayout permits ValueLayouts.OfCharImpl { * @see #JAVA_SHORT_UNALIGNED * @since 22 */ - sealed interface OfShort extends ValueLayout permits ValueLayouts.OfShortImpl { + sealed interface OfShort extends OfIntegral permits ValueLayouts.OfShortImpl { /** * {@inheritDoc} @@ -263,6 +331,13 @@ sealed interface OfShort extends ValueLayout permits ValueLayouts.OfShortImpl { @Override OfShort withOrder(ByteOrder order); + /** + * {@inheritDoc} + * @since 28 + */ + @Override + OfShort withSignedness(boolean signed); + } /** @@ -272,7 +347,7 @@ sealed interface OfShort extends ValueLayout permits ValueLayouts.OfShortImpl { * @see #JAVA_INT_UNALIGNED * @since 22 */ - sealed interface OfInt extends ValueLayout permits ValueLayouts.OfIntImpl { + sealed interface OfInt extends OfIntegral permits ValueLayouts.OfIntImpl { /** * {@inheritDoc} @@ -299,6 +374,13 @@ sealed interface OfInt extends ValueLayout permits ValueLayouts.OfIntImpl { @Override OfInt withOrder(ByteOrder order); + /** + * {@inheritDoc} + * @since 28 + */ + @Override + OfInt withSignedness(boolean signed); + } /** @@ -308,7 +390,7 @@ sealed interface OfInt extends ValueLayout permits ValueLayouts.OfIntImpl { * @see #JAVA_FLOAT_UNALIGNED * @since 22 */ - sealed interface OfFloat extends ValueLayout permits ValueLayouts.OfFloatImpl { + sealed interface OfFloat extends ValueLayout permits ValueLayouts.OfFloatImpl { /** * {@inheritDoc} @@ -343,7 +425,7 @@ sealed interface OfFloat extends ValueLayout permits ValueLayouts.OfFloatImpl { * @see #JAVA_LONG_UNALIGNED * @since 22 */ - sealed interface OfLong extends ValueLayout permits ValueLayouts.OfLongImpl { + sealed interface OfLong extends OfIntegral permits ValueLayouts.OfLongImpl { /** * {@inheritDoc} @@ -370,6 +452,13 @@ sealed interface OfLong extends ValueLayout permits ValueLayouts.OfLongImpl { @Override OfLong withOrder(ByteOrder order); + /** + * {@inheritDoc} + * @since 28 + */ + @Override + OfLong withSignedness(boolean signed); + } /** @@ -379,7 +468,7 @@ sealed interface OfLong extends ValueLayout permits ValueLayouts.OfLongImpl { * @see #JAVA_DOUBLE_UNALIGNED * @since 22 */ - sealed interface OfDouble extends ValueLayout permits ValueLayouts.OfDoubleImpl { + sealed interface OfDouble extends ValueLayout permits ValueLayouts.OfDoubleImpl { /** * {@inheritDoc} @@ -416,8 +505,9 @@ sealed interface OfDouble extends ValueLayout permits ValueLayouts.OfDoubleImpl AddressLayout ADDRESS = ValueLayouts.OfAddressImpl.of(ByteOrder.nativeOrder()); /** - * A value layout constant whose size is the same as that of a Java {@code byte}, - * byte alignment set to 1, and byte order set to {@link ByteOrder#nativeOrder()}. + * An integral value layout constant whose size is the same as that of a Java {@code byte}, + * byte alignment set to 1, byte order set to {@link ByteOrder#nativeOrder()}, + * and signedness set to {@code true}. */ OfByte JAVA_BYTE = ValueLayouts.OfByteImpl.of(ByteOrder.nativeOrder()); @@ -434,20 +524,23 @@ sealed interface OfDouble extends ValueLayout permits ValueLayouts.OfDoubleImpl OfChar JAVA_CHAR = ValueLayouts.OfCharImpl.of(ByteOrder.nativeOrder()); /** - * A value layout constant whose size is the same as that of a Java {@code short}, - * byte alignment set to 2, and byte order set to {@link ByteOrder#nativeOrder()}. + * An integral value layout constant whose size is the same as that of a Java {@code short}, + * byte alignment set to 2, byte order set to {@link ByteOrder#nativeOrder()}, + * and signedness set to {@code true}. */ OfShort JAVA_SHORT = ValueLayouts.OfShortImpl.of(ByteOrder.nativeOrder()); /** - * A value layout constant whose size is the same as that of a Java {@code int}, - * byte alignment set to 4, and byte order set to {@link ByteOrder#nativeOrder()}. + * An integral value layout constant whose size is the same as that of a Java {@code int}, + * byte alignment set to 4, byte order set to {@link ByteOrder#nativeOrder()}, + * and signedness set to {@code true}. */ OfInt JAVA_INT = ValueLayouts.OfIntImpl.of(ByteOrder.nativeOrder()); /** - * A value layout constant whose size is the same as that of a Java {@code long}, - * byte alignment set to 8, and byte order set to {@link ByteOrder#nativeOrder()}. + * An integral value layout constant whose size is the same as that of a Java {@code long}, + * byte alignment set to 8, and byte order set to {@link ByteOrder#nativeOrder()}, + * and signedness set to {@code true}. */ OfLong JAVA_LONG = ValueLayouts.OfLongImpl.of(ByteOrder.nativeOrder()); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/AbstractLinker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/AbstractLinker.java index 401d3e9a9c5..52e4c01220b 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/AbstractLinker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/AbstractLinker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,10 +55,7 @@ import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; +import java.util.*; public abstract sealed class AbstractLinker implements Linker permits LinuxAArch64Linker, MacOsAArch64Linker, SysVx64Linker, WindowsAArch64Linker, @@ -67,6 +64,11 @@ public abstract sealed class AbstractLinker implements Linker permits LinuxAArch LinuxRISCV64Linker, LinuxS390Linker, FallbackLinker { + public static final ValueLayout.OfByte UBYTE = ValueLayout.JAVA_BYTE.withSignedness(false); + public static final ValueLayout.OfShort USHORT = ValueLayout.JAVA_SHORT.withSignedness(false); + public static final ValueLayout.OfInt UINT = ValueLayout.JAVA_INT.withSignedness(false); + public static final ValueLayout.OfLong ULONG = ValueLayout.JAVA_LONG.withSignedness(false); + public interface UpcallStubFactory { MemorySegment makeStub(MethodHandle target, Arena arena); } @@ -108,7 +110,7 @@ private MethodHandle downcallHandle0(FunctionDescriptor function, Option... opti Objects.requireNonNull(function); Objects.requireNonNull(options); checkLayouts(function); - function = stripNames(function); + function = stripLayout(function); LinkerOptions optionSet = LinkerOptions.forDowncall(function, options); validateVariadicLayouts(function, optionSet); @@ -133,7 +135,7 @@ public final MemorySegment upcallStub(MethodHandle target, FunctionDescriptor fu Objects.requireNonNull(function); checkLayouts(function); SharedUtils.checkExceptions(target); - function = stripNames(function); + function = stripLayout(function); LinkerOptions optionSet = LinkerOptions.forUpcall(function, options); MethodType type = function.toMethodType(); @@ -164,11 +166,9 @@ private void validateVariadicLayouts(FunctionDescriptor function, LinkerOptions List variadicLayouts = argumentLayouts.subList(optionSet.firstVariadicArgIndex(), argumentLayouts.size()); for (MemoryLayout variadicLayout : variadicLayouts) { - if (variadicLayout.equals(ValueLayout.JAVA_BOOLEAN) - || variadicLayout.equals(ValueLayout.JAVA_BYTE) - || variadicLayout.equals(ValueLayout.JAVA_CHAR) - || variadicLayout.equals(ValueLayout.JAVA_SHORT) - || variadicLayout.equals(ValueLayout.JAVA_FLOAT)) { + if (variadicLayout instanceof ValueLayout valueLayout && + (valueLayout.carrier().equals(float.class) || + valueLayout.byteSize() < canonicalLayouts().get("int").byteSize())) { throw new IllegalArgumentException("Invalid variadic argument layout: " + variadicLayout); } } @@ -313,38 +313,48 @@ private void checkHasNaturalAlignment(MemoryLayout layout) { } } + // overridden by sub classes + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout instanceof ValueLayout.OfIntegral integral + ? integral.withSignedness(true) + : valueLayout; + } + + // Strip info from the layout that's not needed by the linker, such as name. + // This helps to improve caching efficiency. @SuppressWarnings("restricted") - private static MemoryLayout stripNames(MemoryLayout ml) { + private MemoryLayout stripLayout(MemoryLayout ml) { // we don't care about transferring alignment and byte order here // since the linker already restricts those such that they will always be the same return switch (ml) { - case StructLayout sl -> MemoryLayout.structLayout(stripNames(sl.memberLayouts())); - case UnionLayout ul -> MemoryLayout.unionLayout(stripNames(ul.memberLayouts())); - case SequenceLayout sl -> MemoryLayout.sequenceLayout(sl.elementCount(), stripNames(sl.elementLayout())); + case StructLayout sl -> MemoryLayout.structLayout(stripLayout(sl.memberLayouts())); + case UnionLayout ul -> MemoryLayout.unionLayout(stripLayout(ul.memberLayouts())); + case SequenceLayout sl -> MemoryLayout.sequenceLayout(sl.elementCount(), stripLayout(sl.elementLayout())); case AddressLayout al -> { var stripped = al.withoutName(); var target = al.targetLayout(); if (target.isPresent()) - stripped = stripped.withTargetLayout(stripNames(target.get())); + stripped = stripped.withTargetLayout(stripLayout(target.get())); yield stripped; } - default -> ml.withoutName(); // ValueLayout and PaddingLayout + case ValueLayout vl -> maybeEraseSign(vl.withoutName()); + default -> ml.withoutName(); // PaddingLayout }; } - private static MemoryLayout[] stripNames(List layouts) { + private MemoryLayout[] stripLayout(List layouts) { var ret = new MemoryLayout[layouts.size()]; for (int i = 0; i < ret.length; i++) { - ret[i] = stripNames(layouts.get(i)); + ret[i] = stripLayout(layouts.get(i)); } return ret; } - private static FunctionDescriptor stripNames(FunctionDescriptor function) { + private FunctionDescriptor stripLayout(FunctionDescriptor function) { var retLayout = function.returnLayout(); if (retLayout.isEmpty()) { - return FunctionDescriptor.ofVoid(stripNames(function.argumentLayouts())); + return FunctionDescriptor.ofVoid(stripLayout(function.argumentLayouts())); } - return FunctionDescriptor.of(stripNames(retLayout.get()), stripNames(function.argumentLayouts())); + return FunctionDescriptor.of(stripLayout(retLayout.get()), stripLayout(function.argumentLayouts())); } } diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/Binding.java b/src/java.base/share/classes/jdk/internal/foreign/abi/Binding.java index 3e81a451522..12db4d95866 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/Binding.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/Binding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,10 +29,7 @@ import jdk.internal.foreign.abi.BindingInterpreter.LoadFunc; import jdk.internal.foreign.abi.BindingInterpreter.StoreFunc; -import java.lang.foreign.Arena; -import java.lang.foreign.MemoryLayout; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SegmentAllocator; +import java.lang.foreign.*; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; @@ -303,6 +300,10 @@ static ShiftRight shiftRight(int shiftAmount) { } static Binding cast(Class fromType, Class toType) { + return cast(fromType, toType, true); + } + + static Binding cast(Class fromType, Class toType, boolean isSigned) { if (fromType == int.class) { if (toType == boolean.class) { return Cast.INT_TO_BOOLEAN; @@ -313,15 +314,15 @@ static Binding cast(Class fromType, Class toType) { } else if (toType == char.class) { return Cast.INT_TO_CHAR; } else if (toType == long.class) { - return Cast.INT_TO_LONG; + return isSigned ? Cast.INT_TO_LONG : Cast.UINT_TO_LONG; } } else if (toType == int.class) { if (fromType == boolean.class) { return Cast.BOOLEAN_TO_INT; } else if (fromType == byte.class) { - return Cast.BYTE_TO_INT; + return isSigned ? Cast.BYTE_TO_INT : Cast.UBYTE_TO_INT; } else if (fromType == short.class) { - return Cast.SHORT_TO_INT; + return isSigned ? Cast.SHORT_TO_INT : Cast.USHORT_TO_INT; } else if (fromType == char.class) { return Cast.CHAR_TO_INT; } else if (fromType == long.class) { @@ -337,9 +338,9 @@ static Binding cast(Class fromType, Class toType) { } } else if (toType == long.class) { if (fromType == byte.class) { - return Cast.BYTE_TO_LONG; + return isSigned ? Cast.BYTE_TO_LONG : Cast.UBYTE_TO_LONG; } else if (fromType == short.class) { - return Cast.SHORT_TO_LONG; + return isSigned ? Cast.SHORT_TO_LONG : Cast.USHORT_TO_LONG; } else if (fromType == char.class) { return Cast.CHAR_TO_LONG; } @@ -363,8 +364,12 @@ private static boolean isSubIntType(Class type) { } public Binding.Builder vmStore(VMStorage storage, Class type) { + return vmStore(storage, type, true); + } + + public Binding.Builder vmStore(VMStorage storage, Class type, boolean isSigned) { if (isSubIntType(type)) { - bindings.add(Binding.cast(type, int.class)); + bindings.add(Binding.cast(type, int.class, isSigned)); type = int.class; } bindings.add(Binding.vmStore(storage, type)); @@ -383,6 +388,15 @@ public Binding.Builder vmLoad(VMStorage storage, Class type) { return this; } + public Binding.Builder cast(Class fromType, Class toType) { + return cast(fromType, toType, true); + } + + public Binding.Builder cast(Class fromType, Class toType, boolean isSigned) { + bindings.add(Binding.cast(fromType, toType, isSigned)); + return this; + } + public Binding.Builder bufferStore(long offset, Class type) { bindings.add(Binding.bufferStore(offset, type)); return this; @@ -848,11 +862,14 @@ public void interpret(Deque stack, StoreFunc storeFunc, INT_TO_CHAR(int.class, char.class), INT_TO_SHORT(int.class, short.class), INT_TO_LONG(int.class, long.class), + UINT_TO_LONG(int.class, long.class), BOOLEAN_TO_INT(boolean.class, int.class), BYTE_TO_INT(byte.class, int.class), + UBYTE_TO_INT(byte.class, int.class), CHAR_TO_INT(char.class, int.class), SHORT_TO_INT(short.class, int.class), + USHORT_TO_INT(short.class, int.class), LONG_TO_INT(long.class, int.class), LONG_TO_BYTE(long.class, byte.class), @@ -860,7 +877,9 @@ public void interpret(Deque stack, StoreFunc storeFunc, LONG_TO_CHAR(long.class, char.class), BYTE_TO_LONG(byte.class, long.class), + UBYTE_TO_LONG(byte.class, long.class), SHORT_TO_LONG(short.class, long.class), + USHORT_TO_LONG(short.class, long.class), CHAR_TO_LONG(char.class, long.class); private final Class fromType; @@ -886,12 +905,43 @@ public void verify(Deque> stack) { stack.push(toType); } + private static final MethodHandle BYTE_TO_INT_UNSIGNED; + private static final MethodHandle BYTE_TO_LONG_UNSIGNED; + private static final MethodHandle SHORT_TO_INT_UNSIGNED; + private static final MethodHandle SHORT_TO_LONG_UNSIGNED; + private static final MethodHandle INT_TO_LONG_UNSIGNED; + + static { + MethodHandles.Lookup lookup = MethodHandles.publicLookup(); + try { + BYTE_TO_INT_UNSIGNED = lookup.findStatic(Byte.class, "toUnsignedInt", + MethodType.methodType(int.class, byte.class)); + SHORT_TO_INT_UNSIGNED = lookup.findStatic(Short.class, "toUnsignedInt", + MethodType.methodType(int.class, short.class)); + BYTE_TO_LONG_UNSIGNED = lookup.findStatic(Byte.class, "toUnsignedLong", + MethodType.methodType(long.class, byte.class)); + SHORT_TO_LONG_UNSIGNED = lookup.findStatic(Short.class, "toUnsignedLong", + MethodType.methodType(long.class, short.class)); + INT_TO_LONG_UNSIGNED = lookup.findStatic(Integer.class, "toUnsignedLong", + MethodType.methodType(long.class, int.class)); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + @Override public void interpret(Deque stack, StoreFunc storeFunc, LoadFunc loadFunc, SegmentAllocator allocator) { Object arg = stack.pop(); - MethodHandle converter = MethodHandles.explicitCastArguments(MethodHandles.identity(toType), - MethodType.methodType(toType, fromType)); + MethodHandle converter = switch (this) { + case UBYTE_TO_INT -> BYTE_TO_INT_UNSIGNED; + case USHORT_TO_INT -> SHORT_TO_INT_UNSIGNED; + case UBYTE_TO_LONG -> BYTE_TO_LONG_UNSIGNED; + case USHORT_TO_LONG -> SHORT_TO_LONG_UNSIGNED; + case UINT_TO_LONG -> INT_TO_LONG_UNSIGNED; + default -> MethodHandles.explicitCastArguments(MethodHandles.identity(toType), + MethodType.methodType(toType, fromType)); + }; try { Object result = converter.invoke(arg); stack.push(result); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/BindingSpecializer.java b/src/java.base/share/classes/jdk/internal/foreign/abi/BindingSpecializer.java index 20ccec61fd2..2645b882528 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/BindingSpecializer.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/BindingSpecializer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -782,13 +782,31 @@ private void emitCast(Cast cast) { .invokestatic(CD_Utils, "byteToBoolean", MTD_BYTE_TO_BOOLEAN); } case INT_TO_BYTE -> cb.i2b(); - case INT_TO_CHAR -> cb.i2c(); + case INT_TO_CHAR, USHORT_TO_INT -> cb.i2c(); case INT_TO_SHORT -> cb.i2s(); + case UINT_TO_LONG -> { + cb.i2l(); + cb.loadConstant(0xFFFFFFFFL); + cb.land(); + } case BYTE_TO_LONG, CHAR_TO_LONG, SHORT_TO_LONG, INT_TO_LONG -> cb.i2l(); + case UBYTE_TO_LONG -> { + cb.loadConstant(0xFF); + cb.iand(); + cb.i2l(); + } + case USHORT_TO_LONG -> { + cb.i2c(); + cb.i2l(); + } case LONG_TO_BYTE -> { cb.l2i(); cb.i2b(); } case LONG_TO_SHORT -> { cb.l2i(); cb.i2s(); } case LONG_TO_CHAR -> { cb.l2i(); cb.i2c(); } case LONG_TO_INT -> cb.l2i(); + case UBYTE_TO_INT -> { + cb.loadConstant(0xFF); + cb.iand(); + } case BOOLEAN_TO_INT, BYTE_TO_INT, CHAR_TO_INT, SHORT_TO_INT -> { // no-op in bytecode } diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/SharedUtils.java b/src/java.base/share/classes/jdk/internal/foreign/abi/SharedUtils.java index 5e4d667b4f6..02dc90f0001 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/SharedUtils.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/SharedUtils.java @@ -390,6 +390,10 @@ static long pickChunkOffset(long chunkOffset, long byteWidth, int chunkWidth) { : chunkOffset; } + public static boolean isSigned(MemoryLayout layout) { + return layout instanceof OfIntegral integral && integral.isSigned(); + } + @ForceInline static Arena newBoundedArena(long size) { return BoundedArena.of(size); @@ -501,11 +505,12 @@ static Object read(MemorySegment ptr, long offset, Class type) { } } - public static Map canonicalLayouts(ValueLayout longLayout, ValueLayout sizetLayout, ValueLayout wchartLayout) { + public static Map canonicalLayouts(ValueLayout.OfIntegral longLayout, ValueLayout sizetLayout, + ValueLayout charLayout, ValueLayout wchartLayout) { return Map.ofEntries( // specified canonical layouts Map.entry("bool", ValueLayout.JAVA_BOOLEAN), - Map.entry("char", ValueLayout.JAVA_BYTE), + Map.entry("char", charLayout), Map.entry("short", ValueLayout.JAVA_SHORT), Map.entry("int", ValueLayout.JAVA_INT), Map.entry("float", ValueLayout.JAVA_FLOAT), @@ -515,11 +520,20 @@ public static Map canonicalLayouts(ValueLayout longLayout, Map.entry("void*", ValueLayout.ADDRESS), Map.entry("size_t", sizetLayout), Map.entry("wchar_t", wchartLayout), - // unspecified size-dependent layouts + Map.entry("unsigned char", ValueLayout.JAVA_BYTE.withSignedness(false)), + Map.entry("unsigned short", ValueLayout.JAVA_SHORT.withSignedness(false)), + Map.entry("unsigned int", ValueLayout.JAVA_INT.withSignedness(false)), + Map.entry("unsigned long", longLayout.withSignedness(false)), + Map.entry("unsigned long long", ValueLayout.JAVA_LONG.withSignedness(false)), + // size/sign-dependent layouts Map.entry("int8_t", ValueLayout.JAVA_BYTE), Map.entry("int16_t", ValueLayout.JAVA_SHORT), Map.entry("int32_t", ValueLayout.JAVA_INT), Map.entry("int64_t", ValueLayout.JAVA_LONG), + Map.entry("uint8_t", ValueLayout.JAVA_BYTE.withSignedness(false)), + Map.entry("uint16_t", ValueLayout.JAVA_SHORT.withSignedness(false)), + Map.entry("uint32_t", ValueLayout.JAVA_INT.withSignedness(false)), + Map.entry("uint64_t", ValueLayout.JAVA_LONG.withSignedness(false)), // unspecified JNI layouts Map.entry("jboolean", ValueLayout.JAVA_BOOLEAN), Map.entry("jchar", ValueLayout.JAVA_CHAR), diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/CallArranger.java b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/CallArranger.java index 2ad5ffa902e..5221233bc9e 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/CallArranger.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/CallArranger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2019, 2022, Arm Limited. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -449,7 +449,8 @@ List getBindings(Class carrier, MemoryLayout layout) { } case INTEGER -> { VMStorage storage = storageCalculator.nextStorage(StorageType.INTEGER, (ValueLayout) layout); - bindings.vmStore(storage, carrier); + // pass integral extension policy here in case it's present (on Mac) + bindings.vmStore(storage, carrier, SharedUtils.isSigned(layout)); } case FLOAT -> { boolean forVariadicFunctionArgs = forArguments && forVariadicFunction; diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/linux/LinuxAArch64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/linux/LinuxAArch64Linker.java index d89717c8320..0fd3976769a 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/linux/LinuxAArch64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/linux/LinuxAArch64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2019, 2021, Arm Limited. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,7 +45,8 @@ public final class LinuxAArch64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + UBYTE, UINT); public static LinuxAArch64Linker getInstance() { final class Holder { diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/macos/MacOsAArch64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/macos/MacOsAArch64Linker.java index a63af4c98df..67392a86e6b 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/macos/MacOsAArch64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/macos/MacOsAArch64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, Arm Limited. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,7 +45,8 @@ public final class MacOsAArch64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + ValueLayout.JAVA_BYTE, ValueLayout.JAVA_INT); public static MacOsAArch64Linker getInstance() { final class Holder { @@ -59,6 +60,13 @@ private MacOsAArch64Linker() { // Ensure there is only one instance } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout.byteSize() < 4 // smaller than int + ? valueLayout // keep, if any + : super.maybeEraseSign(valueLayout); + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { return CallArranger.MACOS.arrangeDowncall(inferredMethodType, function, options); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/windows/WindowsAArch64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/windows/WindowsAArch64Linker.java index df859435f63..55147dbc033 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/windows/WindowsAArch64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/aarch64/windows/WindowsAArch64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, Arm Limited. All rights reserved. * Copyright (c) 2021, 2022, Microsoft. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -46,7 +46,8 @@ public final class WindowsAArch64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_INT, ValueLayout.JAVA_LONG, ValueLayout.JAVA_CHAR); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_INT, ULONG, + ValueLayout.JAVA_BYTE, ValueLayout.JAVA_CHAR); public static WindowsAArch64Linker getInstance() { class Holder { diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FFIType.java b/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FFIType.java index 64c364e6ad2..ecbb7b14a4b 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FFIType.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FFIType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,23 +27,18 @@ import jdk.internal.foreign.Utils; -import java.lang.foreign.Arena; -import java.lang.foreign.GroupLayout; -import java.lang.foreign.MemoryLayout; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.PaddingLayout; -import java.lang.foreign.SequenceLayout; -import java.lang.foreign.StructLayout; -import java.lang.foreign.UnionLayout; -import java.lang.foreign.ValueLayout; +import java.lang.foreign.*; import java.lang.invoke.VarHandle; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.function.Predicate; -import static java.lang.foreign.ValueLayout.*; +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_BYTE; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; +import static java.lang.foreign.ValueLayout.JAVA_SHORT; /** * typedef struct _ffi_type @@ -56,8 +51,8 @@ */ class FFIType { - static final ValueLayout SIZE_T = layoutFor((int)ADDRESS.byteSize()); - private static final ValueLayout UNSIGNED_SHORT = JAVA_SHORT; + static final ValueLayout SIZE_T = layoutFor((int)ADDRESS.byteSize()).withSignedness(false); + private static final ValueLayout UNSIGNED_SHORT = JAVA_SHORT.withSignedness(false); private static final StructLayout LAYOUT = Utils.computePaddedStructLayout( SIZE_T, UNSIGNED_SHORT, UNSIGNED_SHORT.withName("type"), ADDRESS.withName("elements")); @@ -83,37 +78,47 @@ private static MemorySegment make(List elements, FFIABI abi, Arena return ffiType; } - private static final Map, MemorySegment> CARRIER_TO_TYPE = Map.of( - boolean.class, LibFallback.uint8Type(), - byte.class, LibFallback.sint8Type(), - short.class, LibFallback.sint16Type(), - char.class, LibFallback.uint16Type(), - int.class, LibFallback.sint32Type(), - long.class, LibFallback.sint64Type(), - float.class, LibFallback.floatType(), - double.class, LibFallback.doubleType(), - MemorySegment.class, LibFallback.pointerType() - ); + private static final Map UNSIGNED_INTEGRAL_TYPES = Map.of( + 1L, LibFallback.uint8Type(), + 2L, LibFallback.uint16Type(), + 4L, LibFallback.uint32Type(), + 8L, LibFallback.uint64Type()); + + private static final Map SIGNED_INTEGRAL_TYPES = Map.of( + 1L, LibFallback.sint8Type(), + 2L, LibFallback.sint16Type(), + 4L, LibFallback.sint32Type(), + 8L, LibFallback.sint64Type()); static MemorySegment toFFIType(MemoryLayout layout, FFIABI abi, Arena scope) { - if (layout instanceof GroupLayout grpl) { - if (grpl instanceof StructLayout strl) { - // libffi doesn't want our padding - List filteredLayouts = strl.memberLayouts().stream() - .filter(Predicate.not(PaddingLayout.class::isInstance)) - .toList(); - MemorySegment structType = make(filteredLayouts, abi, scope); - verifyStructType(strl, filteredLayouts, structType, abi); - return structType; + return switch (layout) { + case GroupLayout grpl -> { + if (grpl instanceof StructLayout strl) { + // libffi doesn't want our padding + List filteredLayouts = strl.memberLayouts().stream() + .filter(Predicate.not(PaddingLayout.class::isInstance)) + .toList(); + MemorySegment structType = make(filteredLayouts, abi, scope); + verifyStructType(strl, filteredLayouts, structType, abi); + yield structType; + } + assert grpl instanceof UnionLayout; + // JDK-8301800 + throw new IllegalArgumentException("Fallback linker does not support by-value unions: " + grpl); } - assert grpl instanceof UnionLayout; - // JDK-8301800 - throw new IllegalArgumentException("Fallback linker does not support by-value unions: " + grpl); - } else if (layout instanceof SequenceLayout sl) { - List elements = Collections.nCopies(Math.toIntExact(sl.elementCount()), sl.elementLayout()); - return make(elements, abi, scope); - } - return Objects.requireNonNull(CARRIER_TO_TYPE.get(((ValueLayout) layout).carrier())); + case SequenceLayout sl -> { + List elements = Collections.nCopies(Math.toIntExact(sl.elementCount()), sl.elementLayout()); + yield make(elements, abi, scope); + } + case ValueLayout.OfFloat _ -> LibFallback.floatType(); + case ValueLayout.OfDouble _ -> LibFallback.doubleType(); + case AddressLayout _ -> LibFallback.pointerType(); + case ValueLayout.OfBoolean _ -> LibFallback.uint8Type(); + case ValueLayout.OfChar _ -> LibFallback.uint16Type(); + case ValueLayout.OfIntegral integral -> + (integral.isSigned() ? SIGNED_INTEGRAL_TYPES : UNSIGNED_INTEGRAL_TYPES).get(layout.byteSize()); + case null, default -> throw new IllegalArgumentException("Unsupported value layout type: " + layout); + }; } // verify layout against what libffi sets @@ -138,7 +143,7 @@ private static void verifyStructType(StructLayout structLayout, List JAVA_BYTE; case 2 -> JAVA_SHORT; diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FallbackLinker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FallbackLinker.java index 7343a23436d..31768284bf7 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FallbackLinker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/FallbackLinker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,6 @@ import jdk.internal.foreign.AbstractMemorySegmentImpl; import jdk.internal.foreign.MemorySessionImpl; import jdk.internal.foreign.abi.AbstractLinker; -import jdk.internal.foreign.abi.CapturableState; import jdk.internal.foreign.abi.LinkerOptions; import jdk.internal.foreign.abi.SharedUtils; @@ -43,6 +42,7 @@ import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; + import java.lang.invoke.MethodType; import java.lang.ref.Reference; import java.util.ArrayList; @@ -50,6 +50,7 @@ import java.util.Map; import static java.lang.foreign.ValueLayout.*; +import static java.lang.foreign.ValueLayout.JAVA_LONG; import static java.lang.invoke.MethodHandles.foldArguments; public final class FallbackLinker extends AbstractLinker { @@ -79,6 +80,12 @@ public static boolean isSupported() { return LibFallback.SUPPORTED; } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + // never drop, we don't know when the native ABI needs it + return valueLayout; + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { assertNotEmpty(function); @@ -243,14 +250,14 @@ private static void doUpcall(MethodHandle target, MemorySegment retPtr, MemorySe // where private static void writeValue(Object arg, MemoryLayout layout, MemorySegment argSeg) { switch (layout) { - case ValueLayout.OfBoolean bl -> argSeg.set(bl, 0, (Boolean) arg); - case ValueLayout.OfByte bl -> argSeg.set(bl, 0, (Byte) arg); - case ValueLayout.OfShort sl -> argSeg.set(sl, 0, (Short) arg); - case ValueLayout.OfChar cl -> argSeg.set(cl, 0, (Character) arg); - case ValueLayout.OfInt il -> argSeg.set(il, 0, (Integer) arg); - case ValueLayout.OfLong ll -> argSeg.set(ll, 0, (Long) arg); - case ValueLayout.OfFloat fl -> argSeg.set(fl, 0, (Float) arg); - case ValueLayout.OfDouble dl -> argSeg.set(dl, 0, (Double) arg); + case OfBoolean bl -> argSeg.set(bl, 0, (Boolean) arg); + case OfByte bl -> argSeg.set(bl, 0, (Byte) arg); + case OfShort sl -> argSeg.set(sl, 0, (Short) arg); + case OfChar cl -> argSeg.set(cl, 0, (Character) arg); + case OfInt il -> argSeg.set(il, 0, (Integer) arg); + case OfLong ll -> argSeg.set(ll, 0, (Long) arg); + case OfFloat fl -> argSeg.set(fl, 0, (Float) arg); + case OfDouble dl -> argSeg.set(dl, 0, (Double) arg); case AddressLayout al -> argSeg.set(al, 0, (MemorySegment) arg); case GroupLayout _ -> MemorySegment.copy((MemorySegment) arg, 0, argSeg, 0, argSeg.byteSize()); // by-value struct @@ -261,21 +268,21 @@ private static void writeValue(Object arg, MemoryLayout layout, MemorySegment ar } private static Object readValue(MemorySegment seg, MemoryLayout layout) { - if (layout instanceof ValueLayout.OfBoolean bl) { + if (layout instanceof OfBoolean bl) { return seg.get(bl, 0); - } else if (layout instanceof ValueLayout.OfByte bl) { + } else if (layout instanceof OfByte bl) { return seg.get(bl, 0); - } else if (layout instanceof ValueLayout.OfShort sl) { + } else if (layout instanceof OfShort sl) { return seg.get(sl, 0); - } else if (layout instanceof ValueLayout.OfChar cl) { + } else if (layout instanceof OfChar cl) { return seg.get(cl, 0); - } else if (layout instanceof ValueLayout.OfInt il) { + } else if (layout instanceof OfInt il) { return seg.get(il, 0); - } else if (layout instanceof ValueLayout.OfLong ll) { + } else if (layout instanceof OfLong ll) { return seg.get(ll, 0); - } else if (layout instanceof ValueLayout.OfFloat fl) { + } else if (layout instanceof OfFloat fl) { return seg.get(fl, 0); - } else if (layout instanceof ValueLayout.OfDouble dl) { + } else if (layout instanceof OfDouble dl) { return seg.get(dl, 0); } else if (layout instanceof AddressLayout al) { return seg.get(al, 0); @@ -294,25 +301,39 @@ class Holder { static { int wchar_size = LibFallback.wcharSize(); - MemoryLayout wchartLayout = switch(wchar_size) { + ValueLayout wchartLayout = switch(wchar_size) { case 2 -> JAVA_CHAR; // prefer JAVA_CHAR - default -> FFIType.layoutFor(wchar_size); + default -> FFIType.layoutFor(wchar_size).withSignedness(!LibFallback.wcharIsUnsigned()); }; CANONICAL_LAYOUTS = Map.ofEntries( // specified canonical layouts Map.entry("bool", JAVA_BOOLEAN), - Map.entry("char", JAVA_BYTE), + Map.entry("char", JAVA_BYTE.withSignedness(!LibFallback.charIsUnsigned())), + Map.entry("unsigned char", JAVA_BYTE.withSignedness(false)), Map.entry("float", JAVA_FLOAT), Map.entry("long long", JAVA_LONG.withByteAlignment(LibFallback.longLongAlign())), + Map.entry("unsigned long long", JAVA_LONG.withByteAlignment(LibFallback.longLongAlign()).withSignedness(false)), Map.entry("double", JAVA_DOUBLE.withByteAlignment(LibFallback.doubleAlign())), Map.entry("void*", ADDRESS), // platform-dependent sizes Map.entry("size_t", FFIType.SIZE_T), Map.entry("short", FFIType.layoutFor(LibFallback.shortSize())), + Map.entry("unsigned short", FFIType.layoutFor(LibFallback.shortSize()).withSignedness(false)), Map.entry("int", FFIType.layoutFor(LibFallback.intSize())), + Map.entry("unsigned int", FFIType.layoutFor(LibFallback.intSize()).withSignedness(false)), Map.entry("long", FFIType.layoutFor(LibFallback.longSize())), + Map.entry("unsigned long", FFIType.layoutFor(LibFallback.longSize()).withSignedness(false)), Map.entry("wchar_t", wchartLayout), + // size/sign-dependent layouts + Map.entry("int8_t", JAVA_BYTE), + Map.entry("int16_t", JAVA_SHORT), + Map.entry("int32_t", JAVA_INT), + Map.entry("int64_t", JAVA_LONG.withByteAlignment(LibFallback.int64Align())), + Map.entry("uint8_t", JAVA_BYTE.withSignedness(false)), + Map.entry("uint16_t", JAVA_SHORT.withSignedness(false)), + Map.entry("uint32_t", JAVA_INT.withSignedness(false)), + Map.entry("uint64_t", JAVA_LONG.withByteAlignment(LibFallback.int64Align()).withSignedness(false)), // JNI types Map.entry("jboolean", JAVA_BOOLEAN), Map.entry("jchar", JAVA_CHAR), diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/LibFallback.java b/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/LibFallback.java index d77982ef502..929e19af756 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/LibFallback.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/fallback/LibFallback.java @@ -57,7 +57,9 @@ private static boolean tryLoadLibrary() { static MemorySegment uint16Type() { return NativeConstants.UINT16_TYPE; } static MemorySegment sint16Type() { return NativeConstants.SINT16_TYPE; } static MemorySegment sint32Type() { return NativeConstants.SINT32_TYPE; } + static MemorySegment uint32Type() { return NativeConstants.UINT32_TYPE; } static MemorySegment sint64Type() { return NativeConstants.SINT64_TYPE; } + static MemorySegment uint64Type() { return NativeConstants.UINT64_TYPE; } static MemorySegment floatType() { return NativeConstants.FLOAT_TYPE; } static MemorySegment doubleType() { return NativeConstants.DOUBLE_TYPE; } static MemorySegment pointerType() { return NativeConstants.POINTER_TYPE; } @@ -68,8 +70,11 @@ private static boolean tryLoadLibrary() { static int intSize() { return NativeConstants.SIZEOF_INT; } static int longSize() {return NativeConstants.SIZEOF_LONG; } static int wcharSize() {return NativeConstants.SIZEOF_WCHAR; } + static boolean wcharIsUnsigned() {return NativeConstants.WCHAR_IS_UNSIGNED; } + static boolean charIsUnsigned() {return NativeConstants.CHAR_IS_UNSIGNED; } static int longLongAlign() { return NativeConstants.ALIGNOF_LONG_LONG; } static int doubleAlign() { return NativeConstants.ALIGNOF_DOUBLE; } + static int int64Align() { return NativeConstants.ALIGNOF_INT64; } static short structTag() { return NativeConstants.STRUCT_TAG; } @@ -239,9 +244,12 @@ private static native void doDowncall(long cif, long fn, long rvalue, long avalu private static native int ffi_sizeof_int(); private static native int ffi_sizeof_long(); private static native int ffi_sizeof_wchar(); + private static native boolean ffi_wchar_is_unsigned(); + private static native boolean ffi_char_is_unsigned(); private static native int alignof_long_long(); private static native int alignof_double(); + private static native int alignof_int64(); // put these in a separate class to avoid an UnsatisfiedLinkError // when LibFallback is initialized but the library is not present @@ -254,7 +262,9 @@ private NativeConstants() {} static final MemorySegment SINT8_TYPE = MemorySegment.ofAddress(ffi_type_sint8()); static final MemorySegment UINT16_TYPE = MemorySegment.ofAddress(ffi_type_uint16()); static final MemorySegment SINT16_TYPE = MemorySegment.ofAddress(ffi_type_sint16()); + static final MemorySegment UINT32_TYPE = MemorySegment.ofAddress(ffi_type_uint32()); static final MemorySegment SINT32_TYPE = MemorySegment.ofAddress(ffi_type_sint32()); + static final MemorySegment UINT64_TYPE = MemorySegment.ofAddress(ffi_type_uint64()); static final MemorySegment SINT64_TYPE = MemorySegment.ofAddress(ffi_type_sint64()); static final MemorySegment FLOAT_TYPE = MemorySegment.ofAddress(ffi_type_float()); static final MemorySegment DOUBLE_TYPE = MemorySegment.ofAddress(ffi_type_double()); @@ -263,9 +273,12 @@ private NativeConstants() {} static final int SIZEOF_INT = ffi_sizeof_int(); static final int SIZEOF_LONG = ffi_sizeof_long(); static final int SIZEOF_WCHAR = ffi_sizeof_wchar(); + static final boolean WCHAR_IS_UNSIGNED = ffi_wchar_is_unsigned(); + static final boolean CHAR_IS_UNSIGNED = ffi_char_is_unsigned(); static final int ALIGNOF_LONG_LONG = alignof_long_long(); static final int ALIGNOF_DOUBLE = alignof_double(); + static final int ALIGNOF_INT64 = alignof_int64(); static final MemorySegment VOID_TYPE = MemorySegment.ofAddress(ffi_type_void()); static final short STRUCT_TAG = ffi_type_struct(); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/CallArranger.java b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/CallArranger.java index c9994ec2930..de940e5c015 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/CallArranger.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/CallArranger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -433,9 +433,18 @@ List getBindings(Class carrier, MemoryLayout layout) { } } case INTEGER -> { - // ABI requires all int types to get extended to 64 bit. VMStorage storage = storageCalculator.nextStorage(StorageType.INTEGER, false); - bindings.vmStore(storage, carrier); + // ABI requires all int types to get extended to 64 bit. + // But we only do it for unsigned values here since this saves + // on argument slots for the downcall stub. Signed values will be + // sign-extended when being moved into the destination register. + if (layout instanceof ValueLayout.OfIntegral integral + && !integral.isSigned() && carrier != long.class) { + bindings.cast(carrier, long.class, false) + .vmStore(storage, long.class); + } else { + bindings.vmStore(storage, carrier); + } } case FLOAT -> { VMStorage storage = storageCalculator.nextStorage(StorageType.FLOAT, carrier == float.class); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/aix/AixPPC64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/aix/AixPPC64Linker.java index 503dac3e4fb..2dc094b231f 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/aix/AixPPC64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/aix/AixPPC64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,7 +41,8 @@ public final class AixPPC64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + UBYTE, UINT); public static AixPPC64Linker getInstance() { final class Holder { @@ -73,6 +74,13 @@ protected void checkStructMember(MemoryLayout member, long offset) { } } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout.byteSize() < 8 // smaller than long + ? valueLayout // keep, if any + : super.maybeEraseSign(valueLayout); + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { return CallArranger.AIX.arrangeDowncall(inferredMethodType, function, options); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64Linker.java index 72d1ed704e7..7dc52af05e5 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,7 +41,8 @@ public final class LinuxPPC64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + UBYTE, ValueLayout.JAVA_INT); public static LinuxPPC64Linker getInstance() { final class Holder { @@ -55,6 +56,13 @@ private LinuxPPC64Linker() { // Ensure there is only one instance } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout.byteSize() < 8 // smaller than long + ? valueLayout // keep, if any + : super.maybeEraseSign(valueLayout); + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { return CallArranger.ABIv1.arrangeDowncall(inferredMethodType, function, options); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64leLinker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64leLinker.java index 22acc6ea683..ccb18c73f61 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64leLinker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/ppc64/linux/LinuxPPC64leLinker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,7 +41,8 @@ public final class LinuxPPC64leLinker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + UBYTE, ValueLayout.JAVA_INT); public static LinuxPPC64leLinker getInstance() { final class Holder { @@ -55,6 +56,13 @@ private LinuxPPC64leLinker() { // Ensure there is only one instance } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout.byteSize() < 8 // smaller than long + ? valueLayout // keep, if any + : super.maybeEraseSign(valueLayout); + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { return CallArranger.ABIv2.arrangeDowncall(inferredMethodType, function, options); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64CallArranger.java b/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64CallArranger.java index eb4192fdfe7..82563765c87 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64CallArranger.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64CallArranger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023, Institute of Software, Chinese Academy of Sciences. * All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -28,7 +28,15 @@ package jdk.internal.foreign.abi.riscv64.linux; +import java.lang.foreign.AddressLayout; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.GroupLayout; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; import jdk.internal.foreign.Utils; +import java.lang.foreign.*; + import jdk.internal.foreign.abi.ABIDescriptor; import jdk.internal.foreign.abi.AbstractLinker.UpcallStubFactory; import jdk.internal.foreign.abi.Binding; @@ -39,20 +47,15 @@ import jdk.internal.foreign.abi.SharedUtils; import jdk.internal.foreign.abi.VMStorage; -import java.lang.foreign.AddressLayout; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.GroupLayout; -import java.lang.foreign.MemoryLayout; -import java.lang.foreign.MemorySegment; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import java.util.List; import java.util.Map; import java.util.Optional; +import static jdk.internal.foreign.abi.riscv64.linux.TypeClass.*; import static jdk.internal.foreign.abi.riscv64.RISCV64Architecture.Regs.*; import static jdk.internal.foreign.abi.riscv64.RISCV64Architecture.*; -import static jdk.internal.foreign.abi.riscv64.linux.TypeClass.*; /** * For the RISCV64 C ABI specifically, this class uses CallingSequenceBuilder @@ -275,7 +278,7 @@ List getBindings(Class carrier, MemoryLayout layout, TypeClass argum switch (argumentClass) { case INTEGER -> { VMStorage storage = storageCalculator.getStorage(StorageType.INTEGER); - bindings.vmStore(storage, carrier); + bindings.vmStore(storage, carrier, SharedUtils.isSigned(layout)); } case FLOAT -> { VMStorage storage = storageCalculator.getStorage(StorageType.FLOAT); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64Linker.java index cc948b884bc..e033ccbb739 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/riscv64/linux/LinuxRISCV64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023, Institute of Software, Chinese Academy of Sciences. * All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -42,7 +42,8 @@ public final class LinuxRISCV64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + UBYTE, ValueLayout.JAVA_INT); public static LinuxRISCV64Linker getInstance() { final class Holder { @@ -56,6 +57,13 @@ private LinuxRISCV64Linker() { // Ensure there is only one instance } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout.byteSize() < 4 // smaller than int + ? valueLayout // keep, if any + : super.maybeEraseSign(valueLayout); + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { return LinuxRISCV64CallArranger.arrangeDowncall(inferredMethodType, function, options); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390CallArranger.java b/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390CallArranger.java index bafa5652c30..75d009ccf02 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390CallArranger.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390CallArranger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023 IBM Corp. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,6 +26,13 @@ package jdk.internal.foreign.abi.s390.linux; +import java.lang.foreign.AddressLayout; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.GroupLayout; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; + import jdk.internal.foreign.Utils; import jdk.internal.foreign.abi.ABIDescriptor; import jdk.internal.foreign.abi.AbstractLinker.UpcallStubFactory; @@ -37,11 +44,6 @@ import jdk.internal.foreign.abi.SharedUtils; import jdk.internal.foreign.abi.VMStorage; -import java.lang.foreign.AddressLayout; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.GroupLayout; -import java.lang.foreign.MemoryLayout; -import java.lang.foreign.MemorySegment; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import java.util.List; @@ -247,9 +249,18 @@ List getBindings(Class carrier, MemoryLayout layout) { } } case INTEGER -> { - // ABI requires all int types to get extended to 64 bit. VMStorage storage = storageCalculator.getStorage(StorageType.INTEGER, false); - bindings.vmStore(storage, carrier); + // ABI requires all int types to get extended to 64 bit. + // But we only do it for unsigned values here since this saves + // on argument slots for the downcall stub. Signed values will be + // sign-extended when being moved into the destination register. + if (layout instanceof ValueLayout.OfIntegral integral + && !integral.isSigned() && carrier != long.class) { + bindings.cast(carrier, long.class, false) + .vmStore(storage, long.class); + } else { + bindings.vmStore(storage, carrier); + } } case FLOAT -> { VMStorage storage = storageCalculator.getStorage(StorageType.FLOAT, carrier == float.class); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390Linker.java index 558d19d772c..8a5ca554837 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/s390/linux/LinuxS390Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023 IBM Corp. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -40,7 +40,8 @@ public final class LinuxS390Linker extends AbstractLinker { private static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + UBYTE, ValueLayout.JAVA_INT); public static LinuxS390Linker getInstance() { final class Holder { @@ -54,6 +55,13 @@ private LinuxS390Linker() { // Ensure there is only one instance } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout.byteSize() < 8 // smaller than long + ? valueLayout // keep, if any + : super.maybeEraseSign(valueLayout); + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { return LinuxS390CallArranger.arrangeDowncall(inferredMethodType, function, options); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/CallArranger.java b/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/CallArranger.java index 6b8db51ba46..b60de638ee3 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/CallArranger.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/CallArranger.java @@ -295,7 +295,11 @@ List getBindings(Class carrier, MemoryLayout layout) { } case INTEGER -> { VMStorage storage = storageCalculator.nextStorage(StorageType.INTEGER); - bindings.vmStore(storage, carrier); + // we specify the sign-extension behavior here so that we get zero-extension for + // unsigned types. This is required by the Mac ABI, and there's a bug in clang + // where callee's might be assuming the upper bits of a register are sign/zero-extended + // on Linux as well. + bindings.vmStore(storage, carrier, SharedUtils.isSigned(layout)); } case FLOAT -> { VMStorage storage = storageCalculator.nextStorage(StorageType.VECTOR); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/SysVx64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/SysVx64Linker.java index 1b4237ec7fa..d3176cbf166 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/SysVx64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/x64/sysv/SysVx64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,8 @@ public final class SysVx64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_LONG, ULONG, + ValueLayout.JAVA_BYTE, ValueLayout.JAVA_INT); public static SysVx64Linker getInstance() { final class Holder { @@ -56,6 +57,13 @@ private SysVx64Linker() { // Ensure there is only one instance } + @Override + protected ValueLayout maybeEraseSign(ValueLayout valueLayout) { + return valueLayout.byteSize() < 4 // smaller than int + ? valueLayout // keep, if any + : super.maybeEraseSign(valueLayout); + } + @Override protected MethodHandle arrangeDowncall(MethodType inferredMethodType, FunctionDescriptor function, LinkerOptions options) { return CallArranger.arrangeDowncall(inferredMethodType, function, options); diff --git a/src/java.base/share/classes/jdk/internal/foreign/abi/x64/windows/Windowsx64Linker.java b/src/java.base/share/classes/jdk/internal/foreign/abi/x64/windows/Windowsx64Linker.java index c14616f190b..370def2f5f1 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/abi/x64/windows/Windowsx64Linker.java +++ b/src/java.base/share/classes/jdk/internal/foreign/abi/x64/windows/Windowsx64Linker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,8 @@ public final class Windowsx64Linker extends AbstractLinker { static final Map CANONICAL_LAYOUTS = - SharedUtils.canonicalLayouts(ValueLayout.JAVA_INT, ValueLayout.JAVA_LONG, ValueLayout.JAVA_CHAR); + SharedUtils.canonicalLayouts(ValueLayout.JAVA_INT, ULONG, + ValueLayout.JAVA_BYTE, ValueLayout.JAVA_CHAR); public static Windowsx64Linker getInstance() { final class Holder { diff --git a/src/java.base/share/classes/jdk/internal/foreign/layout/ValueLayouts.java b/src/java.base/share/classes/jdk/internal/foreign/layout/ValueLayouts.java index d1dd9e51301..5ecbf64bb53 100644 --- a/src/java.base/share/classes/jdk/internal/foreign/layout/ValueLayouts.java +++ b/src/java.base/share/classes/jdk/internal/foreign/layout/ValueLayouts.java @@ -71,7 +71,8 @@ abstract static sealed class AbstractValueLayout carrier, ByteOrder order, long byteSize, long byteAlignment, Optional name) { + AbstractValueLayout(Class carrier, ByteOrder order, long byteSize, long byteAlignment, + Optional name) { super(byteSize, byteAlignment, name); this.carrier = carrier; this.order = order; @@ -170,6 +171,53 @@ public final VarHandle varHandle() { } } + abstract static sealed class AbstractIntegralLayout & ValueLayout> extends AbstractValueLayout { + + private final boolean sign; + + AbstractIntegralLayout(Class carrier, ByteOrder order, boolean sign, + long byteSize, long byteAlignment, Optional name) { + super(carrier, order, byteSize, byteAlignment, name); + this.sign = sign; + } + + @Override + final V dup(ByteOrder order, long byteAlignment, Optional name) { + return dup(order, isSigned(), byteAlignment, name); + } + + abstract V dup(ByteOrder order, boolean sign, long byteAlignment, Optional name); + + public final boolean isSigned() { + return sign; + } + + public final V withSignedness(boolean sign) { + return dup(order(), sign, byteAlignment(), name()); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), sign); + } + + @Override + public boolean equals(Object other) { + return this == other || + other instanceof AbstractIntegralLayout otherValue && + super.equals(other) && + sign == otherValue.sign; + } + + @Override + String decorateLayoutString(String s) { + if (!sign) { + s = "u" + s; + } + return super.decorateLayoutString(s); + } + } + @ValueBased public static final class OfBooleanImpl extends AbstractValueLayout implements ValueLayout.OfBoolean { @@ -188,26 +236,29 @@ public static OfBoolean of(ByteOrder order) { } @ValueBased - public static final class OfByteImpl extends AbstractValueLayout implements ValueLayout.OfByte { + public static final class OfByteImpl extends AbstractIntegralLayout implements ValueLayout.OfByte { - private OfByteImpl(ByteOrder order, long byteAlignment, Optional name) { - super(byte.class, order, Byte.BYTES, byteAlignment, name); + private OfByteImpl(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + super(byte.class, order, sign, Byte.BYTES, byteAlignment, name); } @Override - OfByteImpl dup(ByteOrder order, long byteAlignment, Optional name) { - return new OfByteImpl(order, byteAlignment, name); + OfByteImpl dup(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + return new OfByteImpl(order, sign, byteAlignment, name); } public static OfByte of(ByteOrder order) { - return new OfByteImpl(order, Byte.BYTES, Optional.empty()); + return new OfByteImpl(order, true, Byte.BYTES, Optional.empty()); } } @ValueBased public static final class OfCharImpl extends AbstractValueLayout implements ValueLayout.OfChar { - private OfCharImpl(ByteOrder order, long byteAlignment, Optional name) { + private OfCharImpl(ByteOrder order, long byteAlignment, + Optional name) { super(char.class, order, Character.BYTES, byteAlignment, name); } @@ -222,36 +273,40 @@ public static OfChar of(ByteOrder order) { } @ValueBased - public static final class OfShortImpl extends AbstractValueLayout implements ValueLayout.OfShort { + public static final class OfShortImpl extends AbstractIntegralLayout implements ValueLayout.OfShort { - private OfShortImpl(ByteOrder order, long byteAlignment, Optional name) { - super(short.class, order, Short.BYTES, byteAlignment, name); + private OfShortImpl(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + super(short.class, order, sign, Short.BYTES, byteAlignment, name); } @Override - OfShortImpl dup(ByteOrder order, long byteAlignment, Optional name) { - return new OfShortImpl(order, byteAlignment, name); + OfShortImpl dup(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + return new OfShortImpl(order, sign, byteAlignment, name); } public static OfShort of(ByteOrder order) { - return new OfShortImpl(order, Short.BYTES, Optional.empty()); + return new OfShortImpl(order, true, Short.BYTES, Optional.empty()); } } @ValueBased - public static final class OfIntImpl extends AbstractValueLayout implements ValueLayout.OfInt { + public static final class OfIntImpl extends AbstractIntegralLayout implements ValueLayout.OfInt { - private OfIntImpl(ByteOrder order, long byteAlignment, Optional name) { - super(int.class, order, Integer.BYTES, byteAlignment, name); + private OfIntImpl(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + super(int.class, order, sign, Integer.BYTES, byteAlignment, name); } @Override - OfIntImpl dup(ByteOrder order, long byteAlignment, Optional name) { - return new OfIntImpl(order, byteAlignment, name); + OfIntImpl dup(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + return new OfIntImpl(order, sign, byteAlignment, name); } public static OfInt of(ByteOrder order) { - return new OfIntImpl(order, Integer.BYTES, Optional.empty()); + return new OfIntImpl(order, true, Integer.BYTES, Optional.empty()); } } @@ -273,19 +328,21 @@ public static OfFloat of(ByteOrder order) { } @ValueBased - public static final class OfLongImpl extends AbstractValueLayout implements ValueLayout.OfLong { + public static final class OfLongImpl extends AbstractIntegralLayout implements ValueLayout.OfLong { - private OfLongImpl(ByteOrder order, long byteAlignment, Optional name) { - super(long.class, order, Long.BYTES, byteAlignment, name); + private OfLongImpl(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + super(long.class, order, sign, Long.BYTES, byteAlignment, name); } @Override - OfLongImpl dup(ByteOrder order, long byteAlignment, Optional name) { - return new OfLongImpl(order, byteAlignment, name); + OfLongImpl dup(ByteOrder order, boolean sign, long byteAlignment, + Optional name) { + return new OfLongImpl(order, sign, byteAlignment, name); } public static OfLong of(ByteOrder order) { - return new OfLongImpl(order, Long.BYTES, Optional.empty()); + return new OfLongImpl(order, true, Long.BYTES, Optional.empty()); } } @@ -312,7 +369,8 @@ public static final class OfAddressImpl extends AbstractValueLayout name) { + private OfAddressImpl(ByteOrder order, long byteSize, long byteAlignment, MemoryLayout targetLayout, + Optional name) { super(MemorySegment.class, order, byteSize, byteAlignment, name); this.targetLayout = targetLayout; } diff --git a/src/java.base/share/native/libfallbackLinker/fallbackLinker.c b/src/java.base/share/native/libfallbackLinker/fallbackLinker.c index 7519efd93bb..e5ad7ef30cb 100644 --- a/src/java.base/share/native/libfallbackLinker/fallbackLinker.c +++ b/src/java.base/share/native/libfallbackLinker/fallbackLinker.c @@ -321,3 +321,20 @@ JNIEXPORT jint JNICALL Java_jdk_internal_foreign_abi_fallback_LibFallback_alignof_1double(JNIEnv* env, jclass cls) { return alignof(double); } + +JNIEXPORT jint JNICALL +Java_jdk_internal_foreign_abi_fallback_LibFallback_alignof_1int64(JNIEnv* env, jclass cls) { + return alignof(int64_t); +} + +#define IS_UNSIGNED(T) ((T)0 < (T)-1) + +JNIEXPORT jboolean JNICALL +Java_jdk_internal_foreign_abi_fallback_LibFallback_ffi_1wchar_1is_1unsigned(JNIEnv* env, jclass cls) { + return IS_UNSIGNED(wchar_t); +} + +JNIEXPORT jboolean JNICALL +Java_jdk_internal_foreign_abi_fallback_LibFallback_ffi_1char_1is_1unsigned(JNIEnv* env, jclass cls) { + return IS_UNSIGNED(char); +} diff --git a/test/jdk/TEST.groups b/test/jdk/TEST.groups index aa6d13ad58f..d74d123d573 100644 --- a/test/jdk/TEST.groups +++ b/test/jdk/TEST.groups @@ -406,6 +406,7 @@ jdk_svc = \ jdk_foreign = \ java/foreign \ jdk/internal/reflect/CallerSensitive/CheckCSMs.java \ + tools/sincechecker/modules/java.base/JavaBaseCheckSince.java \ -java/foreign/TestMatrix.java jdk_vector = \ diff --git a/test/jdk/java/foreign/MemoryLayoutTypeRetentionTest.java b/test/jdk/java/foreign/MemoryLayoutTypeRetentionTest.java index 12f9b145133..24ba9ac6774 100644 --- a/test/jdk/java/foreign/MemoryLayoutTypeRetentionTest.java +++ b/test/jdk/java/foreign/MemoryLayoutTypeRetentionTest.java @@ -62,7 +62,8 @@ public void testOfByte() { .withByteAlignment(BYTE_ALIGNMENT) .withoutName() .withName(NAME) - .withOrder(BYTE_ORDER); + .withOrder(BYTE_ORDER) + .withSignedness(false); check(v); } @@ -72,7 +73,8 @@ public void testOfShort() { .withByteAlignment(BYTE_ALIGNMENT) .withoutName() .withName(NAME) - .withOrder(BYTE_ORDER); + .withOrder(BYTE_ORDER) + .withSignedness(false); check(v); } @@ -82,7 +84,8 @@ public void testOfInt() { .withByteAlignment(BYTE_ALIGNMENT) .withoutName() .withName(NAME) - .withOrder(BYTE_ORDER); + .withOrder(BYTE_ORDER) + .withSignedness(false); check(v); } @@ -102,7 +105,8 @@ public void testOfLong() { .withByteAlignment(BYTE_ALIGNMENT) .withoutName() .withName(NAME) - .withOrder(BYTE_ORDER); + .withOrder(BYTE_ORDER) + .withSignedness(false); check(v); } @@ -196,6 +200,11 @@ public void testUnionLayout() { check(v); } + public void check(ValueLayout.OfIntegral i) { + check((ValueLayout) i); + assertFalse(i.isSigned()); + } + public void check(ValueLayout v) { check((MemoryLayout) v); assertEquals(BYTE_ORDER, v.order()); diff --git a/test/jdk/java/foreign/NativeTestHelper.java b/test/jdk/java/foreign/NativeTestHelper.java index 1ea45437da1..74804ea2426 100644 --- a/test/jdk/java/foreign/NativeTestHelper.java +++ b/test/jdk/java/foreign/NativeTestHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -129,6 +129,13 @@ public static boolean isPointer(MemoryLayout layout) { */ public static final ValueLayout C_SIZE_T = (ValueLayout) LINKER.canonicalLayouts().get("size_t"); + public static final ValueLayout.OfByte UCHAR = (ValueLayout.OfByte) LINKER.canonicalLayouts().get("unsigned char"); + public static final ValueLayout.OfShort USHORT = (ValueLayout.OfShort) LINKER.canonicalLayouts().get("unsigned short"); + public static final ValueLayout.OfInt UINT = (ValueLayout.OfInt) LINKER.canonicalLayouts().get("unsigned int"); + public static final ValueLayout.OfByte UINT8 = (ValueLayout.OfByte) LINKER.canonicalLayouts().get("uint8_t"); + public static final ValueLayout.OfShort UINT16 = (ValueLayout.OfShort) LINKER.canonicalLayouts().get("uint16_t"); + public static final ValueLayout.OfInt UINT32 = (ValueLayout.OfInt) LINKER.canonicalLayouts().get("uint32_t"); + // Common layout shared by some tests // struct S_PDI { void* p0; double p1; int p2; }; public static final MemoryLayout S_PDI_LAYOUT = switch ((int) ValueLayout.ADDRESS.byteSize()) { diff --git a/test/jdk/java/foreign/TestIllegalLink.java b/test/jdk/java/foreign/TestIllegalLink.java index 995efd199d6..d63e5b4476f 100644 --- a/test/jdk/java/foreign/TestIllegalLink.java +++ b/test/jdk/java/foreign/TestIllegalLink.java @@ -198,7 +198,8 @@ public static Object[][] types() { }, })); - for (ValueLayout illegalLayout : List.of(C_CHAR, ValueLayout.JAVA_CHAR, C_BOOL, C_SHORT, C_FLOAT)) { + for (ValueLayout illegalLayout : List.of(C_CHAR, ValueLayout.JAVA_CHAR, C_BOOL, C_SHORT, C_FLOAT, + UCHAR, USHORT, UINT8, UINT16)) { cases.add(new Object[]{ FunctionDescriptor.ofVoid(C_INT, illegalLayout), new Linker.Option[]{Linker.Option.firstVariadicArg(1)}, diff --git a/test/jdk/java/foreign/TestNulls.java b/test/jdk/java/foreign/TestNulls.java index 8825809930a..d7a70169e66 100644 --- a/test/jdk/java/foreign/TestNulls.java +++ b/test/jdk/java/foreign/TestNulls.java @@ -152,6 +152,7 @@ static void addDefaultMapping(Class carrier, Z value) { addDefaultMapping(MethodType.class, MethodType.methodType(void.class)); addDefaultMapping(MemoryLayout.class, ValueLayout.JAVA_INT); addDefaultMapping(ValueLayout.class, ValueLayout.JAVA_INT); + addDefaultMapping(ValueLayout.OfIntegral.class, ValueLayout.JAVA_INT); addDefaultMapping(AddressLayout.class, ValueLayout.ADDRESS); addDefaultMapping(ValueLayout.OfByte.class, ValueLayout.JAVA_BYTE); addDefaultMapping(ValueLayout.OfBoolean.class, ValueLayout.JAVA_BOOLEAN); diff --git a/test/jdk/java/foreign/callarranger/TestLayoutEquality.java b/test/jdk/java/foreign/callarranger/TestLayoutEquality.java index 96ee11f6a96..8eaff680d22 100644 --- a/test/jdk/java/foreign/callarranger/TestLayoutEquality.java +++ b/test/jdk/java/foreign/callarranger/TestLayoutEquality.java @@ -56,6 +56,9 @@ public void testReconstructedEquality(ValueLayout layout) { if (layout instanceof AddressLayout addressLayout && addressLayout.targetLayout().isPresent()) { newLayout = ((AddressLayout)newLayout).withTargetLayout(addressLayout.targetLayout().get()); } + if (layout instanceof ValueLayout.OfIntegral integral) { + newLayout = ((ValueLayout.OfIntegral) newLayout).withSignedness(integral.isSigned()); + } // properties should be equal assertEquals(layout.byteSize(), newLayout.byteSize()); diff --git a/test/jdk/java/foreign/canonicallayouts/TestCanonicalLayouts.java b/test/jdk/java/foreign/canonicallayouts/TestCanonicalLayouts.java new file mode 100644 index 00000000000..6c62a269e8e --- /dev/null +++ b/test/jdk/java/foreign/canonicallayouts/TestCanonicalLayouts.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @library ../ /test/lib + * @run junit/othervm/native --enable-native-access=ALL-UNNAMED TestCanonicalLayouts + */ + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.ValueLayout; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +public class TestCanonicalLayouts extends NativeTestHelper { + + static { + System.loadLibrary("CanonicalLayouts"); + } + + @ParameterizedTest + @MethodSource("cases") + public void testCanonicalLayout(String name) { + MemoryLayout layout = LINKER.canonicalLayouts().get(name); + assertNotNull(layout); + assertEquals(nativeSizeFor(name), layout.byteSize()); + assertEquals(nativeAlignFor(name), layout.byteAlignment()); + if (layout instanceof ValueLayout.OfIntegral integral) { + assertEquals(nativeSignednessFor(name), integral.isSigned()); + } + } + + private boolean nativeSignednessFor(String name) { + try { + return (boolean) downcallHandle( + escapeName(name) + "_signedness", + FunctionDescriptor.of(C_BOOL) + ).invokeExact(); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + private long nativeAlignFor(String name) { + try { + return (long) downcallHandle( + escapeName(name) + "_align", + FunctionDescriptor.of(C_LONG_LONG) + ).invokeExact(); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + private long nativeSizeFor(String name) { + try { + return (long) downcallHandle( + escapeName(name) + "_size", + FunctionDescriptor.of(C_LONG_LONG) + ).invokeExact(); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + private static String escapeName(String str) { + return str.replace(' ', '_').replace("*", "_star"); + } + + public static Stream cases() { + // As defined by the Linker javadoc + return Stream.of( + "bool", + "char", + "unsigned char", + "short", + "unsigned short", + "int", + "unsigned int", + "long", + "unsigned long", + "long long", + "unsigned long long", + "float", + "double", + "size_t", + "wchar_t", + "void*", + "int8_t", + "int16_t", + "int32_t", + "int64_t", + "uint8_t", + "uint16_t", + "uint32_t", + "uint64_t" + ); + } +} + diff --git a/test/jdk/java/foreign/canonicallayouts/libCanonicalLayouts.c b/test/jdk/java/foreign/canonicallayouts/libCanonicalLayouts.c new file mode 100644 index 00000000000..e6833b2ac19 --- /dev/null +++ b/test/jdk/java/foreign/canonicallayouts/libCanonicalLayouts.c @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#ifdef _AIX +// The JDK prefers linux compatible double alignment by default. +// Also see usage of #pragma align (natural) +typedef double linux_double __attribute__((aligned(8))); +#endif + +#include "export.h" + +#include +#include +#include +#include + +// Inverted test to avoid compiler warnings +#define IS_SIGNED(T) (!((T)0 < (T)-1)) + +// Expose some basic information about the type, such as size, align, and signedness +#define CHECKS_ALL(T, NAME) \ + EXPORT long long NAME##_size() { \ + return sizeof(T); \ + } \ + EXPORT long long NAME##_align() { \ + return alignof(T); \ + } + +#define CHECKS_INTEGRAL(T, NAME) \ +CHECKS_ALL(T, NAME) \ + EXPORT bool NAME##_signedness() { \ + return IS_SIGNED(T); \ + } + +CHECKS_ALL(bool, bool) +CHECKS_ALL(float, float) +#ifdef _AIX +CHECKS_ALL(linux_double, double) +#else +CHECKS_ALL(double, double) +#endif +CHECKS_ALL(void*, void_star) + +CHECKS_INTEGRAL(char, char) +CHECKS_INTEGRAL(unsigned char, unsigned_char) +CHECKS_INTEGRAL(short, short) +CHECKS_INTEGRAL(unsigned short, unsigned_short) +CHECKS_INTEGRAL(int, int) +CHECKS_INTEGRAL(unsigned int, unsigned_int) +CHECKS_INTEGRAL(long, long) +CHECKS_INTEGRAL(unsigned long, unsigned_long) +CHECKS_INTEGRAL(long long, long_long) +CHECKS_INTEGRAL(unsigned long long, unsigned_long_long) +CHECKS_INTEGRAL(size_t, size_t) +CHECKS_INTEGRAL(wchar_t, wchar_t) +CHECKS_INTEGRAL(int8_t, int8_t) +CHECKS_INTEGRAL(int16_t, int16_t) +CHECKS_INTEGRAL(int32_t, int32_t) +CHECKS_INTEGRAL(int64_t, int64_t) +CHECKS_INTEGRAL(uint8_t, uint8_t) +CHECKS_INTEGRAL(uint16_t, uint16_t) +CHECKS_INTEGRAL(uint32_t, uint32_t) +CHECKS_INTEGRAL(uint64_t, uint64_t) diff --git a/test/jdk/java/foreign/normalize/TestZeroExtendInt.java b/test/jdk/java/foreign/normalize/TestZeroExtendInt.java new file mode 100644 index 00000000000..08110f3839c --- /dev/null +++ b/test/jdk/java/foreign/normalize/TestZeroExtendInt.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @requires jdk.foreign.linker != "FALLBACK" + * @library ../ + * @requires os.name == "Mac OS X" | os.name == "AIX" | (os.name == "Linux" & os.arch != "aarch64") + * + * @run junit/othervm/native + * --enable-native-access=ALL-UNNAMED + * TestZeroExtendInt + */ + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.foreign.*; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class TestZeroExtendInt extends NativeTestHelper { + + static final MethodHandle MH_CAPTURE; + + static { + try { + MH_CAPTURE = MethodHandles.lookup().findStatic(TestZeroExtendInt.class, "capture", + MethodType.methodType(int.class, AtomicInteger.class, int.class)); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + // some platforms (see @requires) require zero-extension of types smaller than int + @ParameterizedTest + @MethodSource("cases") + public void testZeroExtend(MemoryLayout layout, Object input, Object expectedOutput) throws Throwable { + AtomicInteger captured = new AtomicInteger(); + // We pass a type smaller than int, but receive back an int + // make sure it gets widened correctly according to its sign by the binding recipe. + MemorySegment stub = LINKER.upcallStub(MH_CAPTURE.bindTo(captured), + FunctionDescriptor.of(C_INT, C_INT), Arena.ofAuto()); + MethodHandle mh = LINKER.downcallHandle(FunctionDescriptor.of(C_INT, layout)); + int output = (int) mh.invoke(stub, input); + assertEquals(expectedOutput, captured.get()); + assertEquals(expectedOutput, output); + } + + private static int capture(AtomicInteger captured, int arg) { + captured.set(arg); + return arg; + } + + public static Object[][] cases() { + return new Object[][] { + // when MIN_VALUE gets zero-extended the sign should be dropped + { UCHAR, Byte.MIN_VALUE, Byte.toUnsignedInt(Byte.MIN_VALUE) }, + { USHORT, Short.MIN_VALUE, Short.toUnsignedInt(Short.MIN_VALUE) }, + { UINT8, Byte.MIN_VALUE, Byte.toUnsignedInt(Byte.MIN_VALUE) }, + { UINT16, Short.MIN_VALUE, Short.toUnsignedInt(Short.MIN_VALUE) }, + }; + } +} diff --git a/test/jdk/java/foreign/normalize/TestZeroExtendLong.java b/test/jdk/java/foreign/normalize/TestZeroExtendLong.java new file mode 100644 index 00000000000..31f1341c4fa --- /dev/null +++ b/test/jdk/java/foreign/normalize/TestZeroExtendLong.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @requires jdk.foreign.linker != "FALLBACK" + * @library ../ + * @requires os.arch == "ppc64" | os.arch == "ppc64le" | os.arch == "s390x" + * @run junit/othervm/native + * --enable-native-access=ALL-UNNAMED + * TestZeroExtendLong + */ + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class TestZeroExtendLong extends NativeTestHelper { + + static final MethodHandle MH_CAPTURE; + + static { + try { + MH_CAPTURE = MethodHandles.lookup().findStatic(TestZeroExtendLong.class, "capture", + MethodType.methodType(long.class, AtomicLong.class, long.class)); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + // some platforms (see @requires) require widening of types smaller than long + @ParameterizedTest + @MethodSource("cases") + public void testZeroExtend(MemoryLayout layout, Object input, Object expectedOutput) throws Throwable { + AtomicLong captured = new AtomicLong(); + // We pass a type smaller than long, but receive back a long, + // make sure it gets widened correctly according to its sign by the binding recipe. + MemorySegment stub = LINKER.upcallStub(MH_CAPTURE.bindTo(captured), + FunctionDescriptor.of(C_LONG_LONG, C_LONG_LONG), Arena.ofAuto()); + MethodHandle mh = LINKER.downcallHandle(FunctionDescriptor.of(C_LONG_LONG, layout)); + long output = (long) mh.invoke(stub, input); + assertEquals(expectedOutput, captured.get()); + assertEquals(expectedOutput, output); + } + + private static long capture(AtomicLong captured, long arg) { + captured.set(arg); + return arg; + } + + public static Object[][] cases() { + return new Object[][] { + // when MIN_VALUE gets zero-extended the sign should be dropped + { UCHAR, Byte.MIN_VALUE, Byte.toUnsignedLong(Byte.MIN_VALUE) }, + { USHORT, Short.MIN_VALUE, Short.toUnsignedLong(Short.MIN_VALUE) }, + { UINT8, Byte.MIN_VALUE, Byte.toUnsignedLong(Byte.MIN_VALUE) }, + { UINT16, Short.MIN_VALUE, Short.toUnsignedLong(Short.MIN_VALUE) }, + { UINT, Integer.MIN_VALUE, Integer.toUnsignedLong(Integer.MIN_VALUE) }, + { UINT32, Integer.MIN_VALUE, Integer.toUnsignedLong(Integer.MIN_VALUE) }, + }; + } +} diff --git a/test/jdk/java/lang/invoke/VarHandles/VarHandleTestExact.java b/test/jdk/java/lang/invoke/VarHandles/VarHandleTestExact.java index 9960e08a0c7..56c1a36e431 100644 --- a/test/jdk/java/lang/invoke/VarHandles/VarHandleTestExact.java +++ b/test/jdk/java/lang/invoke/VarHandles/VarHandleTestExact.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,6 @@ /* * @test - * @modules java.base/jdk.internal.access.foreign - * @modules java.base/jdk.internal.foreign.layout * * @run junit/othervm -Xverify:all * -Djdk.internal.foreign.SHOULD_ADAPT_HANDLES=false @@ -49,8 +47,7 @@ import java.lang.foreign.Arena; import java.lang.foreign.MemorySegment; -import jdk.internal.foreign.layout.ValueLayouts; - +import java.lang.foreign.ValueLayout; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; import java.lang.invoke.WrongMethodTypeException; @@ -61,6 +58,7 @@ import java.util.List; import java.util.function.Consumer; +import static java.lang.foreign.ValueLayout.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.TestInstance; @@ -178,14 +176,13 @@ public void testExactBufferSet(Class arrayClass, Object testValue, SetBufferX @ParameterizedTest @MethodSource("dataSetMemorySegment") - public void testExactSegmentSet(Class carrier, Object testValue, SetSegmentX setter) { - VarHandle vh = ValueLayouts.valueLayout(carrier, ByteOrder.nativeOrder()).varHandle(); + public void testExactSegmentSet(ValueLayout layout, Object testValue, SetSegmentX setter) { try (Arena arena = Arena.ofConfined()) { MemorySegment seg = arena.allocate(8); - doTest(vh, + doTest(layout.varHandle(), tvh -> tvh.set(seg, 0L, testValue), tvh -> setter.set(tvh, seg, 0L, testValue), - ".*\\Qhandle's method type (MemorySegment,long," + carrier.getSimpleName() + ")void \\E.*"); + ".*\\Qhandle's method type (MemorySegment,long," + layout.carrier().getSimpleName() + ")void \\E.*"); } } @@ -270,8 +267,8 @@ private static void testCaseBufferSet(List cases, Class arrayType, cases.add(new Object[] { arrayType, testValue, setter }); } - private static void testCaseSegmentSet(List cases, Class carrier, Object testValue, SetSegmentX setter) { - cases.add(new Object[] { carrier, testValue, setter }); + private static void testCaseSegmentSet(List cases, ValueLayout layout, Object testValue, SetSegmentX setter) { + cases.add(new Object[] { layout, testValue, setter }); } public static Object[][] dataObjectAccess() { @@ -383,11 +380,11 @@ public static Object[][] dataSetMemorySegment() { List cases = new ArrayList<>(); // create a bunch of different sig-poly call sites - testCaseSegmentSet(cases, long.class, 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (int) tv)); - testCaseSegmentSet(cases, long.class, (char) 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (char) tv)); - testCaseSegmentSet(cases, long.class, (short) 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (short) tv)); - testCaseSegmentSet(cases, long.class, (byte) 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (byte) tv)); - testCaseSegmentSet(cases, double.class, 1234F, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (float) tv)); + testCaseSegmentSet(cases, JAVA_LONG, 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (int) tv)); + testCaseSegmentSet(cases, JAVA_LONG, (char) 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (char) tv)); + testCaseSegmentSet(cases, JAVA_LONG, (short) 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (short) tv)); + testCaseSegmentSet(cases, JAVA_LONG, (byte) 1234, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (byte) tv)); + testCaseSegmentSet(cases, JAVA_DOUBLE, 1234F, (vh, seg, off, tv) -> vh.set((MemorySegment) seg, off, (float) tv)); return cases.toArray(Object[][]::new); } From 2bc72cc55bbe8acdc77cf3789b13615bd6da4ecf Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Tue, 24 Nov 2026 18:09:37 +0000 Subject: [PATCH 69/95] 8398126: [Leyden] Remove MethodCounters::_aot_preload_code_entry field Reviewed-by: heidinga, iveresov --- src/hotspot/share/ci/ciEnv.cpp | 3 - src/hotspot/share/code/aotCodeCache.cpp | 88 ++++++++++++++++++++--- src/hotspot/share/code/aotCodeCache.hpp | 8 +++ src/hotspot/share/oops/methodCounters.cpp | 26 ------- src/hotspot/share/oops/methodCounters.hpp | 20 +----- 5 files changed, 86 insertions(+), 59 deletions(-) diff --git a/src/hotspot/share/ci/ciEnv.cpp b/src/hotspot/share/ci/ciEnv.cpp index 24ae1ac8282..d3b4bbb0942 100644 --- a/src/hotspot/share/ci/ciEnv.cpp +++ b/src/hotspot/share/ci/ciEnv.cpp @@ -1083,9 +1083,6 @@ void ciEnv::make_code_usable(JavaThread* thread, ciMethod* target, bool aot_prel method->set_code(method, nm); #if INCLUDE_CDS if (aot_preload) { - MethodCounters* mc = method->get_method_counters(thread); - assert(mc != nullptr, "CompileBroker should create MethodCounters if it is missing"); - mc->set_aot_preload_code_entry(aot_code_entry); nm->set_aot_preloaded(true); } #endif diff --git a/src/hotspot/share/code/aotCodeCache.cpp b/src/hotspot/share/code/aotCodeCache.cpp index f7d6eb344e3..0f1b1919ea0 100644 --- a/src/hotspot/share/code/aotCodeCache.cpp +++ b/src/hotspot/share/code/aotCodeCache.cpp @@ -76,6 +76,7 @@ #include "runtime/timerTrace.hpp" #include "utilities/copy.hpp" #include "utilities/ostream.hpp" +#include "utilities/quickSort.hpp" #ifdef COMPILER1 #include "c1/c1_Runtime1.hpp" #include "gc/g1/c1/g1BarrierSetC1.hpp" @@ -979,6 +980,7 @@ bool AOTCodeCache::Config::verify() const { // Header // AOT preload code entries 'AOTCodeEntry preload_entries[preload_entries_count]' array // AOT preload code +// 'uint preload_table[preload_entries_count]' array // AOT entries for adapters, stubs, code 'AOTCodeEntry load_entries[entries_count]' array // AOT adapters, stubs, code // 'uint search_entries[2 * entries_count]' array @@ -1040,10 +1042,16 @@ bool AOTCodeCache::Header::verify(uint load_size) const { return false; } + uint pre_table_offset = preload_table_offset(); + size_t pre_table_end = verify_section(pre_table_offset, preload_count, sizeof(uint), preload_end, "preload table"); + if (pre_table_end == 0) { + return false; + } + // Check normal entries uint normal_offset = entries_offset(); uint normal_count = entries_count(); - size_t normal_end = verify_section(normal_offset, normal_count, entry_size, preload_end, "normal entries"); + size_t normal_end = verify_section(normal_offset, normal_count, entry_size, pre_table_end, "normal entries"); if (normal_end == 0) { return false; } @@ -1632,6 +1640,44 @@ AOTCodeEntry* AOTCodeCache::search_entry(AOTCodeEntry::Kind kind, uint id, uint return nullptr; } +AOTCodeEntry* AOTCodeCache::find_preload_entry(uint method_id) { + assert(is_using_code(), "AOT code caching should be enabled"); + uint count = _load_header->preload_entries_count(); + if (count == 0) { + return nullptr; + } + AOTCodeEntry* preload_entry = (AOTCodeEntry*)addr(_load_header->preload_entries_offset()); + uint* preload_table = (uint*)addr(_load_header->preload_table_offset()); + + // Binary search + uint l = 0; + uint h = count; + while (l < h) { + uint mid = l + ((h - l) >> 1); + uint index = preload_table[mid]; + if (index >= count) { + log_warning(aot, codecache)("Damaged preload table: index %u >= count %u", index, count); + return nullptr; + } + uint id = preload_entry[index].id(); + if (id < method_id) { + l = mid + 1; + } else { + h = mid; + } + } + if (l == count) { + return nullptr; + } + uint index = preload_table[l]; + if (index >= count) { + log_warning(aot, codecache)("Damaged preload table: index %u >= count %u", index, count); + return nullptr; + } + AOTCodeEntry* entry = &preload_entry[index]; + return (entry->for_preload() && entry->id() == method_id) ? entry : nullptr; +} + void AOTCodeCache::invalidate_entry(AOTCodeEntry* entry) { assert(entry!= nullptr, "all entries should be read already"); if (entry->try_set_not_entrant()) { @@ -1677,13 +1723,10 @@ void AOTCodeCache::invalidate_entry(AOTCodeEntry* entry) { // most likely because some dependencies changed during run. // We can still use normal AOT code if preload code is // invalidated - normal AOT code has less restrictions. - MethodCounters* mc = entry->method()->method_counters(); - if (mc != nullptr && mc->aot_preload_code_entry() != nullptr) { - AOTCodeEntry* preload_entry = mc->aot_preload_code_entry(); - if (preload_entry != nullptr) { - assert(preload_entry->for_preload(), "expecting only such entries here"); - invalidate_entry(preload_entry); - } + AOTCodeEntry* preload_entry = find_preload_entry(entry->id()); + if (preload_entry != nullptr) { + assert(preload_entry->for_preload(), "expecting only such entries here"); + invalidate_entry(preload_entry); } } } @@ -1771,10 +1814,11 @@ bool AOTCodeCache::finish_write() { uint header_size = (uint)align_up(sizeof(AOTCodeCache::Header), DATA_ALIGNMENT); uint search_count = code_count * 2; uint search_size = search_count * sizeof(uint); + uint preload_table_size = code_count * sizeof(uint); uint entries_size = (uint)align_up(code_count * sizeof(AOTCodeEntry), DATA_ALIGNMENT); // In bytes // _write_position should include code and strings uint code_alignment = code_count * DATA_ALIGNMENT; // We align_up code size when storing it. - uint total_size = header_size + _write_position + code_alignment + search_size + entries_size; + uint total_size = header_size + _write_position + code_alignment + search_size + preload_table_size + entries_size; assert(total_size < max_aot_code_size(), "AOT Code size (" UINT32_FORMAT " bytes) is greater than AOTCodeMaxSize(" UINT32_FORMAT " bytes).", total_size, max_aot_code_size()); // Allocate in AOT Cache buffer @@ -1832,6 +1876,28 @@ bool AOTCodeCache::finish_write() { } FREE_C_HEAP_ARRAY(preload_sorted); + current = align_up(current, DATA_ALIGNMENT); + uint preload_table_offset = current - start; + if (preload_entries_cnt > 0) { + // Create ordered search table for preload entries [id]. + // The table is used only in AOTCodeCache::invalidate_entry(). + uint* preload_table = NEW_C_HEAP_ARRAY(uint, preload_entries_cnt, mtCode); + for (int i = 0; i < (int)preload_entries_cnt; i++) { + preload_table[i] = i; + } + // Sort preload entry indices based on _id (Method's offset in AOT cache). + QuickSort::sort(preload_table, preload_entries_cnt, + [preload_entries](uint i, uint j) { + uint a = preload_entries[i].id(); + uint b = preload_entries[j].id(); + return a > b ? 1 : a < b ? -1 : 0; + }); + uint sz = preload_entries_cnt * sizeof(uint); + copy_bytes((const char*)preload_table, (address)current, sz); + current += sz; + FREE_C_HEAP_ARRAY(preload_table); + } + // Store the rest of AOTCodeEntry uint entries_count = 0; current = align_up(current, DATA_ALIGNMENT); @@ -1900,7 +1966,7 @@ bool AOTCodeCache::finish_write() { // Finalize header AOTCodeCache::Header* header = (AOTCodeCache::Header*)start; header->init(size, - preload_entries_cnt, preload_entries_offset, + preload_entries_cnt, preload_entries_offset, preload_table_offset, entries_count, new_entries_offset, search_table_offset, (uint)strings_count, strings_offset, stats.entry_count(AOTCodeEntry::Adapter), stats.entry_count(AOTCodeEntry::SharedBlob), @@ -3175,7 +3241,7 @@ void AOTCodeCache::preload_aot_code(TRAPS) { uint entries_offset = _load_header->preload_entries_offset(); // Boundaries of preload code uint low_bound = entries_offset + preload_entries_count * sizeof(AOTCodeEntry); - uint high_bound = _load_header->entries_offset(); // Following section + uint high_bound = _load_header->preload_table_offset(); // Following section AOTCodeEntry* preload_entry = (AOTCodeEntry*)addr(entries_offset); // AOTCodePreloadStop is inclusive uint last_preload_index = MIN2(preload_entries_count - 1, AOTCodePreloadStop); diff --git a/src/hotspot/share/code/aotCodeCache.hpp b/src/hotspot/share/code/aotCodeCache.hpp index 2826ab06279..85c66785456 100644 --- a/src/hotspot/share/code/aotCodeCache.hpp +++ b/src/hotspot/share/code/aotCodeCache.hpp @@ -722,6 +722,7 @@ class AOTCodeCache : public CHeapObj { uint _cache_size; // cache size in bytes uint _preload_entries_count; // entries for pre-loading code uint _preload_entries_offset; + uint _preload_table_offset; // offset of table for looking up an preload entry uint _entries_count; // number of recorded entries uint _entries_offset; // offset of AOTCodeEntry array describing entries uint _search_table_offset; // offset of table for looking up an AOTCodeEntry @@ -744,6 +745,7 @@ class AOTCodeCache : public CHeapObj { public: void init(uint cache_size, uint preload_entries_count, uint preload_entries_offset, + uint preload_table_offset, uint entries_count, uint entries_offset, uint search_table_offset, uint strings_count, uint strings_offset, @@ -755,6 +757,7 @@ class AOTCodeCache : public CHeapObj { _cache_size = cache_size; _preload_entries_count = preload_entries_count; _preload_entries_offset = preload_entries_offset; + _preload_table_offset = preload_table_offset; _entries_count = entries_count; _entries_offset = entries_offset; _search_table_offset = search_table_offset; @@ -774,6 +777,7 @@ class AOTCodeCache : public CHeapObj { uint cache_size() const { return _cache_size; } uint preload_entries_count() const { return _preload_entries_count; } uint preload_entries_offset() const { return _preload_entries_offset; } + uint preload_table_offset() const { return _preload_table_offset; } uint entries_count() const { return _entries_count; } uint entries_offset() const { return _entries_offset; } uint strings_count() const { return _strings_count; } @@ -850,6 +854,9 @@ class AOTCodeCache : public CHeapObj { // @(preload_entries[1]._offset): nmethod preimage for preload entry #1 // ... // + // @preload_table_offset: uint[preload_entries_count] index, sorted by id. + // The id matches AOTCodeEntry::_id. The index point into the preload entries array. + // // @entries_offset: AOTCodeEntry[entries_count] other code (A1/A2/A4/stub/adapter) // Main (non-preload) code array, presented in dump order (arbitrary). // @@ -957,6 +964,7 @@ class AOTCodeCache : public CHeapObj { bool verify_nmethod_entry(AOTCodeEntry* entry, uint id, uint low_bound, uint high_bound); AOTCodeEntry* find_entry(AOTCodeEntry::Kind kind, uint id, uint comp_level = 0); AOTCodeEntry* search_entry(AOTCodeEntry::Kind kind, uint id, uint comp_level); + AOTCodeEntry* find_preload_entry(uint method_id); void invalidate_entry(AOTCodeEntry* entry); static uint get_jvmti_state(); diff --git a/src/hotspot/share/oops/methodCounters.cpp b/src/hotspot/share/oops/methodCounters.cpp index 32f4b9ad20f..5b3126c4c82 100644 --- a/src/hotspot/share/oops/methodCounters.cpp +++ b/src/hotspot/share/oops/methodCounters.cpp @@ -23,7 +23,6 @@ */ #include "cds/cdsConfig.hpp" -#include "code/aotCodeCache.hpp" #include "compiler/compiler_globals.hpp" #include "compiler/compilerOracle.hpp" #include "memory/metaspaceClosure.hpp" @@ -41,9 +40,6 @@ MethodCounters::MethodCounters(const methodHandle& mh) : _highest_comp_level(0), _highest_osr_comp_level(0) { -#if INCLUDE_CDS - set_aot_preload_code_entry(nullptr); -#endif set_interpreter_throwout_count(0); JVMTI_ONLY(clear_number_of_breakpoints()); invocation_counter()->init(); @@ -77,12 +73,6 @@ MethodCounters* MethodCounters::allocate_with_exception(const methodHandle& mh, void MethodCounters::clear_counters() { invocation_counter()->reset(); backedge_counter()->reset(); -#if INCLUDE_CDS - if (aot_preload_code_entry() != nullptr) { - AOTCodeCache::invalidate(aot_preload_code_entry()); - set_aot_preload_code_entry(nullptr); - } -#endif set_interpreter_throwout_count(0); set_prev_time(0); set_prev_event_count(0); @@ -91,28 +81,12 @@ void MethodCounters::clear_counters() { set_highest_osr_comp_level(0); } -#if INCLUDE_CDS -void MethodCounters::deallocate_contents(ClassLoaderData* loader_data) { - if (aot_preload_code_entry() != nullptr) { - AOTCodeCache::invalidate(aot_preload_code_entry()); - set_aot_preload_code_entry(nullptr); - } -} -#endif - void MethodCounters::metaspace_pointers_do(MetaspaceClosure* it) { log_trace(aot, training)("Iter(MethodCounters): %p", this); it->push(&_method); it->push(&_method_training_data); } -#if INCLUDE_CDS -void MethodCounters::set_aot_preload_code_entry(AOTCodeEntry* entry) { - precond(entry == nullptr || entry->for_preload()); - _aot_preload_code_entry = entry; -} -#endif // INCLUDE_CDS - void MethodCounters::print_on(outputStream* st) const { assert(is_methodCounters(), "should be method counters"); st->print("method counters"); diff --git a/src/hotspot/share/oops/methodCounters.hpp b/src/hotspot/share/oops/methodCounters.hpp index a45d9b84ca1..c63f8c92baf 100644 --- a/src/hotspot/share/oops/methodCounters.hpp +++ b/src/hotspot/share/oops/methodCounters.hpp @@ -30,7 +30,6 @@ #include "oops/metadata.hpp" #include "utilities/align.hpp" -class AOTCodeEntry; class MethodTrainingData; class MethodCounters : public Metadata { @@ -49,15 +48,6 @@ class MethodCounters : public Metadata { Method* _method; Metadata* _method_training_data; -#if INCLUDE_CDS - // After JDK-8380476 FIXME: Jamming in a code reference here is a code - // smell. Since access to this value is infrequent, it does not - // need to be a pointer. (See AOTCodeCache::invalidate_entry.) - // Suggestion: Have finish_write build a two-column binary-search - // table in the AOT cache, to map method ID to preload method index. - // Searchable static indexes are a core competency for AOT. - AOTCodeEntry* _aot_preload_code_entry; // AOT Code Cache entry for preload code -#endif jlong _prev_time; // Previous time the rate was acquired float _rate; // Events (invocation and backedge counter increments) per millisecond int _invoke_mask; // per-method Tier0InvokeNotifyFreqLog @@ -81,7 +71,7 @@ class MethodCounters : public Metadata { static MethodCounters* allocate_no_exception(const methodHandle& mh); static MethodCounters* allocate_with_exception(const methodHandle& mh, TRAPS); - void deallocate_contents(ClassLoaderData* loader_data) NOT_CDS_RETURN; + void deallocate_contents(ClassLoaderData* loader_data) {} static int method_counters_size() { return align_up((int)sizeof(MethodCounters), wordSize) / wordSize; @@ -177,14 +167,6 @@ class MethodCounters : public Metadata { return false; } -#if INCLUDE_CDS - void set_aot_preload_code_entry(AOTCodeEntry* entry); - AOTCodeEntry* aot_preload_code_entry() const { - return _aot_preload_code_entry; - } - -#endif - // Printing void print_on (outputStream* st) const; void print_value_on(outputStream* st) const; From 9d6b5b3276837da1b3bb921dfebac52ae0a0beb4 Mon Sep 17 00:00:00 2001 From: Matias Saavedra Silva Date: Tue, 24 Nov 2026 19:23:10 +0000 Subject: [PATCH 70/95] 8354315: Restrict AOT cache functionality when -Djava.system.class.loader is used Reviewed-by: iklam, kvn --- src/hotspot/share/cds/aotMetaspaceRecipes.cpp | 20 ++- src/hotspot/share/cds/aotSystemDictionary.cpp | 15 +- src/hotspot/share/cds/aotSystemDictionary.hpp | 1 + src/hotspot/share/cds/cdsConfig.cpp | 15 ++ src/hotspot/share/cds/cdsConfig.hpp | 2 + src/hotspot/share/cds/filemap.cpp | 5 +- .../share/classfile/systemDictionary.cpp | 5 + .../cds/appcds/AlternateSystemLoaderTest.java | 152 ++++++++++++++++++ .../cds/appcds/SpecifySysLoaderProp.java | 4 +- test/lib/jdk/test/lib/cds/CDSAppTester.java | 17 +- .../jdk/test/lib/cds/SimpleCDSAppTester.java | 13 +- 11 files changed, 238 insertions(+), 11 deletions(-) create mode 100644 test/hotspot/jtreg/runtime/cds/appcds/AlternateSystemLoaderTest.java diff --git a/src/hotspot/share/cds/aotMetaspaceRecipes.cpp b/src/hotspot/share/cds/aotMetaspaceRecipes.cpp index 13694c00b1e..a4d382c9f11 100644 --- a/src/hotspot/share/cds/aotMetaspaceRecipes.cpp +++ b/src/hotspot/share/cds/aotMetaspaceRecipes.cpp @@ -160,6 +160,9 @@ void AOTMetaspaceRecipes::apply_recipes_for_constantpool(JavaThread* current) { int flags = _flags->at(i); if (cp_indices != nullptr) { InstanceKlass* ik = InstanceKlass::cast(_all_klasses->at(i)); + if (AOTSystemDictionary::is_excluded_by_alternate_system_loader(ik)) { + continue; + } if (ik->is_loaded()) { ResourceMark rm(current); ConstantPool* cp = ik->constants(); @@ -182,14 +185,23 @@ void AOTMetaspaceRecipes::apply_recipes_for_constantpool(JavaThread* current) { } void AOTMetaspaceRecipes::load_all_classes(TRAPS) { - Handle class_loader(THREAD, SystemDictionary::java_system_loader()); for (int i = 0; i < _all_klasses->length(); i++) { Klass* k = _all_klasses->at(i); if (k->is_instance_klass()) { InstanceKlass* ik = InstanceKlass::cast(k); + if (AOTSystemDictionary::is_excluded_by_alternate_system_loader(ik)) { + assert(!CDSConfig::is_dumping_aot_linked_classes(), "must be"); + continue; + } if (ik->defined_by_other_loaders()) { AOTSystemDictionary::copy_unregistered_class(THREAD, ik); } else if (!ik->is_hidden()) { + Handle class_loader; + // Avoid loading classes defined in an alternate system loader. Classes + // defined in the boot and platform loaders are safe to be loaded through + // the platform loader, which will delegate accordingly. + class_loader = CDSConfig::using_alternate_system_loader() ? + Handle(THREAD, SystemDictionary::java_platform_loader()) : Handle(THREAD, SystemDictionary::java_system_loader()); Klass* actual = SystemDictionary::resolve_or_fail(ik->name(), class_loader, true, CHECK); if (actual != ik) { ResourceMark rm(THREAD); @@ -210,6 +222,9 @@ void AOTMetaspaceRecipes::link_all_classes(TRAPS) { if (k->is_instance_klass()) { InstanceKlass* ik = InstanceKlass::cast(k); if (!ik->defined_by_other_loaders() && !ik->is_hidden()) { + if (AOTSystemDictionary::is_excluded_by_alternate_system_loader(ik)) { + continue; + } assert(ik->is_loaded(), "must be"); ik->link_class(CHECK); } @@ -224,6 +239,9 @@ void AOTMetaspaceRecipes::initialize_all_safe_classes(TRAPS) { if (k->is_instance_klass()) { InstanceKlass* ik = InstanceKlass::cast(k); if (!ik->defined_by_other_loaders() && !ik->is_hidden()) { + if (AOTSystemDictionary::is_excluded_by_alternate_system_loader(ik)) { + continue; + } assert(ik->is_linked(), "must be"); if (ik->has_aot_safe_initializer() && (flags & WAS_INITED) != 0) { assert(ik->class_loader() == nullptr, "supported only for boot classes for now"); diff --git a/src/hotspot/share/cds/aotSystemDictionary.cpp b/src/hotspot/share/cds/aotSystemDictionary.cpp index a2654d82017..94575474258 100644 --- a/src/hotspot/share/cds/aotSystemDictionary.cpp +++ b/src/hotspot/share/cds/aotSystemDictionary.cpp @@ -412,6 +412,10 @@ bool AOTSystemDictionary::check_self_exclusion(InstanceKlass* k) { const char* AOTSystemDictionary::check_self_exclusion_helper(InstanceKlass* k, bool& log_warning) { assert_lock_strong(DumpTimeTable_lock); + if (AOTSystemDictionary::is_excluded_by_alternate_system_loader(k)) { + return "Defined in built-in app class loader"; + } + if (CDSConfig::is_dumping_with_input_archive() && k->defined_by_other_loaders() && k->in_aot_cache()) { return nullptr; // Do not exclude: unregistered classes are passed from input archive to output archive.. @@ -659,7 +663,9 @@ InstanceKlass* AOTSystemDictionary::find_or_load_shared_class( return nullptr; } - if (SystemDictionary::is_system_class_loader(class_loader()) || + bool is_builtin_app_loader = SystemDictionary::is_system_class_loader(class_loader()) && + !CDSConfig::using_alternate_system_loader(); + if (is_builtin_app_loader || SystemDictionary::is_platform_class_loader(class_loader())) { ClassLoaderData *loader_data = register_loader(class_loader); Dictionary* dictionary = loader_data->dictionary(); @@ -1043,6 +1049,13 @@ void AOTSystemDictionary::set_excluded(InstanceKlass* k) { info->set_excluded(); } +bool AOTSystemDictionary::is_excluded_by_alternate_system_loader(InstanceKlass* ik) { + // When using an alternate system loader, there are no guarantees that + // the loader will delegate to the built-in application loader, so classes + // defined by the built-in app loader should be excluded. + return CDSConfig::using_alternate_system_loader() && ik->defined_by_app_loader(); +} + void AOTSystemDictionary::set_class_has_failed_verification(InstanceKlass* ik) { assert(CDSConfig::is_dumping_archive(), "sanity"); DumpTimeClassInfo* p = get_info(ik); diff --git a/src/hotspot/share/cds/aotSystemDictionary.hpp b/src/hotspot/share/cds/aotSystemDictionary.hpp index 62c7fdc3334..69a37c895a4 100644 --- a/src/hotspot/share/cds/aotSystemDictionary.hpp +++ b/src/hotspot/share/cds/aotSystemDictionary.hpp @@ -286,6 +286,7 @@ class AOTSystemDictionary: public SystemDictionary { static bool is_excluded_class(InstanceKlass* k); static void set_excluded(InstanceKlass* k); static void set_excluded_locked(InstanceKlass* k); + static bool is_excluded_by_alternate_system_loader(InstanceKlass* ik); static void set_from_class_file_load_hook(InstanceKlass* k) NOT_CDS_RETURN; static void log_exclusion(InstanceKlass* k, const char* reason, bool is_warning = false); static void dumptime_classes_do(class MetaspaceClosure* it); diff --git a/src/hotspot/share/cds/cdsConfig.cpp b/src/hotspot/share/cds/cdsConfig.cpp index f9041de9759..13f548a6989 100644 --- a/src/hotspot/share/cds/cdsConfig.cpp +++ b/src/hotspot/share/cds/cdsConfig.cpp @@ -61,6 +61,7 @@ bool CDSConfig::_has_temp_aot_config_file = false; bool CDSConfig::_old_cds_flags_used = false; bool CDSConfig::_new_aot_flags_used = false; bool CDSConfig::_disable_heap_dumping = false; +bool CDSConfig::_using_alternate_system_loader = false; bool CDSConfig::_is_at_aot_safepoint = false; const char* CDSConfig::_default_archive_path = nullptr; @@ -109,6 +110,11 @@ void CDSConfig::ergo_initialize() { AOTMapLogger::ergo_initialize(); + if (using_alternate_system_loader() && (is_dumping_aot_configuration() || is_dumping_aot_cache())) { + log_warning(aot)("AOT optimizations are curtailed because -Djava.system.class.loader=%s is specified", + Arguments::get_property("java.system.class.loader")); + } + setup_compiler_args(); if (is_dumping_full_module_graph()) { @@ -335,6 +341,10 @@ void CDSConfig::check_incompatible_property(const char* key, const char* value) "jdk.module.validation" }; + if (strcmp(key, "java.system.class.loader") == 0) { + _using_alternate_system_loader = true; + } + for (const char* property : incompatible_properties) { if (strcmp(key, property) == 0) { stop_dumping_full_module_graph(); @@ -789,6 +799,11 @@ void CDSConfig::setup_compiler_args() { if (is_dumping_aot_configuration()) { // --- AOT training + if (using_alternate_system_loader()) { + FLAG_SET_ERGO(AOTRecordTraining, false); + FLAG_SET_ERGO(AOTReplayTraining, false); + } + if (!AOTClassLinking) { // Note: is_dumping_aot_linked_classes() is false in training run. disable_profile_and_compiled_code(); return; diff --git a/src/hotspot/share/cds/cdsConfig.hpp b/src/hotspot/share/cds/cdsConfig.hpp index 49a357ad0fe..26605baf640 100644 --- a/src/hotspot/share/cds/cdsConfig.hpp +++ b/src/hotspot/share/cds/cdsConfig.hpp @@ -53,6 +53,7 @@ class CDSConfig : public AllStatic { static bool _old_cds_flags_used; static bool _new_aot_flags_used; static bool _disable_heap_dumping; + static bool _using_alternate_system_loader; // preserve CompileThresholdScaling for A2 compilation static double _aot_compile_threshold_scaling; @@ -97,6 +98,7 @@ class CDSConfig : public AllStatic { static void set_old_cds_flags_used() { CDS_ONLY(_old_cds_flags_used = true); } static bool old_cds_flags_used() { return CDS_ONLY(_old_cds_flags_used) NOT_CDS(false); } static bool new_aot_flags_used() { return CDS_ONLY(_new_aot_flags_used) NOT_CDS(false); } + static bool using_alternate_system_loader() { return CDS_ONLY(_using_alternate_system_loader) NOT_CDS(false); } static void check_internal_module_property(const char* key, const char* value) NOT_CDS_RETURN; static void check_incompatible_property(const char* key, const char* value) NOT_CDS_RETURN; static bool has_unsupported_runtime_module_options() NOT_CDS_RETURN_(false); diff --git a/src/hotspot/share/cds/filemap.cpp b/src/hotspot/share/cds/filemap.cpp index 25d45d3c1af..6fa857a9519 100644 --- a/src/hotspot/share/cds/filemap.cpp +++ b/src/hotspot/share/cds/filemap.cpp @@ -2052,10 +2052,9 @@ bool FileMapHeader::validate() { CDSConfig::type_of_archive_being_loaded()); return false; } - aot_log_warning(aot)("Archived non-system classes are disabled because the " + aot_log_warning(aot)("Archived application classes are disabled because the " "java.system.class.loader property is specified (value = \"%s\"). " - "To use archived non-system classes, this property must not be set", prop); - _has_platform_or_app_classes = false; + "To use archived application classes, this property must not be set", prop); } diff --git a/src/hotspot/share/classfile/systemDictionary.cpp b/src/hotspot/share/classfile/systemDictionary.cpp index 562ea7a64e2..52626f9bf92 100644 --- a/src/hotspot/share/classfile/systemDictionary.cpp +++ b/src/hotspot/share/classfile/systemDictionary.cpp @@ -1196,6 +1196,11 @@ InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik, assert(AtomicAccess::add(&ik->_shared_class_load_count, 1) == 1, "shared class loaded more than once"); Symbol* class_name = ik->name(); + if (AOTSystemDictionary::is_excluded_by_alternate_system_loader(ik)) { + ik->set_shared_loading_failed(); + return nullptr; + } + if (!is_shared_class_visible(class_name, ik, pkg_entry, class_loader)) { ik->set_shared_loading_failed(); return nullptr; diff --git a/test/hotspot/jtreg/runtime/cds/appcds/AlternateSystemLoaderTest.java b/test/hotspot/jtreg/runtime/cds/appcds/AlternateSystemLoaderTest.java new file mode 100644 index 00000000000..3b19945d485 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/AlternateSystemLoaderTest.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +/* + * @test + * @bug 8354315 + * @summary Test restrictions when using an alternate system class loader + * @requires vm.cds + * @library /test/lib + * @build AlternateSystemLoaderTest + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar ExcludedClass$AlternateSystemLoader ExcludedClass + * @run driver AlternateSystemLoaderTest + */ + +import java.net.URL; +import java.net.URLClassLoader; + +import jdk.test.lib.cds.SimpleCDSAppTester; +import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; + +public class AlternateSystemLoaderTest { + + public static void main(String[] args) throws Exception { + final String appName = "ExcludedClass"; + String appJar = ClassFileInstaller.getJarPath("app.jar"); + String logArgs = "-Xlog:cds=debug,aot=debug,class+load,aot+class=debug"; + + SimpleCDSAppTester tester = SimpleCDSAppTester.of("AlternateSystemLoader"); + + // Train with alternate system loader + tester.addVmArgs("-XX:-AOTClassLinking", + logArgs, + "-Djava.system.class.loader=ExcludedClass$AlternateSystemLoader") + .classpath(appJar) + .appCommandLine(appName) + .setTrainingChecker((OutputAnalyzer out) -> { + out.shouldContain("AOT optimizations are curtailed because -Djava.system.class.loader=ExcludedClass$AlternateSystemLoader is specified"); + out.shouldContain("Skipping ExcludedClass: Defined in built-in app class loader"); + }).runAOTTraining(); + + // Assemble without alternate loader + tester.setVmArgs("-XX:-AOTClassLinking", + logArgs) + .setAssemblyChecker((OutputAnalyzer out) -> { + out.shouldNotContain("AOT optimizations are curtailed because -Djava.system.class.loader=ExcludedClass$AlternateSystemLoader is specified"); + out.shouldNotContain("ExcludedClass source: shared objects file"); + out.shouldNotContain("app ExcludedClass"); + }).runAOTAssembly(); + + tester.setProductionChecker((OutputAnalyzer out) -> { + // Do not load any classes defined in the system loader + out.shouldNotContain("ExcludedClass source: shared objects file"); + }).productionRun(); + + // Train without alternate loader + tester.setVmArgs("-XX:-AOTClassLinking", + logArgs) + .classpath(appJar) + .appCommandLine(appName) + .setTrainingChecker((OutputAnalyzer out) -> { + out.shouldNotContain("Skipping ExcludedClass: Defined in built-in app class loader"); + }).runAOTTraining(); + + // Assemble with alternate loader + tester.setVmArgs("-XX:-AOTClassLinking", + logArgs, + "-Djava.system.class.loader=ExcludedClass$AlternateSystemLoader") + .setAssemblyChecker((OutputAnalyzer out) -> { + out.shouldContain("AOT optimizations are curtailed because -Djava.system.class.loader=ExcludedClass$AlternateSystemLoader is specified"); + out.shouldNotContain("ExcludedClass source: shared objects file"); + out.shouldNotContain("app ExcludedClass"); + }).runAOTAssembly(); + tester.setVmArgs("-XX:-AOTClassLinking", + logArgs) + .setProductionChecker((OutputAnalyzer out) -> { + out.shouldNotContain("ExcludedClass source: shared objects file"); + }).productionRun(); + + // Train and assemble without alternate loader + tester.setVmArgs("-XX:-AOTClassLinking", + logArgs) + .classpath(appJar) + .appCommandLine(appName) + .setTrainingChecker((OutputAnalyzer out) -> { + out.shouldNotContain("AOT optimizations are curtailed because -Djava.system.class.loader=ExcludedClass$AlternateSystemLoader is specified"); + out.shouldNotContain("Skipping ExcludedClass: Defined in built-in app class loader"); + }) + .setAssemblyChecker((OutputAnalyzer out) -> { + out.shouldNotContain("AOT optimizations are curtailed because -Djava.system.class.loader=ExcludedClass$AlternateSystemLoader is specified"); + out.shouldContain("ExcludedClass source: shared objects file"); + out.shouldContain("app ExcludedClass"); + }).runAOTTrainingAndAssemblyWorkflow(); + + // Production run with alternate loader + tester.setVmArgs(logArgs, "-Djava.system.class.loader=ExcludedClass$AlternateSystemLoader") + .setProductionChecker((OutputAnalyzer out) -> { + // Do not load any unregistered classes or any classes defined in platform and system loaders + out.shouldNotContain("ExcludedClass source: shared objects file"); + }).productionRun(); + } +} + +class ExcludedClass { + public static void main(String[] args) { + System.out.println("Hello"); + } + + public static class AlternateSystemLoader extends URLClassLoader { + public AlternateSystemLoader(ClassLoader parent) { + super(new URL[] { + ExcludedClass.class.getProtectionDomain().getCodeSource().getLocation() + }, parent); + } + + @Override + public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.equals("ExcludedClass")) { + return super.loadClass(name, resolve); + } + Class c = findLoadedClass(name); + if (c == null) { + c = findClass(name); + } + if (resolve) { + resolveClass(c); + } + return c; + } + } +} diff --git a/test/hotspot/jtreg/runtime/cds/appcds/SpecifySysLoaderProp.java b/test/hotspot/jtreg/runtime/cds/appcds/SpecifySysLoaderProp.java index 8548f76d2ec..dc5cd264a7f 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/SpecifySysLoaderProp.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/SpecifySysLoaderProp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public static void main(String[] args) throws Exception { String jarFileName = "sysloader.jar"; String appJar = TestCommon.getTestJar(jarFileName); TestCommon.testDump(appJar, TestCommon.list("ReportMyLoader")); - String warning = "Archived non-system classes are disabled because the java.system.class.loader property is specified"; + String warning = "Archived application classes are disabled because the java.system.class.loader property is specified"; // (0) Baseline. Do not specify -Djava.system.class.loader diff --git a/test/lib/jdk/test/lib/cds/CDSAppTester.java b/test/lib/jdk/test/lib/cds/CDSAppTester.java index 10e9ad6d02c..d89f5e27bfc 100644 --- a/test/lib/jdk/test/lib/cds/CDSAppTester.java +++ b/test/lib/jdk/test/lib/cds/CDSAppTester.java @@ -24,11 +24,11 @@ package jdk.test.lib.cds; import java.io.File; -import jdk.test.lib.cds.CDSTestUtils; + import jdk.test.lib.Platform; -import jdk.test.lib.process.ProcessTools; -import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.StringArrayUtils; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; import jdk.test.whitebox.WhiteBox; import jtreg.SkippedException; @@ -695,6 +695,17 @@ public boolean isAOTRetraining() { return this.isAOTRetraining; } + public void runAOTTraining() throws Exception { + this.workflow = Workflow.AOT; + recordAOTConfiguration(); + } + + // Ensure Training has already run + public void runAOTAssembly() throws Exception { + this.workflow = Workflow.AOT; + createAOTCache(); + } + // See JEP 483; stop at the assembly run; do not execute production run public void runAOTTrainingAndAssemblyWorkflow() throws Exception { this.workflow = Workflow.AOT; diff --git a/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java b/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java index ab8f85961b6..f3b5452dc90 100644 --- a/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java +++ b/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java @@ -27,9 +27,9 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; +import jdk.test.lib.StringArrayUtils; import jdk.test.lib.cds.CDSAppTester.RunMode; import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.StringArrayUtils; /* * A simpler way to use CDSAppTester. Example: @@ -213,6 +213,17 @@ public SimpleCDSAppTester runAOTWorkflow() throws Exception { return this; } + public SimpleCDSAppTester runAOTTraining() throws Exception { + tester.runAOTTraining(); + return this; + } + + // Ensure Training has already run + public SimpleCDSAppTester runAOTAssembly() throws Exception { + tester.runAOTAssembly(); + return this; + } + public SimpleCDSAppTester runAOTTrainingAndAssemblyWorkflow() throws Exception { tester.runAOTTrainingAndAssemblyWorkflow(); return this; From c3b9d08dfdca3c8c3c6c93b80b7a675401b09673 Mon Sep 17 00:00:00 2001 From: Ekaterina Pavlova Date: Tue, 24 Nov 2026 19:28:28 +0000 Subject: [PATCH 71/95] 8395980: org.openjdk.bench.sun.misc.UnsafeOps.putLongOnHeap crashes with "assert(!is_null(v)) failed: narrow klass value can never be zero" Reviewed-by: alanb, vklang --- test/micro/org/openjdk/bench/sun/misc/UnsafeOps.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/micro/org/openjdk/bench/sun/misc/UnsafeOps.java b/test/micro/org/openjdk/bench/sun/misc/UnsafeOps.java index 02bd357da93..66dcdc31725 100644 --- a/test/micro/org/openjdk/bench/sun/misc/UnsafeOps.java +++ b/test/micro/org/openjdk/bench/sun/misc/UnsafeOps.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,7 +24,7 @@ import java.lang.reflect.Field; import java.util.concurrent.TimeUnit; -import jdk.internal.misc.Unsafe; +import sun.misc.Unsafe; import org.openjdk.jmh.annotations.*; @BenchmarkMode(Mode.AverageTime) @@ -60,6 +60,8 @@ public void setup() throws Exception { valueOffset = U.objectFieldOffset(f); address = U.allocateMemory(1000); + // Ensure getLongOffHeap doesn't read from uninitialized memory. + U.putLong(null, address, 0); } @TearDown @@ -69,12 +71,12 @@ public void finish() { @Benchmark public void putLongOnHeap() { - U.putLong(object, 0, 99); + U.putLong(object, valueOffset, 99); } @Benchmark public long getLongOnHeap() { - return U.getLong(object, 0); + return U.getLong(object, valueOffset); } @Benchmark From 35aa044b3d48a14e5092fcc04d6f8d89784373bd Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Tue, 24 Nov 2026 22:37:21 +0000 Subject: [PATCH 72/95] 8398230: Disable gtest AssemblerX86.validate_other_vm until JDK-8396723 is fixed 8398231: ProblemList java/awt/Focus/ActivateFocusTest.java on linux-x64 8398242: ProblemList jdk/jfr/event/oldobject/TestEmergencyDumpAtOOM.java for linux configs Reviewed-by: dholmes --- test/hotspot/gtest/x86/test_assembler_x86.cpp | 2 +- test/jdk/ProblemList.txt | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/test/hotspot/gtest/x86/test_assembler_x86.cpp b/test/hotspot/gtest/x86/test_assembler_x86.cpp index e79863fadfb..ddd1954f9bf 100644 --- a/test/hotspot/gtest/x86/test_assembler_x86.cpp +++ b/test/hotspot/gtest/x86/test_assembler_x86.cpp @@ -64,7 +64,7 @@ static void asm_check(const uint8_t *insns, const uint8_t *insns1, const unsigne } } -TEST_OTHER_VM(AssemblerX86, validate) { +TEST_OTHER_VM(DISABLED_AssemblerX86, validate) { UseAVX = 3; FlagSetting flag_change_apx(UseAPX, true); VM_Version::set_bmi_cpuFeatures(); diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index ad79e57c903..b16114f5e45 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -319,6 +319,7 @@ java/awt/GraphicsDevice/DisplayModes/UnknownRefrshRateTest.java 8286436 macosx-a java/awt/image/multiresolution/MultiresolutionIconTest.java 8291979 linux-x64,windows-all java/awt/event/SequencedEvent/MultipleContextsFunctionalTest.java 8305061 macosx-x64 sun/java2d/DirectX/OnScreenRenderingResizeTest/OnScreenRenderingResizeTest.java 8301177 linux-x64 +java/awt/Focus/ActivateFocusTest.java 8391069 linux-x64 # Several tests which fail on some hidpi systems/macosx12-aarch64 system java/awt/Window/8159168/SetShapeTest.java 8274106 macosx-aarch64 @@ -567,6 +568,7 @@ jdk/jfr/event/oldobject/TestShenandoah.java 8342951 generic- jdk/jfr/event/runtime/TestResidentSetSizeEvent.java 8309846 aix-ppc64 jdk/jfr/jvm/TestWaste.java 8371630 generic-all jdk/jfr/event/oldobject/TestZ.java 8375615 generic-all +jdk/jfr/event/oldobject/TestEmergencyDumpAtOOM.java 8385942 linux-all ############################################################################ From b0aae5c00a0154854c8c5d4bd17aff311743215b Mon Sep 17 00:00:00 2001 From: Dingli Zhang Date: Wed, 25 Nov 2026 00:33:59 +0000 Subject: [PATCH 73/95] 8398125: RISC-V: Avoid redundant FP spills in C2 GC barrier stubs Reviewed-by: fyang, gcao, yadongwang --- src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp b/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp index 73a61255b92..806251748f7 100644 --- a/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/gc/shared/barrierSetAssembler_riscv.cpp @@ -424,6 +424,9 @@ void SaveLiveRegisters::initialize(BarrierStubC2* stub) { // Remove C-ABI SOE registers and tmp regs _gp_regs -= RegSet::range(x18, x27) + RegSet::of(x2, x5) + RegSet::of(x8, x9); + + // Remove C-ABI SOE fp registers + _fp_regs -= FloatRegSet::range(f18, f27) + FloatRegSet::of(f8, f9); } SaveLiveRegisters::SaveLiveRegisters(MacroAssembler* masm, BarrierStubC2* stub) From 460ff205b86b6894f0d0327155563c937c2bd3d0 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Wed, 25 Nov 2026 02:40:37 +0000 Subject: [PATCH 74/95] 8370945: With Windows LAF, the location of a JMenuItem icon is incorrect Reviewed-by: aivanov, prr, kizune, tr --- .../plaf/windows/WindowsIconFactory.java | 83 +++----- .../swing/plaf/windows/WindowsMenuItemUI.java | 46 ++--- .../plaf/windows/WindowsPopupMenuUI.java | 61 ++++++ .../TestRadioAndCheckMenuItemWithIcon.java | 187 +++++++++++++++--- 4 files changed, 262 insertions(+), 115 deletions(-) diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java index 91c2cbcd61d..b1d532bf6ec 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java @@ -48,6 +48,7 @@ import javax.swing.plaf.ButtonUI; import javax.swing.plaf.UIResource; +import com.sun.java.swing.SwingUtilities3; import sun.swing.MenuItemCheckIconFactory; import sun.swing.SwingUtilities2; @@ -862,13 +863,11 @@ public int getIconWidth() { return lafIcon.getIconWidth(); } Icon icon = getIcon(); - int width = 0; if (icon != null) { - width = icon.getIconWidth() + 2 * OFFSET; - } else { - width = VistaMenuItemCheckIconFactory.getIconWidth(); + int imageOffset = getImageOffset(); + return imageOffset + icon.getIconWidth() + OFFSET; } - return width; + return VistaMenuItemCheckIconFactory.getIconWidth(); } @Override @@ -881,6 +880,8 @@ public void paintIcon(Component c, Graphics g, int x, int y) { assert menuItem == null || c == menuItem; Icon icon = getIcon(); + boolean leftToRight = WindowsGraphicsUtils.isLeftToRight(c); + if (type == JCheckBoxMenuItem.class || type == JRadioButtonMenuItem.class) { AbstractButton b = (AbstractButton) c; @@ -904,63 +905,33 @@ public void paintIcon(Component c, Graphics g, int x, int y) { } XPStyle xp = XPStyle.getXP(); if (xp != null) { - Skin skin = xp.getSkin(c, part); - if (WindowsGraphicsUtils.isLeftToRight(c)) { - if (icon == null || icon.getIconHeight() <= 16) { - skin.paintSkin(g, x + OFFSET, y + OFFSET, state); - } else { - skin.paintSkin(g, x + OFFSET, y + icon.getIconHeight() / 2, state); - } - } else { - if (icon == null) { - skin.paintSkin(g, x + 4 * OFFSET, y + OFFSET, state); - } else { - int ycoord = (icon.getIconHeight() <= 16) - ? y + OFFSET - : (y + icon.getIconHeight() / 2); - if (icon.getIconWidth() <= 8) { - skin.paintSkin(g, x + OFFSET, ycoord, state); - } else if (icon.getIconWidth() <= 16) { - if (menuItem.getText().isEmpty()) { - skin.paintSkin(g, - (menuItem.getAccelerator() != null) - ? (x + 2 * OFFSET) : (x + 3 * OFFSET), - ycoord, state); - } else { - skin.paintSkin(g, - (type == JRadioButtonMenuItem.class) - ? (x + 4 * OFFSET) : (x + 3 * OFFSET), - ycoord, state); - } - } else { - if (menuItem.getText().isEmpty() - || menuItem.getAccelerator() != null) { - skin.paintSkin(g, - (type == JRadioButtonMenuItem.class) - ? (x + 3 * OFFSET) : (x + 4 * OFFSET), - ycoord, state); - } else { - skin.paintSkin(g, x + 7 * OFFSET, - ycoord, state); - } - } - } - } + Skin skin = xp.getSkin(c, backgroundPart); + skin.paintSkin(g, x, y, getIconWidth(), getIconHeight(), backgroundState); + skin = xp.getSkin(c, part); + int markX = leftToRight + ? x + OFFSET + : x + getIconWidth() - OFFSET - skin.getWidth(); + int markY = icon == null || icon.getIconHeight() <= 16 + ? y + OFFSET + : y + icon.getIconHeight() / 2; + skin.paintSkin(g, markX, markY, state); } } } if (icon != null) { - if (WindowsGraphicsUtils.isLeftToRight(c)) { - icon.paintIcon(c, g, - x + VistaMenuItemCheckIconFactory.getIconWidth(), - y + OFFSET); - } else { - icon.paintIcon(c, g, - x - VistaMenuItemCheckIconFactory.getIconWidth() + 2 * OFFSET, - y + OFFSET); - } + int imageOffset = getImageOffset(); + int imageX = leftToRight + ? x + imageOffset + : x + getIconWidth() - imageOffset - icon.getIconWidth(); + icon.paintIcon(c, g, imageX, y + OFFSET); } } + private int getImageOffset() { + return WindowsMenuItemUI.isCheckBulletAndIconPresent(menuItem) + ? VistaMenuItemCheckIconFactory.getIconWidth() + : OFFSET; + } + private static WindowsMenuItemUIAccessor getAccessor( JMenuItem menuItem) { WindowsMenuItemUIAccessor rv = null; diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java index d50540588fb..610b2713282 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java @@ -38,7 +38,7 @@ import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; -import javax.swing.SwingConstants; +import javax.swing.JPopupMenu; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; @@ -160,6 +160,16 @@ protected void paintMenuItem(Graphics g, JComponent c, foreground, defaultTextIconGap); } + static boolean isCheckBulletAndIconPresent(JMenuItem item) { + return item != null + && item.getParent() instanceof JPopupMenu popup + && Boolean.TRUE.equals(popup.getClientProperty( + CHECK_BULLET_AND_ICON_PRESENT)); + } + + static final String CHECK_BULLET_AND_ICON_PRESENT = + "WindowsMenuItemUI.checkBulletAndIconPresent"; + static void paintMenuItem(WindowsMenuItemUIAccessor accessor, Graphics g, JComponent c, Icon checkIcon, Icon arrowIcon, @@ -200,22 +210,6 @@ static void paintMenuItem(WindowsMenuItemUIAccessor accessor, Graphics g, SwingUtilities3.paintCheckIcon(g, lh, lr, holdc, foreground); SwingUtilities3.paintIcon(g, lh, lr, holdc); - if (lh.getCheckIcon() != null && lh.useCheckAndArrow()) { - Rectangle rect = lr.getTextRect(); - if (menuItem.getComponentOrientation().isLeftToRight()) { - if (menuItem.getHorizontalTextPosition() != SwingConstants.LEADING - && menuItem.getHorizontalTextPosition() != SwingConstants.LEFT) { - rect.x += lh.getAfterCheckIconGap(); - } - } else { - if (menuItem.getHorizontalTextPosition() != SwingConstants.LEADING - && menuItem.getHorizontalTextPosition() != SwingConstants.RIGHT) { - rect.x -= lh.getAfterCheckIconGap(); - } - } - - lr.setTextRect(rect); - } if (!lh.getText().isEmpty()) { if (lh.getHtmlView() != null) { // Text is HTML @@ -226,27 +220,9 @@ static void paintMenuItem(WindowsMenuItemUIAccessor accessor, Graphics g, lr.getTextRect(), lh.getText()); } } - if (lh.getCheckIcon() != null && lh.useCheckAndArrow()) { - Rectangle rect = lr.getAccRect(); - if (menuItem.getComponentOrientation().isLeftToRight()) { - rect.x += lh.getAfterCheckIconGap(); - } else { - rect.x -= lh.getAfterCheckIconGap(); - } - lr.setAccRect(rect); - } SwingUtilities3.paintAccText(g, lh, lr, disabledForeground, acceleratorSelectionForeground, acceleratorForeground); - if (lh.getCheckIcon() != null && lh.useCheckAndArrow()) { - Rectangle rect = lr.getArrowRect(); - if (menuItem.getComponentOrientation().isLeftToRight()) { - rect.x += lh.getAfterCheckIconGap(); - } else { - rect.x -= lh.getAfterCheckIconGap(); - } - lr.setArrowRect(rect); - } SwingUtilities3.paintArrowIcon(g, lh, lr, foreground); // Restore original graphics font and color diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java index 1c85cfebd94..6e907a2f920 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java @@ -26,12 +26,18 @@ package com.sun.java.swing.plaf.windows; import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Window; +import javax.swing.BoxLayout; +import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; +import javax.swing.JMenuItem; import javax.swing.JPopupMenu; +import javax.swing.JRadioButtonMenuItem; import javax.swing.JRootPane; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; @@ -42,7 +48,9 @@ import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ComponentUI; +import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicPopupMenuUI; +import javax.swing.plaf.basic.DefaultMenuLayout; import com.sun.java.swing.plaf.windows.TMSchema.Part; import com.sun.java.swing.plaf.windows.TMSchema.State; @@ -50,6 +58,7 @@ import sun.swing.MnemonicHandler; import sun.swing.StringUIClientPropertyKey; +import static com.sun.java.swing.plaf.windows.WindowsMenuItemUI.CHECK_BULLET_AND_ICON_PRESENT; import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET; /** @@ -67,6 +76,21 @@ public static ComponentUI createUI(JComponent c) { return new WindowsPopupMenuUI(); } + @Override + public void installDefaults() { + super.installDefaults(); + if (popupMenu.getLayout() == null + || popupMenu.getLayout() instanceof UIResource) { + popupMenu.setLayout(new WindowsMenuLayout(popupMenu)); + } + } + + @Override + protected void uninstallDefaults() { + popupMenu.putClientProperty(CHECK_BULLET_AND_ICON_PRESENT, null); + super.uninstallDefaults(); + } + @Override public void installListeners() { super.installListeners(); @@ -197,6 +221,43 @@ private static boolean isLeftToRight(JComponent c) { return leftToRight; } + @SuppressWarnings("serial") // Same-version serialization only + private static final class WindowsMenuLayout extends DefaultMenuLayout { + WindowsMenuLayout(JPopupMenu popup) { + super(popup, BoxLayout.Y_AXIS); + } + + @Override + public Dimension preferredLayoutSize(Container target) { + JPopupMenu popup = (JPopupMenu) target; + // Each popup owns its columns. Scan before measuring children, + // without including the contents of any nested popup. + popup.putClientProperty(CHECK_BULLET_AND_ICON_PRESENT, + hasCheckBulletAndIcon(popup)); + return super.preferredLayoutSize(target); + } + + @Override + public void layoutContainer(Container target) { + // Also refresh when layout is requested without a size query. + preferredLayoutSize(target); + super.layoutContainer(target); + } + } + + private static boolean hasCheckBulletAndIcon(JPopupMenu popup) { + for (Component child : popup.getComponents()) { + if (child.isVisible() + && child instanceof JMenuItem item + && (item instanceof JCheckBoxMenuItem + || item instanceof JRadioButtonMenuItem) + && item.getIcon() != null) { + return true; + } + } + return false; + } + @Override public void paint(Graphics g, JComponent c) { XPStyle xp = XPStyle.getXP(); diff --git a/test/jdk/javax/swing/JMenuItem/TestRadioAndCheckMenuItemWithIcon.java b/test/jdk/javax/swing/JMenuItem/TestRadioAndCheckMenuItemWithIcon.java index 15b1c7fe217..0006f7ffdd3 100644 --- a/test/jdk/javax/swing/JMenuItem/TestRadioAndCheckMenuItemWithIcon.java +++ b/test/jdk/javax/swing/JMenuItem/TestRadioAndCheckMenuItemWithIcon.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,18 +22,43 @@ */ /* - * @test - * @bug 8348760 + * @test id=default + * @bug 8348760 8370945 * @summary Verify if RadioButtonMenuItem bullet and * JCheckboxMenuItem checkmark is shown if * JRadioButtonMenuItem and JCheckboxMenuItem * is rendered with ImageIcon in WindowsLookAndFeel - * @requires (os.family == "windows") + * @requires (os.family != "mac") * @library /java/awt/regtesthelpers * @build PassFailJFrame - * @run main/manual TestRadioAndCheckMenuItemWithIcon + * @run main/manual TestRadioAndCheckMenuItemWithIcon system */ +/* + * @test id=metal + * @bug 8348760 8370945 + * @summary Verify if RadioButtonMenuItem bullet and + * JCheckboxMenuItem checkmark is shown if + * JRadioButtonMenuItem and JCheckboxMenuItem + * is rendered with ImageIcon in WindowsLookAndFeel + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestRadioAndCheckMenuItemWithIcon metal + */ + +/* + * @test id=nimbus + * @bug 8348760 8370945 + * @summary Verify if RadioButtonMenuItem bullet and + * JCheckboxMenuItem checkmark is shown if + * JRadioButtonMenuItem and JCheckboxMenuItem + * is rendered with ImageIcon in WindowsLookAndFeel + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestRadioAndCheckMenuItemWithIcon nimbus + */ + + import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; @@ -51,38 +76,138 @@ import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; import javax.swing.UIManager; public class TestRadioAndCheckMenuItemWithIcon { - private static final String INSTRUCTIONS = """ - A top level Menu will be shown. + private static final String INSTRUCTIONS1 = """ +
      +
    • + A window is displayed which has 2 Menu on the menu bar. + One is "Menu" and another "Menu2". +
    • +
      +
    • + Clicking on the "Menu" will show + a JRadioButtonMenuItem group with 3 radiobutton menuitems + and a JCheckBoxMenuItem group with 3 checkbox menuitems + and 2 JMenuItems. +
    • +
      +
    • + First radiobutton menuitem is selected with image icon of a red square. +
      Second radiobutton menuitem is unselected with image icon. +
      Third radiobutton menuItem is unselected without image icon. +
      +
      First checkbox menuitem is selected with image icon. +
      Second checkbox menuitem is unselected with image icon. +
      Third checkbox menuItem is unselected without image icon. +
    • +
      +
    • + Verify that for +
      first JRadioButtonMenuItem with image icon, + a bullet is shown alongside the image icon and +
      for first JCheckBoxMenuItem with image icon + a checkmark is shown alongside the image icon. +
      + Also, verify the JMenuItem "MenuItem2" red square image icon location. +
      The red square images are not all the same size but + their left edges should  all be aligned. +
    • +
      +
    • + If bullet and checkmark is shown in "Menu" + and "MenuItem2" image icon location is aligned, test passes else fails. +
    • +
      +
    • + Clicking on the "Menu2" will show +
      2 JMenuitems with only text +
      1 JMenuItem with an image icon +
      1 JCheckBoxMenuItem menuitem with selected check mark +
      1 JRadioButtonMenuItem with a radio bullet +
      +
    • +
    + """; - Clicking on the Menu will show a - JRadioButtonMenuItem group with 3 radiobutton menuitems - and a JCheckBoxMenuItem group with 3 checkbox menuitems. + private static final String INSTRUCTIONS2 = """ +
      +
    • + The check mark and radio bullet should all be rendered in the 1st column +
      and red square image should be rendered in 2nd column +
      and the menu text of all the menuitems should be aligned. +
    • + If bullet and checkmark is shown in "Menu" + and "MenuItem2" image icon location and + and "Menu2" rendering is as described, test passes else fails. +
    • +
    + + """; - First radiobutton menuitem is selected with imageicon of a red square. - Second radiobutton menuitem is unselected with imageicon. - Third radiobutton menuItem is unselected without imageicon. + private static final String INSTRUCTIONS3 = """ +
      +
    • + The red square imgae, check mark and radio bullet + should all be rendered in the 1st column +
      and the menu text of all the menuitems should be aligned. +
    • + If bullet and checkmark is shown in "Menu" + and "MenuItem2" image icon location and + and "Menu2" rendering is as described, test passes else fails. +
    • +
    + + """; - First checkbox menuitem is selected with imageicon. - Second checkbox menuitem is unselected with imageicon. - Third checkbox menuItem is unselected without imageicon. - Verify that for first JRadioButtonMenuItem with imageicon, - a bullet is shown alongside the imageicon and - for first JCheckBoxMenuItem with imageicon - a checkmark is shown alongside the imageicon. + private static volatile String lafName; - If bullet and checkmark is shown, test passes else fails."""; + private static String getLafClassName(String lafKey) { + final String lafClassName; + switch (lafKey) { + case "metal" -> lafClassName = UIManager.getCrossPlatformLookAndFeelClassName(); + case "system" -> lafClassName = UIManager.getSystemLookAndFeelClassName(); + case "nimbus" -> lafClassName = "javax.swing.plaf.nimbus.NimbusLookAndFeel"; + default -> throw new IllegalArgumentException("Unsupported Look-and-Feel keyword: " + lafKey); + } + return lafClassName; + } public static void main(String[] args) throws Exception { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + if (args.length < 1) { + throw new IllegalArgumentException("Look-and-Feel keyword is required"); + } + + final String lafClassName = getLafClassName(args[0]); + SwingUtilities.invokeAndWait(() -> { + try { + UIManager.setLookAndFeel(lafClassName); + lafName = UIManager.getLookAndFeel().getName(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + + System.out.println("Test for LookAndFeel " + lafClassName); + String instructions = null; + int colWidth = 60; + if (lafName.equals("Windows")) { + instructions = INSTRUCTIONS1 + INSTRUCTIONS3; + } else { + instructions = INSTRUCTIONS1 + INSTRUCTIONS2; + } PassFailJFrame.builder() .title("JRadioButtonMenuItem Instructions") - .instructions(INSTRUCTIONS) - .columns(60) + .instructions("\n" + + "

    Look and Feel: " + + lafName + "

    \n" + + instructions) + .columns(colWidth) + .rows(35) .testUI(TestRadioAndCheckMenuItemWithIcon::doTest) .build() .awaitAndCheck(); @@ -146,6 +271,20 @@ public static JFrame doTest() { JMenuBar menuBar = new JMenuBar(); menuBar.add(topLevel); + JMenu menu2 = new JMenu("Menu2"); + JMenuItem menuItem1 = new JMenuItem("text-only menu item1"); + JMenuItem menuItem2 = new JMenuItem("text-only menu item2"); + JMenuItem menuItem3 = new JMenuItem("text-only menu item2", imageIcon1); + JCheckBoxMenuItem cbMenuItem = new JCheckBoxMenuItem("text-check menu item4"); + cbMenuItem.setSelected(true); + JRadioButtonMenuItem radioMenuItem = new JRadioButtonMenuItem("text-radio menu item5"); + radioMenuItem.setSelected(true); + menu2.add(menuItem1); + menu2.add(menuItem2); + menu2.add(menuItem3); + menu2.add(cbMenuItem); + menu2.add(radioMenuItem); + menuBar.add(menu2); frame.setJMenuBar(menuBar); frame.setSize(300, 300); From 272b7b28270c3615219c76fe772685da413eb544 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Wed, 25 Nov 2026 02:50:46 +0000 Subject: [PATCH 75/95] 8393918: BasicListUI exports literal list text as unescaped HTML when copying Reviewed-by: azvegint, kizune --- .../javax/swing/plaf/basic/BasicListUI.java | 5 ++ .../basic/BasicListTransferHandlerBug.java | 60 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 test/jdk/javax/swing/plaf/basic/BasicListTransferHandlerBug.java diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java index 8eb7f11be3f..947d9c9c9b5 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java @@ -3047,6 +3047,11 @@ protected Transferable createTransferable(JComponent c) { Object obj = values[i]; String val = ((obj == null) ? "" : obj.toString()); plainStr.append(val).append('\n'); + if (val != null && !BasicHTML.isHTMLString(val)) { + val = val.replace("&", "&") + .replace("<", "<") + .replace(">", ">"); + } htmlStr.append("
  • ").append(val).append('\n'); } diff --git a/test/jdk/javax/swing/plaf/basic/BasicListTransferHandlerBug.java b/test/jdk/javax/swing/plaf/basic/BasicListTransferHandlerBug.java new file mode 100644 index 00000000000..e771e97d439 --- /dev/null +++ b/test/jdk/javax/swing/plaf/basic/BasicListTransferHandlerBug.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8393918 + * @summary Verifies BasicListUI exports literal list text + * escaping HTML special characters when copying + * @run main BasicListTransferHandlerBug + */ + +import javax.swing.JList; +import javax.swing.SwingUtilities; +import javax.swing.TransferHandler; +import javax.swing.plaf.basic.BasicListUI; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; + +public class BasicListTransferHandlerBug { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + String actual = null, expected = null; + try { + JList list = new JList<>(new String[]{"literal&"}); + list.setUI(new BasicListUI()); + list.setSelectedIndex(0); + Clipboard clipboard = new Clipboard("test"); + list.getTransferHandler().exportToClipboard(list, clipboard, TransferHandler.COPY); + actual = (String) clipboard.getData( + new DataFlavor("text/html;class=java.lang.String", "HTML")); + expected = "<b>literal</b>&"; + } catch (Exception e) { + throw new RuntimeException(e); + } + if (!actual.contains(expected)) { + throw new RuntimeException("Expected: " + expected + "\nActual: " + actual); + } + }); + } +} From 38c69068d892b0bc14d058318927ad86fafd6942 Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Wed, 25 Nov 2026 03:20:35 +0000 Subject: [PATCH 76/95] 8397671: DepList::at_put does not enforce COW Reviewed-by: kvn, iklam --- src/hotspot/share/oops/trainingData.hpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/hotspot/share/oops/trainingData.hpp b/src/hotspot/share/oops/trainingData.hpp index 854d05a14be..dd3930d0085 100644 --- a/src/hotspot/share/oops/trainingData.hpp +++ b/src/hotspot/share/oops/trainingData.hpp @@ -381,14 +381,11 @@ class TrainingData : public Metadata { return _deps->at(i); } else ShouldNotReachHere(); } - void at_put(int i, E dep) const { + void at_put(int i, E dep) { TrainingDataLocker::assert_locked_or_snapshotted(); assert(i >= 0 && i < length(), "oob"); - if (_deps_dyn != nullptr) { - return _deps_dyn->at_put(i, dep); - } else if (_deps != nullptr) { - return _deps->at_put(i, dep); - } else ShouldNotReachHere(); + copy_on_write_if_necessary(); + _deps_dyn->at_put(i, dep); } bool append_if_missing(E dep) { TrainingDataLocker::assert_can_add(); From 4aeed7137e712a0f0ac83f06d24682b0822c72fa Mon Sep 17 00:00:00 2001 From: Ashutosh Mehra Date: Wed, 25 Nov 2026 03:23:36 +0000 Subject: [PATCH 77/95] 8398134: Test runtime/cds/appcds/StressArchiveUnmapping.java is failing after JDK-8397857 Reviewed-by: kvn, iklam --- .../jtreg/runtime/cds/appcds/StressArchiveUnmapping.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java b/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java index 827b6486f6e..3b442e149f3 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/StressArchiveUnmapping.java @@ -45,15 +45,14 @@ public static void main(String... args) throws Exception { .addVmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:ArchiveRelocationMode=0", "-XX:+AOTStressArchiveUnmapping", - "-Xlog:aot,class+path") + "-Xlog:aot,class+path", + "-Xlog:aot=debug") .appCommandLine("StressArchiveUnmappingApp") .setAssemblyChecker((OutputAnalyzer out) -> { - out.shouldContain("Simulate mapping failure to stress test unmapping") - .shouldContain("Try to map archive(s) at an alternative address"); + out.shouldContain("Try to map archive(s) at an alternative address"); }) .setProductionChecker((OutputAnalyzer out) -> { - out.shouldContain("Simulate mapping failure to stress test unmapping") - .shouldContain("Try to map archive(s) at an alternative address"); + out.shouldContain("Try to map archive(s) at an alternative address"); }) .runAOTWorkflow(); } From 551316e94f9cb090e541ba844cce1d121382b5f6 Mon Sep 17 00:00:00 2001 From: Ioi Lam Date: Wed, 25 Nov 2026 05:10:13 +0000 Subject: [PATCH 78/95] 8397866: Classes loaded from AddToBootstrapClassLoaderSearch should be exclude from AOT Co-authored-by: Jason Cheng Reviewed-by: kvn, adinn --- src/hotspot/share/cds/aotClassLocation.cpp | 15 +- src/hotspot/share/cds/aotClassLocation.hpp | 2 + src/hotspot/share/runtime/arguments.cpp | 3 + .../appcds/aotCache/AgentBootClassPath.java | 149 ++++++++++++++++++ 4 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java diff --git a/src/hotspot/share/cds/aotClassLocation.cpp b/src/hotspot/share/cds/aotClassLocation.cpp index d5d05e8bcad..aa6ecf4b1c2 100644 --- a/src/hotspot/share/cds/aotClassLocation.cpp +++ b/src/hotspot/share/cds/aotClassLocation.cpp @@ -51,6 +51,8 @@ #include #include +static char* _boot_classpath = nullptr; + Array* AOTClassLocationConfig::_dumptime_jar_files = nullptr; AOTClassLocationConfig* AOTClassLocationConfig::_dumptime_instance = nullptr; const AOTClassLocationConfig* AOTClassLocationConfig::_runtime_instance = nullptr; @@ -108,9 +110,11 @@ class ClassLocationStream { class BootCpClassLocationStream : public ClassLocationStream { public: BootCpClassLocationStream() : ClassLocationStream() { - // Arguments::get_boot_class_path() contains $JAVA_HOME/lib/modules, but we treat that separately - for (const char* bootcp = Arguments::get_boot_class_path(); *bootcp != '\0'; ++bootcp) { + assert(_boot_classpath, "must have been initialized"); + for (const char* bootcp = _boot_classpath; *bootcp != '\0'; ++bootcp) { if (*bootcp == *os::path_separator()) { + // Note: this skips the very first element of _boot_classpath ($JAVA_HOME/lib/modules) + // which is not handled by AllClassLocationStreams. ++bootcp; add_paths_in_classpath(bootcp); break; @@ -468,6 +472,13 @@ bool AOTClassLocation::check(const char* runtime_path, bool has_aot_linked_class return true; } +// Save a copy of the bootclasspath before it's (potentially) appended to by JVMTI. +// As a result, we will exclude all classes loaded from the bootclasspath(s) of the +// agent(s). Note that we also exclude all app classes loaded from the agent JARs. +void AOTClassLocationConfig::init_boot_classpath() { + _boot_classpath = os::strdup_check_oom(Arguments::get_boot_class_path(), mtClassShared); +} + inline unsigned cstring_hash(const char* const& s) { return java_lang_String::hash_code((const jbyte*)s, checked_cast(strlen(s))); } diff --git a/src/hotspot/share/cds/aotClassLocation.hpp b/src/hotspot/share/cds/aotClassLocation.hpp index 15408395ca0..34d21dcfbc6 100644 --- a/src/hotspot/share/cds/aotClassLocation.hpp +++ b/src/hotspot/share/cds/aotClassLocation.hpp @@ -250,6 +250,8 @@ class AOTClassLocationConfig : public CHeapObj { return _class_locations->length(); } + static void init_boot_classpath() NOT_CDS_RETURN; + const AOTClassLocation* class_location_at(int index) const; int get_module_shared_path_index(Symbol* location) const; diff --git a/src/hotspot/share/runtime/arguments.cpp b/src/hotspot/share/runtime/arguments.cpp index 0594e946e36..d5a8982ccec 100644 --- a/src/hotspot/share/runtime/arguments.cpp +++ b/src/hotspot/share/runtime/arguments.cpp @@ -22,6 +22,7 @@ * */ +#include "cds/aotClassLocation.hpp" #include "cds/aotLogging.hpp" #include "cds/cds_globals.hpp" #include "cds/cdsConfig.hpp" @@ -3436,6 +3437,8 @@ jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) { Arguments::print_on(&st); } + AOTClassLocationConfig::init_boot_classpath(); + return JNI_OK; } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java new file mode 100644 index 00000000000..fa2e14725e6 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +/* + * @test + * @summary The boot classpath(s) appended by the Boot-Class-Path attribute of a -javaagent + * JAR in the training run, as well as classes loaded from there, must be excluded from + * the AOT configuration file. + * @bug 8397866 + * @requires vm.cds.supports.aot.class.linking + * @requires vm.jvmti + * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds/test-classes + * @build AgentBootClassPath Child Super + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar AgentBootClassPathApp Super Child + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar boot1.jar AgentBootClassPathBoot1 + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar boot2.jar AgentBootClassPathBoot2 Super + * @run driver AgentBootClassPath AOT + */ + +import jdk.test.lib.cds.CDSAppTester; +import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; + +public class AgentBootClassPath { + static final String appJar = ClassFileInstaller.getJarPath("app.jar"); + static final String boot1Jar = ClassFileInstaller.getJarPath("boot1.jar"); + static final String agentJar = "agent.jar"; + static final String mainClass = "AgentBootClassPathApp"; + + public static void main(String[] args) throws Exception { + // The agent appends boot2.jar to the boot classpath in its OnLoad phase. + // The Boot-Class-Path attribute is relative to the location of the agent JAR. + String manifest = "Premain-Class: AgentBootClassPathAgent\n" + + "Boot-Class-Path: boot2.jar\n"; + ClassFileInstaller.writeJar(agentJar, + ClassFileInstaller.Manifest.fromString(manifest), + "AgentBootClassPathAgent"); + + new Tester().run(args); + } + + static class Tester extends CDSAppTester { + public Tester() { + super(mainClass); + } + + @Override + public String classpath(RunMode runMode) { + return appJar; + } + + @Override + public String[] vmArgs(RunMode runMode) { + // The training JVM's boot classpath append is boot1.jar:boot2.jar. + // The child JVM must see the same boot classpath append, in the same order. + return new String[] { + "-Xbootclasspath/a:" + boot1Jar, + "-javaagent:" + agentJar, + "-Xlog:class+load,class+path,aot", + }; + } + + @Override + public String[] appCommandLine(RunMode runMode) { + return new String[] { + mainClass, + }; + } + + @Override + public void checkExecution(OutputAnalyzer out, RunMode runMode) { + if (runMode == RunMode.TRAINING) { + out.shouldContain("Skipping AgentBootClassPathBoot2: Unsupported location"); // from AddToBootstrapClassLoaderSearch + out.shouldContain("Skipping AgentBootClassPathAgent: Unsupported location"); // from AddToSystemClassLoaderSearch + out.shouldContain("Skipping Super: Unsupported location"); // from AddToBootstrapClassLoaderSearch + out.shouldContain("Skipping Child: super Super is excluded"); + } + if (runMode == RunMode.ASSEMBLY) { + // Make sure boot2.jar is not included in the classpath(s) of the config file + out.shouldContain("Reading classpath(s) from AgentBootClassPathApp.aotconfig (size = 3)"); + out.shouldMatch("class,path.*boot.* .1. = .*/boot1.jar"); + out.shouldMatch("class,path.*app.* .2. = .*/app.jar"); + } + if (runMode.isApplicationExecuted()) { + out.shouldContain("AgentBootClassPathBoot1 loader = null"); + out.shouldContain("AgentBootClassPathBoot2 loader = null"); + } + if (runMode.isProductionRun()) { + out.shouldMatch("AgentBootClassPathBoot2 source: .*boot2.jar"); + out.shouldMatch("AgentBootClassPathAgent source: .*agent.jar"); + out.shouldContain("AgentBootClassPathBoot1 source: shared objects file"); + out.shouldContain("AgentBootClassPathApp source: shared objects file"); + out.shouldMatch("Super source: .*boot2.jar"); + out.shouldMatch("Child source: .*app.jar"); + } + } + } +} + +class AgentBootClassPathAgent { + public static void premain(String args, java.lang.instrument.Instrumentation inst) { + System.out.println("AgentBootClassPathAgent.premain"); + } +} + +class AgentBootClassPathApp { + public static void main(String args[]) throws Exception { + for (String name : new String[] {"AgentBootClassPathBoot1", "AgentBootClassPathBoot2"}) { + Class c = Class.forName(name); + System.out.println(name + " loader = " + c.getClassLoader()); + if (c.getClassLoader() != null) { + throw new RuntimeException(name + " should be loaded by the boot loader"); + } + } + Class c = Class.forName("Child"); + Class s = Class.forName("Super"); + if (c.getClassLoader() != AgentBootClassPathApp.class.getClassLoader()) { + throw new RuntimeException("Child should be loaded by the app loader"); + } + if (s.getClassLoader() != null) { + throw new RuntimeException("Super should be loaded by the boot loader (shadowed by the agent's Boot-Class-Path)"); + } + } +} + +class AgentBootClassPathBoot1 {} + +class AgentBootClassPathBoot2 {} From a96f45327177f8fee983af19cc8ba9aa44839bae Mon Sep 17 00:00:00 2001 From: April Ivy Date: Wed, 25 Nov 2026 06:58:04 +0000 Subject: [PATCH 79/95] 8396021: C2: Missed Ideal optimization opportunity in PhaseIterGVN for OrI, OrL, AddI, AddL (optimization to RotateRight) Reviewed-by: chagedorn, epeter --- src/hotspot/share/opto/phaseX.cpp | 25 +++- .../igvn/TestMissingRotateIdealization.java | 139 ++++++++++++++++++ 2 files changed, 159 insertions(+), 5 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/c2/igvn/TestMissingRotateIdealization.java diff --git a/src/hotspot/share/opto/phaseX.cpp b/src/hotspot/share/opto/phaseX.cpp index 70c1d9d2ccc..b0f7aeb6c87 100644 --- a/src/hotspot/share/opto/phaseX.cpp +++ b/src/hotspot/share/opto/phaseX.cpp @@ -2592,18 +2592,33 @@ void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_ return u->Opcode() == Op_AndI || u->Opcode() == Op_AndL; }); } - // OrI/LNode::Ideal converts shift/or patterns into rotates, which - // needs to trigger when x and y common. - // e.g. (x << 14) | (y >>> 18) + // OrI/LNode::Ideal and AddNode::IdealIL convert shift/or and shift/add + // patterns into rotates, which needs to trigger when x and y common. + // e.g. (x << 14) | (y >>> 18), (x >>> 16) + (y << 16) if (use_op == Op_LShiftI || use_op == Op_URShiftI) { add_users_to_worklist_if(worklist, use, [](Node* u) { - return u->Opcode() == Op_OrI; + return u->Opcode() == Op_OrI || u->Opcode() == Op_AddI; }); } else if (use_op == Op_LShiftL || use_op == Op_URShiftL) { add_users_to_worklist_if(worklist, use, [](Node* u) { - return u->Opcode() == Op_OrL; + return u->Opcode() == Op_OrL || u->Opcode() == Op_AddL; }); } + // rotate_shift also matches a variable shift count of the form + // ({0|32|64} - s), so a changed SubI input can enable a rotate two hops up. + // pattern: n -> use=SubI -> shift (count input) -> or + if (use_op == Op_SubI) { + for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) { + Node* shift = use->fast_out(i); + const int shift_op = shift->Opcode(); + if ((shift_op == Op_LShiftI || shift_op == Op_URShiftI || + shift_op == Op_LShiftL || shift_op == Op_URShiftL) && shift->in(2) == use) { + add_users_to_worklist_if(worklist, shift, [](Node* u) { + return u->Opcode() == Op_OrI || u->Opcode() == Op_OrL; + }); + } + } + } // If changed LShift inputs, check CompressBits and ExpandBits users for // compress(x, 1 << n), compress(x, -1 << n), // expand(x, 1 << n), expand(x, -1 << n) optimizations. diff --git a/test/hotspot/jtreg/compiler/c2/igvn/TestMissingRotateIdealization.java b/test/hotspot/jtreg/compiler/c2/igvn/TestMissingRotateIdealization.java new file mode 100644 index 00000000000..0cb44c5bacc --- /dev/null +++ b/test/hotspot/jtreg/compiler/c2/igvn/TestMissingRotateIdealization.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package compiler.c2.igvn; + +import compiler.lib.ir_framework.*; +import java.util.Random; +import jdk.test.lib.Asserts; +import jdk.test.lib.Utils; + +/* + * @test + * @bug 8396021 + * @key randomness + * @summary AddNode::IdealIL and OrI/OrLNode::Ideal turn shift/add and shift/or + * patterns into rotates. When an input of the shifts, or of a + * (0 - s) shift count, changes, the Add/Or must be put back on the + * IGVN worklist. Use -XX:VerifyIterativeGVN=1110 to catch missing + * optimizations. + * @library /test/lib / + * @run driver ${test.main.class} + */ +public class TestMissingRotateIdealization { + private static final Random RANDOM = Utils.getRandomInstance(); + + public static void main(String[] args) { + TestFramework.runWithFlags("-XX:+IgnoreUnrecognizedVMOptions", + "-XX:VerifyIterativeGVN=1110"); + } + + @Run(test = {"testAddI", "testAddL", "testOrI", "testOrL", "testOrIRotateLeft", "testOrLRotateLeft"}) + public void runTests() { + int xi = RANDOM.nextInt(); + long xl = RANDOM.nextLong(); + int s = RANDOM.nextInt(); + + Asserts.assertEQ(Integer.rotateRight(xi, 16), testAddI(xi)); + Asserts.assertEQ(Long.rotateRight(xl, 16), testAddL(xl)); + Asserts.assertEQ(Integer.rotateRight(xi, s), testOrI(xi, s)); + Asserts.assertEQ(Long.rotateRight(xl, s), testOrL(xl, s)); + Asserts.assertEQ(Integer.rotateLeft(xi, s), testOrIRotateLeft(xi, s)); + Asserts.assertEQ(Long.rotateLeft(xl, s), testOrLRotateLeft(xl, s)); + } + + // delayedOne is only known to be 1 after loop opts, so the shifted value + // becomes x late: n -> shift -> add + @Test + @IR(failOn = {IRNode.ROTATE_LEFT, IRNode.ROTATE_RIGHT}, phase = CompilePhase.BEFORE_LOOP_OPTS) + @IR(failOn = IRNode.ADD_I, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatformOr = {"x64", "true", "aarch64", "true"}) + @IR(failOn = IRNode.ADD_I, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatform = {"riscv64", "true"}, applyIfCPUFeature = {"zbb", "true"}) + static int testAddI(int x) { + int delayedOne = 100; + for (int i = 0; i < 99; i++) { delayedOne--; } + return (x >>> 16) + ((x * delayedOne) << 16); + } + + @Test + @IR(failOn = {IRNode.ROTATE_LEFT, IRNode.ROTATE_RIGHT}, phase = CompilePhase.BEFORE_LOOP_OPTS) + @IR(failOn = IRNode.ADD_L, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatformOr = {"x64", "true", "aarch64", "true"}) + @IR(failOn = IRNode.ADD_L, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatform = {"riscv64", "true"}, applyIfCPUFeature = {"zbb", "true"}) + static long testAddL(long x) { + int delayedOne = 100; + for (int i = 0; i < 99; i++) { delayedOne--; } + return (x >>> 16) + ((x * delayedOne) << 48); + } + + // the count of one shift becomes (0 - s) late: n -> SubI -> shift -> or + @Test + @IR(failOn = {IRNode.ROTATE_LEFT, IRNode.ROTATE_RIGHT}, phase = CompilePhase.BEFORE_LOOP_OPTS) + @IR(failOn = IRNode.OR_I, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatformOr = {"x64", "true", "aarch64", "true"}) + @IR(failOn = IRNode.OR_I, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatform = {"riscv64", "true"}, applyIfCPUFeature = {"zbb", "true"}) + static int testOrI(int x, int s) { + int delayedOne = 100; + for (int i = 0; i < 99; i++) { delayedOne--; } + return (x >>> s) | (x << -(s * delayedOne)); + } + + @Test + @IR(failOn = {IRNode.ROTATE_LEFT, IRNode.ROTATE_RIGHT}, phase = CompilePhase.BEFORE_LOOP_OPTS) + @IR(failOn = IRNode.OR_L, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatformOr = {"x64", "true", "aarch64", "true"}) + @IR(failOn = IRNode.OR_L, counts = {IRNode.ROTATE_RIGHT, "1"}, + applyIfPlatform = {"riscv64", "true"}, applyIfCPUFeature = {"zbb", "true"}) + static long testOrL(long x, int s) { + int delayedOne = 100; + for (int i = 0; i < 99; i++) { delayedOne--; } + return (x >>> s) | (x << -(s * delayedOne)); + } + + @Test + @IR(failOn = {IRNode.ROTATE_LEFT, IRNode.ROTATE_RIGHT}, phase = CompilePhase.BEFORE_LOOP_OPTS) + @IR(failOn = IRNode.OR_I, counts = {IRNode.ROTATE_LEFT, "1"}, + applyIfPlatformOr = {"x64", "true", "aarch64", "true"}) + @IR(failOn = IRNode.OR_I, counts = {IRNode.ROTATE_LEFT, "1"}, + applyIfPlatform = {"riscv64", "true"}, applyIfCPUFeature = {"zbb", "true"}) + static int testOrIRotateLeft(int x, int s) { + int delayedOne = 100; + for (int i = 0; i < 99; i++) { delayedOne--; } + return (x << s) | (x >>> -(s * delayedOne)); + } + + @Test + @IR(failOn = {IRNode.ROTATE_LEFT, IRNode.ROTATE_RIGHT}, phase = CompilePhase.BEFORE_LOOP_OPTS) + @IR(failOn = IRNode.OR_L, counts = {IRNode.ROTATE_LEFT, "1"}, + applyIfPlatformOr = {"x64", "true", "aarch64", "true"}) + @IR(failOn = IRNode.OR_L, counts = {IRNode.ROTATE_LEFT, "1"}, + applyIfPlatform = {"riscv64", "true"}, applyIfCPUFeature = {"zbb", "true"}) + static long testOrLRotateLeft(long x, int s) { + int delayedOne = 100; + for (int i = 0; i < 99; i++) { delayedOne--; } + return (x << s) | (x >>> -(s * delayedOne)); + } +} From d419eefbf68a174d83efcbe23fbaa9cd7c56872c Mon Sep 17 00:00:00 2001 From: Per Minborg Date: Wed, 25 Nov 2026 07:46:33 +0000 Subject: [PATCH 80/95] 8397840: Implement JEP 547: Lazy Constants (Fourth Preview) Reviewed-by: mcimadamore --- .../share/classes/jdk/internal/javac/PreviewFeature.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java b/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java index 9f4cb9f370e..aca7c68d837 100644 --- a/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java +++ b/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java @@ -74,7 +74,7 @@ public enum Feature { @JEP(number=401, title="Value Classes and Objects", status = "Preview") VALUE_OBJECTS, STRUCTURED_CONCURRENCY, - @JEP(number = 531, title = "Lazy Constants", status = "Third Preview") + @JEP(number = 547, title = "Lazy Constants", status = "Fourth Preview") LAZY_CONSTANTS, /** * Indicates a preview API exists to allow access to the environment From 961e1065665521152f19f478506c498ef9bc8b46 Mon Sep 17 00:00:00 2001 From: Gui Cao Date: Wed, 25 Nov 2026 08:43:02 +0000 Subject: [PATCH 81/95] 8398135: RISC-V: Use sh1add for pointer updates in RVV element comparison Reviewed-by: fyang, ayang, dzhang --- src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp index 40fa846743f..cfd5bfb6362 100644 --- a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp @@ -2882,11 +2882,8 @@ void C2_MacroAssembler::element_compare(Register a1, Register a2, Register resul vfirst_m(tmp2, vrs); bgez(tmp2, DONE); sub(cnt, cnt, tmp1); - if (!islatin) { - slli(tmp1, tmp1, 1); // get byte counts - } - add(a1, a1, tmp1); - add(a2, a2, tmp1); + shift_left_add(a1, tmp1, a1, islatin ? 0 : 1, tmp2); + shift_left_add(a2, tmp1, a2, islatin ? 0 : 1, tmp2); bnez(cnt, loop); mv(result, true); From 58fde1e14b849ba5bf3543c022c06682f811159f Mon Sep 17 00:00:00 2001 From: Albert Mingkun Yang Date: Wed, 25 Nov 2026 08:47:26 +0000 Subject: [PATCH 82/95] 8397997: AArch64: Emit one instruction for masked widening with a non-negative immediate Reviewed-by: aph, adinn --- src/hotspot/cpu/aarch64/aarch64.ad | 24 ++++- src/hotspot/cpu/aarch64/aarch64_ad.m4 | 12 ++- .../c2/aarch64/TestMaskedWidening.java | 93 +++++++++++++++++++ 3 files changed, 119 insertions(+), 10 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/c2/aarch64/TestMaskedWidening.java diff --git a/src/hotspot/cpu/aarch64/aarch64.ad b/src/hotspot/cpu/aarch64/aarch64.ad index a784305320a..cc53a806602 100644 --- a/src/hotspot/cpu/aarch64/aarch64.ad +++ b/src/hotspot/cpu/aarch64/aarch64.ad @@ -4473,6 +4473,18 @@ operand immILog() interface(CONST_INTER); %} +// 32-bit logical immediate with the sign bit clear. +operand immILogPos() +%{ + predicate(n->get_int() > 0 + && Assembler::operand_valid_for_logical_immediate(/*is32*/true, (uint64_t)n->get_int())); + match(ConI); + + op_cost(0); + format %{ %} + interface(CONST_INTER); +%} + // Integer operands 64 bit // 64 bit immediate operand immL() @@ -11763,16 +11775,18 @@ instruct ubfizLConvL2Ix(iRegINoSp dst, iRegL src, immI lshift, immL_positive_bit // This pattern is automatically generated from aarch64_ad.m4 // DO NOT EDIT ANYTHING IN THIS SECTION OF THE FILE -// Can skip int2long conversions after AND with small bitmask -instruct ubfizIConvI2LAndI(iRegLNoSp dst, iRegI src, immI_bitmask msk) +// AND with a positive immediate. The result will be positive so no +// sign extension is needed, and the implicit zero extension of `andw` +// zeroes the high 32 bits. +instruct convI2L_andI_reg_imm(iRegLNoSp dst, iRegIorL2I src, immILogPos msk) %{ match(Set dst (ConvI2L (AndI src msk))); ins_cost(INSN_COST); - format %{ "ubfiz $dst, $src, 0, exact_log2($msk + 1) " %} + format %{ "and $dst, $src, $msk\t# int -> long" %} ins_encode %{ - __ ubfiz(as_Register($dst$$reg), as_Register($src$$reg), 0, exact_log2($msk$$constant + 1)); + __ andw(as_Register($dst$$reg), as_Register($src$$reg), (uint64_t)($msk$$constant)); %} - ins_pipe(ialu_reg_shift); + ins_pipe(ialu_reg_imm); %} diff --git a/src/hotspot/cpu/aarch64/aarch64_ad.m4 b/src/hotspot/cpu/aarch64/aarch64_ad.m4 index f56e3836ab7..cba0a4a8249 100644 --- a/src/hotspot/cpu/aarch64/aarch64_ad.m4 +++ b/src/hotspot/cpu/aarch64/aarch64_ad.m4 @@ -325,16 +325,18 @@ BFX1_INSN(L, I, L2I, exact_log2_long, get_long, 31, 31, immL_positive_bitm // This pattern is automatically generated from aarch64_ad.m4 // DO NOT EDIT ANYTHING IN THIS SECTION OF THE FILE -// Can skip int2long conversions after AND with small bitmask -instruct ubfizIConvI2LAndI(iRegLNoSp dst, iRegI src, immI_bitmask msk) +// AND with a positive immediate. The result will be positive so no +// sign extension is needed, and the implicit zero extension of `andw` +// zeroes the high 32 bits. +instruct convI2L_andI_reg_imm(iRegLNoSp dst, iRegIorL2I src, immILogPos msk) %{ match(Set dst (ConvI2L (AndI src msk))); ins_cost(INSN_COST); - format %{ "ubfiz $dst, $src, 0, exact_log2($msk + 1) " %} + format %{ "and $dst, $src, $msk\t# int -> long" %} ins_encode %{ - __ ubfiz(as_Register($dst$$reg), as_Register($src$$reg), 0, exact_log2($msk$$constant + 1)); + __ andw(as_Register($dst$$reg), as_Register($src$$reg), (uint64_t)($msk$$constant)); %} - ins_pipe(ialu_reg_shift); + ins_pipe(ialu_reg_imm); %} diff --git a/test/hotspot/jtreg/compiler/c2/aarch64/TestMaskedWidening.java b/test/hotspot/jtreg/compiler/c2/aarch64/TestMaskedWidening.java new file mode 100644 index 00000000000..929c0f2dfff --- /dev/null +++ b/test/hotspot/jtreg/compiler/c2/aarch64/TestMaskedWidening.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2026, Alibaba Group Holding Limited. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Test that the int-to-long widening of a masked int is folded into the AND when the mask is non-negative + * @library /test/lib / + * @requires os.arch == "aarch64" & vm.compiler2.enabled + * @run driver compiler.c2.aarch64.TestMaskedWidening + */ + +package compiler.c2.aarch64; + +import compiler.lib.ir_framework.CompilePhase; +import compiler.lib.ir_framework.DontCompile; +import compiler.lib.ir_framework.IR; +import compiler.lib.ir_framework.Run; +import compiler.lib.ir_framework.Test; +import compiler.lib.ir_framework.TestFramework; +import jdk.test.lib.Asserts; + +public class TestMaskedWidening { + private static final String I2L = "convI2L_reg_reg"; + private static final String I2L_ANDI = "convI2L_andI_reg_imm"; + + private static final long[] VALUES = { + 0L, 1L, -1L, Long.MIN_VALUE, Long.MAX_VALUE, + 0x1234_5678_9abc_def0L, 0xffff_ffff_8000_0000L + }; + + public static void main(String[] args) { + TestFramework.run(); + } + + @Test + @IR(counts = {I2L_ANDI, "1"}, failOn = {I2L}, phase = CompilePhase.FINAL_CODE) + static long maskImmediate(long value) { + return (int) value & 0x7ff; + } + + @Test + @IR(counts = {I2L_ANDI, "1"}, failOn = {I2L}, phase = CompilePhase.FINAL_CODE) + static long maskNonContiguousImmediate(long value) { + return (int) value & 0x0f0f0f0f; + } + + @Test + @IR(counts = {I2L, "1"}, failOn = {I2L_ANDI}, phase = CompilePhase.FINAL_CODE) + static long maskNegativeImmediate(long value) { + return (int) value & -8; + } + + @Test + @IR(counts = {I2L, "1"}, failOn = {I2L_ANDI}, phase = CompilePhase.FINAL_CODE) + static long maskOutOfRangeImmediate(long value) { + return (int) value & 0x12345678; + } + + @Run(test = {"maskImmediate", "maskNonContiguousImmediate", "maskNegativeImmediate", "maskOutOfRangeImmediate"}) + static void runTests() { + for (long value : VALUES) { + verify(value); + } + } + + @DontCompile + static void verify(long value) { + Asserts.assertEQ(maskImmediate(value), (long) ((int) value & 0x7ff)); + Asserts.assertEQ(maskNonContiguousImmediate(value), (long) ((int) value & 0x0f0f0f0f)); + Asserts.assertEQ(maskNegativeImmediate(value), (long) ((int) value & -8)); + Asserts.assertEQ(maskOutOfRangeImmediate(value), (long) ((int) value & 0x12345678)); + } +} \ No newline at end of file From ea7709c22f7499048ab7bb1f7c8b139450f7abf6 Mon Sep 17 00:00:00 2001 From: Timofei Fedotov Date: Wed, 25 Nov 2026 09:24:11 +0000 Subject: [PATCH 83/95] 8397415: Splash JPEG decoder may retain freed frame storage after an allocation failure Reviewed-by: jdv, asemenov --- .../share/native/libsplashscreen/splashscreen_gif.c | 11 +++++++---- .../share/native/libsplashscreen/splashscreen_impl.h | 9 +++++---- .../share/native/libsplashscreen/splashscreen_jpeg.c | 8 ++++++-- .../share/native/libsplashscreen/splashscreen_png.c | 7 +++++-- .../windows/native/libsplashscreen/splashscreen_sys.c | 2 ++ 5 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/java.desktop/share/native/libsplashscreen/splashscreen_gif.c b/src/java.desktop/share/native/libsplashscreen/splashscreen_gif.c index 4b75bf37d34..13cbe2d7618 100644 --- a/src/java.desktop/share/native/libsplashscreen/splashscreen_gif.c +++ b/src/java.desktop/share/native/libsplashscreen/splashscreen_gif.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -95,9 +95,12 @@ SplashDecodeGif(Splash * splash, GifFileType * gif) return 0; } stride = gif->SWidth * splash->imageFormat.depthBytes; - if (splash->byteAlignment > 1) - stride = - (stride + splash->byteAlignment - 1) & ~(splash->byteAlignment - 1); + if (splash->byteAlignment > 1) { + if (stride > INT_MAX - (splash->byteAlignment - 1)) { + return 0; + } + stride = (stride + splash->byteAlignment - 1) & ~(splash->byteAlignment - 1); + } if (!SAFE_TO_ALLOC(gif->SHeight, stride)) { return 0; diff --git a/src/java.desktop/share/native/libsplashscreen/splashscreen_impl.h b/src/java.desktop/share/native/libsplashscreen/splashscreen_impl.h index d1f8b5564d5..e1f5c63208a 100644 --- a/src/java.desktop/share/native/libsplashscreen/splashscreen_impl.h +++ b/src/java.desktop/share/native/libsplashscreen/splashscreen_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ #include "splashscreen_config.h" #include "splashscreen_gfx.h" #include "jni.h" +#include JNIEXPORT int SplashLoadMemory(void *pdata, int size); /* requires preloading the file */ @@ -185,9 +186,9 @@ int SplashDecodePngStream(Splash * splash, SplashStream * stream); int BitmapToYXBandedRectangles(ImageRect * pSrcRect, RECT_T * out); -#define SAFE_TO_ALLOC(c, sz) \ - (((c) > 0) && ((sz) > 0) && \ - ((0xffffffffu / ((unsigned int)(c))) > (unsigned int)(sz))) +#define SAFE_TO_ALLOC(c, sz) \ + (((c) > 0) && ((sz) > 0) && \ + ((size_t)(c) <= (size_t)INT_MAX / (size_t)(sz))) #define dbgprintf printf diff --git a/src/java.desktop/share/native/libsplashscreen/splashscreen_jpeg.c b/src/java.desktop/share/native/libsplashscreen/splashscreen_jpeg.c index ba91abbed46..4f756a0a915 100644 --- a/src/java.desktop/share/native/libsplashscreen/splashscreen_jpeg.c +++ b/src/java.desktop/share/native/libsplashscreen/splashscreen_jpeg.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -172,9 +172,11 @@ SplashDecodeJpeg(Splash * splash, struct jpeg_decompress_struct *cinfo) splash->loopCount = 1; splash->frames[0].delay = 0; - splash->frames[0].bitmapBits = malloc(stride * splash->height); + splash->frames[0].bitmapBits = malloc((size_t) stride * splash->height); if (splash->frames[0].bitmapBits == NULL) { free(splash->frames); + splash->frames = NULL; + splash->frameCount = 0; return 0; } @@ -185,6 +187,8 @@ SplashDecodeJpeg(Splash * splash, struct jpeg_decompress_struct *cinfo) if (buffer == NULL) { free(splash->frames[0].bitmapBits); free(splash->frames); + splash->frames = NULL; + splash->frameCount = 0; return 0; } diff --git a/src/java.desktop/share/native/libsplashscreen/splashscreen_png.c b/src/java.desktop/share/native/libsplashscreen/splashscreen_png.c index 0ad3d448372..2dc59cebf69 100644 --- a/src/java.desktop/share/native/libsplashscreen/splashscreen_png.c +++ b/src/java.desktop/share/native/libsplashscreen/splashscreen_png.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -147,13 +147,16 @@ SplashDecodePng(Splash * splash, png_rw_ptr read_func, void *io_ptr) malloc(sizeof(SplashImage) * splash->frameCount); if (splash->frames == NULL) { + splash->frameCount = 0; goto done; } splash->loopCount = 1; - splash->frames[0].bitmapBits = malloc(stride * splash->height); + splash->frames[0].bitmapBits = malloc((size_t) stride * splash->height); if (splash->frames[0].bitmapBits == NULL) { free(splash->frames); + splash->frames = NULL; + splash->frameCount = 0; goto done; } splash->frames[0].delay = 0; diff --git a/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c b/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c index 4e26ade6c43..bedd19ae763 100644 --- a/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c +++ b/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c @@ -95,6 +95,8 @@ SplashInitFrameShape(Splash * splash, int imageIndex) RGNDATAHEADER *pRgnHdr; ImageRect maskRect; + splash->frames[imageIndex].hRgn = NULL; + if (!splash->maskRequired) return; From 6cec81cbeadf5dd22f36643affba04d83f139634 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Wed, 25 Nov 2026 10:00:47 +0000 Subject: [PATCH 84/95] 8392468: javac crashes with NPE for TYPE_USE annotation on catch parameter in static initializer Reviewed-by: vromero --- .../com/sun/tools/javac/code/Symbol.java | 8 +- .../sun/tools/javac/code/SymbolMetadata.java | 36 +- .../sun/tools/javac/code/TypeAnnotations.java | 20 +- .../com/sun/tools/javac/comp/Attr.java | 4 +- .../TypeAnnotationsOnVariables.java | 370 +++++++++++++++++- 5 files changed, 408 insertions(+), 30 deletions(-) diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java index 37fc5e7e920..c82c143d97b 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java @@ -177,15 +177,15 @@ public void appendAttributes(List l) { } } - public void appendClassInitTypeAttributes(List l) { + public void appendUniqueClassInitTypeAttributes(List l) { if (l.nonEmpty()) { - initedMetadata().appendClassInitTypeAttributes(l); + initedMetadata().appendUniqueClassInitTypeAttributes(l); } } - public void appendInitTypeAttributes(List l) { + public void appendUniqueInitTypeAttributes(List l) { if (l.nonEmpty()) { - initedMetadata().appendInitTypeAttributes(l); + initedMetadata().appendUniqueInitTypeAttributes(l); } } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/SymbolMetadata.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/SymbolMetadata.java index 68d45ef32a6..50d0313d27e 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/SymbolMetadata.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/SymbolMetadata.java @@ -199,41 +199,45 @@ public SymbolMetadata append(List l) { public SymbolMetadata appendUniqueTypes(List l) { if (l.isEmpty()) { // no-op - } else if (type_attributes.isEmpty()) { - type_attributes = l; } else { - // TODO: in case we expect a large number of annotations, this - // might be inefficient. - for (Attribute.TypeCompound tc : l) { - if (!type_attributes.contains(tc)) - type_attributes = type_attributes.append(tc); - } + type_attributes = appendUniqueTypeAttributes(type_attributes, l); } return this; } - public SymbolMetadata appendInitTypeAttributes(List l) { + public SymbolMetadata appendUniqueInitTypeAttributes(List l) { if (l.isEmpty()) { // no-op - } else if (init_type_attributes.isEmpty()) { - init_type_attributes = l; } else { - init_type_attributes = init_type_attributes.appendList(l); + init_type_attributes = appendUniqueTypeAttributes(init_type_attributes, l); } return this; } - public SymbolMetadata appendClassInitTypeAttributes(List l) { + public SymbolMetadata appendUniqueClassInitTypeAttributes(List l) { if (l.isEmpty()) { // no-op - } else if (clinit_type_attributes.isEmpty()) { - clinit_type_attributes = l; } else { - clinit_type_attributes = clinit_type_attributes.appendList(l); + clinit_type_attributes = appendUniqueTypeAttributes(clinit_type_attributes, l); } return this; } + private List appendUniqueTypeAttributes(List existing, + List toAppend) { + if (existing.isEmpty()) { + return toAppend; + } else { + // TODO: in case we expect a large number of annotations, this + // might be inefficient. + for (Attribute.TypeCompound tc : toAppend) { + if (!existing.contains(tc)) + existing = existing.append(tc); + } + return existing; + } + } + public SymbolMetadata prepend(List l) { attributes = filterDeclSentinels(attributes); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java index b065bcc75e9..71eb578a19b 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java @@ -402,7 +402,8 @@ private void separateAnnotationsKinds(JCTree pos, JCTree typetree, Type type, if (sym.getKind() == ElementKind.METHOD) { sym.type.asMethodType().restype = type; - } else if (sym.getKind() == ElementKind.PARAMETER && currentLambda == null) { + } else if (sym.getKind() == ElementKind.PARAMETER && currentLambda == null && + !(contextTree instanceof JCCatch c && c.param.sym == sym)) { sym.type = type; if (sym.getQualifiedName().equals(names._this)) { sym.owner.type.asMethodType().recvtype = type; @@ -448,9 +449,9 @@ private void appendTypeAnnotationsToOwner(Symbol sym, List tas = localEnv.info.scope.owner.getRawTypeAttributes(); if ((tree.flags & STATIC) != 0) { - cs.appendClassInitTypeAttributes(tas); + cs.appendUniqueClassInitTypeAttributes(tas); } else { - cs.appendInitTypeAttributes(tas); + cs.appendUniqueInitTypeAttributes(tas); } } } else { diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsOnVariables.java b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsOnVariables.java index 9c61c3f6d4a..430ca8b218e 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsOnVariables.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsOnVariables.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8371155 8379550 8381965 8384843 + * @bug 8371155 8379550 8381965 8384843 8392468 * @summary Verify type annotations on local-like variables are propagated to * their types at an appropriate time. * @library /tools/lib @@ -745,6 +745,363 @@ public Void visitLambdaExpression(LambdaExpressionTree node, Void p) { " Test$TypeAnno"); } + @Test + void catchParameter() throws Exception { + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + import java.io.IOException; + import java.lang.annotation.ElementType; + import java.lang.annotation.Target; + + class Test { + @Target(ElementType.TYPE_USE) + @interface TypeAnno { } + @Target(ElementType.TYPE_USE) + @interface TypeAnno2 { } + + static class C1 { + static { + try { + new Object(); + } catch (@TypeAnno Exception ex1) {} + } + } + + static class C2 { + static { + try { + new Object(); + } catch (java.lang.@TypeAnno Exception ex2) {} + } + } + + static class C3 { + static { + try { + throw new IOException(); + } catch (java.io.IOException | java.lang.@TypeAnno RuntimeException ex3) {} + } + } + + static class C4 { + static { + try { + throw new IOException(); + } catch (java.io.@TypeAnno IOException | java.lang.RuntimeException ex4) {} + } + } + + static class C5 { + static { + try { + throw new IOException(); + } catch (java.io.@TypeAnno IOException | java.lang.@TypeAnno RuntimeException ex5) {} + } + } + + static class C6 { + static { + try { + throw new IOException(); + } catch (@TypeAnno IOException | @TypeAnno RuntimeException ex6) {} + } + } + + static class C7 { + { + try { + throw new IOException(); + } catch (java.io.@TypeAnno IOException | java.lang.@TypeAnno RuntimeException ex7) {} + } + } + + static class C8 { + static { + try { + throw new IOException(); + } catch (java.io.@TypeAnno IOException | java.lang.@TypeAnno RuntimeException ex8) {} + } + static { + try { + throw new IOException(); + } catch (java.io.@TypeAnno2 IOException | java.lang.@TypeAnno2 RuntimeException ex9) {} + } + { + try { + throw new IOException(); + } catch (java.io.@TypeAnno IOException | java.lang.@TypeAnno RuntimeException exa) {} + } + { + try { + throw new IOException(); + } catch (java.io.@TypeAnno2 IOException | java.lang.@TypeAnno2 RuntimeException exb) {} + } + } + + void test(Exception param) { + try { + new Object(); + } catch (@TypeAnno Exception exc) {} + } + } + """); + Files.createDirectories(classes); + List actual = new ArrayList<>(); + new JavacTask(tb) + .options("-d", classes.toString()) + .files(tb.findJavaFiles(src)) + .callback(task -> { + task.addTaskListener(new TaskListener() { + @Override + public void finished(TaskEvent e) { + if (e.getKind() != TaskEvent.Kind.ANALYZE) { + return ; + } + Trees trees = Trees.instance(task); + new TreePathScanner() { + @Override + public Void visitVariable(VariableTree node, Void p) { + actual.add(node.getName() + ": " + typeToString(trees.getTypeMirror(getCurrentPath()))); + return super.visitVariable(node, p); + } + }.scan(e.getCompilationUnit(), null); + } + }); + }) + .run() + .writeAll(); + + List expected = List.of( + "ex1: java.lang.@Test.TypeAnno Exception", + "ex2: java.lang.@Test.TypeAnno Exception", + "ex3: java.io.IOException | java.lang.@Test.TypeAnno RuntimeException", + "ex4: java.io.@Test.TypeAnno IOException | java.lang.RuntimeException", + "ex5: java.io.@Test.TypeAnno IOException | java.lang.@Test.TypeAnno RuntimeException", + "ex6: java.io.@Test.TypeAnno IOException | java.lang.@Test.TypeAnno RuntimeException", + "ex7: java.io.@Test.TypeAnno IOException | java.lang.@Test.TypeAnno RuntimeException", + "ex8: java.io.@Test.TypeAnno IOException | java.lang.@Test.TypeAnno RuntimeException", + "ex9: java.io.@Test.TypeAnno2 IOException | java.lang.@Test.TypeAnno2 RuntimeException", + "exa: java.io.@Test.TypeAnno IOException | java.lang.@Test.TypeAnno RuntimeException", + "exb: java.io.@Test.TypeAnno2 IOException | java.lang.@Test.TypeAnno2 RuntimeException", + "param: java.lang.Exception", + "exc: java.lang.@Test.TypeAnno Exception" + ); + + actual.forEach(System.out::println); + if (!expected.equals(actual)) { + throw new AssertionError("Expected: " + expected + ", but got: " + actual); + } + + Path testClass = classes.resolve("Test.class"); + TestClassDesc testClassDesc = TestClassDesc.create(testClass); + + checkTypeAnnotations(testClassDesc, + "test", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno"); + + Path c1 = classes.resolve("Test$C1.class"); + TestClassDesc testClassDescC1 = TestClassDesc.create(c1); + + checkTypeAnnotations(testClassDescC1, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno"); + + Path c2 = classes.resolve("Test$C2.class"); + TestClassDesc testClassDescC2 = TestClassDesc.create(c2); + + checkTypeAnnotations(testClassDescC2, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno"); + + Path c3 = classes.resolve("Test$C3.class"); + TestClassDesc testClassDescC3 = TestClassDesc.create(c3); + + checkTypeAnnotations(testClassDescC3, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=1", + " Test$TypeAnno"); + + Path c4 = classes.resolve("Test$C4.class"); + TestClassDesc testClassDescC4 = TestClassDesc.create(c4); + + checkTypeAnnotations(testClassDescC4, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno"); + + Path c5 = classes.resolve("Test$C5.class"); + TestClassDesc testClassDescC5 = TestClassDesc.create(c5); + + checkTypeAnnotations(testClassDescC5, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno", + " 1: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=1", + " Test$TypeAnno"); + + Path c6 = classes.resolve("Test$C6.class"); + TestClassDesc testClassDescC6 = TestClassDesc.create(c6); + + checkTypeAnnotations(testClassDescC6, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno", + " 1: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=1", + " Test$TypeAnno"); + + Path c7 = classes.resolve("Test$C7.class"); + TestClassDesc testClassDescC7 = TestClassDesc.create(c7); + + checkTypeAnnotations(testClassDescC7, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno", + " 1: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=1", + " Test$TypeAnno"); + + Path c8 = classes.resolve("Test$C8.class"); + TestClassDesc testClassDescC8 = TestClassDesc.create(c8); + + checkTypeAnnotations(testClassDescC8, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno", + " 1: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=1", + " Test$TypeAnno", + " 2: LTest$TypeAnno2;(): EXCEPTION_PARAMETER, exception_index=2", + " Test$TypeAnno", + " 3: LTest$TypeAnno2;(): EXCEPTION_PARAMETER, exception_index=3", + " Test$TypeAnno"); + checkTypeAnnotations(testClassDescC8, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=0", + " Test$TypeAnno", + " 1: LTest$TypeAnno;(): EXCEPTION_PARAMETER, exception_index=1", + " Test$TypeAnno", + " 2: LTest$TypeAnno2;(): EXCEPTION_PARAMETER, exception_index=2", + " Test$TypeAnno", + " 3: LTest$TypeAnno2;(): EXCEPTION_PARAMETER, exception_index=3", + " Test$TypeAnno"); + } + + @Test + void resourceVariable() throws Exception { + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + import java.io.IOException; + import java.lang.annotation.ElementType; + import java.lang.annotation.Target; + + class Test { + @Target(ElementType.TYPE_USE) + @interface TypeAnno { } + + static class C1 { + static { + try (@TypeAnno AutoCloseable ac1 = null) { + } catch (Exception ex) {} + } + } + + static class C2 { + static { + try (java.lang. @TypeAnno AutoCloseable ac2 = null) { + } catch (Exception ex) {} + } + } + + void test(Exception param) { + try (@TypeAnno AutoCloseable ac3 = null) { + } catch (Exception ex) {} + } + } + """); + Files.createDirectories(classes); + List actual = new ArrayList<>(); + new JavacTask(tb) + .options("-d", classes.toString()) + .files(tb.findJavaFiles(src)) + .callback(task -> { + task.addTaskListener(new TaskListener() { + @Override + public void finished(TaskEvent e) { + if (e.getKind() != TaskEvent.Kind.ANALYZE) { + return ; + } + Trees trees = Trees.instance(task); + new TreePathScanner() { + @Override + public Void visitVariable(VariableTree node, Void p) { + actual.add(node.getName() + ": " + typeToString(trees.getTypeMirror(getCurrentPath()))); + return super.visitVariable(node, p); + } + }.scan(e.getCompilationUnit(), null); + } + }); + }) + .run() + .writeAll(); + + List expected = List.of( + "ac1: java.lang.@Test.TypeAnno AutoCloseable", + "ex: java.lang.Exception", + "ac2: java.lang.@Test.TypeAnno AutoCloseable", + "ex: java.lang.Exception", + "param: java.lang.Exception", + "ac3: java.lang.@Test.TypeAnno AutoCloseable", + "ex: java.lang.Exception" + ); + + actual.forEach(System.out::println); + if (!expected.equals(actual)) { + throw new AssertionError("Expected: " + expected + ", but got: " + actual); + } + + Path testClass = classes.resolve("Test.class"); + TestClassDesc testClassDesc = TestClassDesc.create(testClass); + + checkTypeAnnotations(testClassDesc, + "test", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): RESOURCE_VARIABLE, {start_pc=2, length=10, index=2}", + " Test$TypeAnno"); + + Path c1 = classes.resolve("Test$C1.class"); + TestClassDesc testClassDescC1 = TestClassDesc.create(c1); + + checkTypeAnnotations(testClassDescC1, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): RESOURCE_VARIABLE, {start_pc=2, length=10, index=0}", + " Test$TypeAnno"); + + Path c2 = classes.resolve("Test$C2.class"); + TestClassDesc testClassDescC2 = TestClassDesc.create(c2); + + checkTypeAnnotations(testClassDescC2, + "", + this::getAnnotationsFromCode, + " 0: LTest$TypeAnno;(): RESOURCE_VARIABLE, {start_pc=2, length=10, index=0}", + " Test$TypeAnno"); + } + private void checkTypeAnnotations(TestClassDesc testClassDesc, String lambdaMethodName, String... expectedEntries) throws IOException { @@ -823,7 +1180,16 @@ void checkJavapOutput(TestClassDesc testClassDesc, String nameOfMethodToCheck, L } } - List> methodContents = feature2Text.entrySet().stream().filter(e -> e.getKey().contains(" " + nameOfMethodToCheck + "(")).map(Entry::getValue).toList(); + String methodKey = switch (nameOfMethodToCheck) { + case "" -> " static {"; + case "" -> { + String fileName = testClassDesc.pathToClass().getFileName().toString(); + yield " " + fileName.substring(0, fileName.indexOf('.')); + } + default -> " " + nameOfMethodToCheck + "("; + }; + + List> methodContents = feature2Text.entrySet().stream().filter(e -> e.getKey().contains(methodKey)).map(Entry::getValue).toList(); assertEquals(1, methodContents.size(), methodContents.toString()); From faa3432b005dfcc5290501b578e766436a5b5f9b Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Wed, 25 Nov 2026 10:02:26 +0000 Subject: [PATCH 85/95] 8398032: Legal method reference rejected after JDK-8392939 Reviewed-by: mcimadamore --- .../sun/tools/javac/parser/JavacParser.java | 4 +- .../tools/javac/parser/JavacParserTest.java | 100 +++++++++++++++++- 2 files changed, 102 insertions(+), 2 deletions(-) diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java index df113495199..f36d5232298 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java @@ -1961,10 +1961,12 @@ boolean isParameterizedTypePrefix() { nextKind == TokenKind.DOT || nextKind == TokenKind.LBRACKET || nextKind == TokenKind.COLCOL; + } else if (depth < 0) { + return false; } break; case COLCOL: - return true; + return depth == 0; default: return false; } diff --git a/test/langtools/tools/javac/parser/JavacParserTest.java b/test/langtools/tools/javac/parser/JavacParserTest.java index 629150309b1..23d49e8c47b 100644 --- a/test/langtools/tools/javac/parser/JavacParserTest.java +++ b/test/langtools/tools/javac/parser/JavacParserTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 7073631 7159445 7156633 8028235 8065753 8205418 8205913 8228451 8237041 8253584 8246774 8256411 8256149 8259050 8266436 8267221 8271928 8275097 8293897 8295401 8304671 8310326 8312093 8312204 8315452 8337976 8324859 8344706 8351260 8370865 8369489 8392939 + * @bug 7073631 7159445 7156633 8028235 8065753 8205418 8205913 8228451 8237041 8253584 8246774 8256411 8256149 8259050 8266436 8267221 8271928 8275097 8293897 8295401 8304671 8310326 8312093 8312204 8315452 8337976 8324859 8344706 8351260 8370865 8369489 8392939 8398032 * @summary tests error and diagnostics positions * @author Jan Lahoda * @modules jdk.compiler/com.sun.tools.javac.api @@ -3388,6 +3388,104 @@ static String getString() { }"""); } + @Test //JDK-8398032 + void testParseMethodReference() throws IOException { + String code = """ + package tests; + + import java.lang.annotation.*; + import java.util.function.*; + + class Test { + int i, j, k; + void test1(boolean b, Supplier r) { + test1(i < j, Test::get); + } + void test2(boolean b1, boolean b2, Supplier r) { + test2(i < j, j > i, Test::get); + } + void test3(boolean b1, boolean b2, Supplier r) { + test3(i > j, j < i, Test::get); + } + void test4(boolean b1, boolean b2, Supplier r) { + test4(i < j >> k, i < j, Test::get); + } + void test5(boolean b1, boolean b2, Supplier r) { + test5(i < j >>> k, i < j, Test::get); + } + void test6(boolean b1, boolean b2, Supplier r) { + test6(i < j, i < j >> k, Test::get); + } + void test7(boolean b1, boolean b2, Supplier r) { + test7(i < j, i < j >>> k, Test::get); + } + private static String get() { + return null; + } + } + """; + DiagnosticCollector coll = + new DiagnosticCollector<>(); + JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, + List.of("-XDrawDiagnostics"), + null, Arrays.asList(new MyFileObject(code))); + CompilationUnitTree cut = ct.parse().iterator().next(); + + String astAsText = toStringWithErrors(cut).replaceAll("\\R", "\n"); + + ct.analyze(); + + assertTrue("Expected no errors, but got: " + coll.getDiagnostics(), + coll.getDiagnostics().isEmpty()); + + System.out.println("RESULT\n" + astAsText); + assertEquals("incorrect AST", + astAsText, + """ + package tests; + + import java.lang.annotation.*; + import java.util.function.*; + + class Test { + int i; + int j; + int k; + \n\ + void test1(boolean b, Supplier r) { + test1(i < j, Test::get); + } + \n\ + void test2(boolean b1, boolean b2, Supplier r) { + test2(i < j, j > i, Test::get); + } + \n\ + void test3(boolean b1, boolean b2, Supplier r) { + test3(i > j, j < i, Test::get); + } + \n\ + void test4(boolean b1, boolean b2, Supplier r) { + test4(i < j >> k, i < j, Test::get); + } + \n\ + void test5(boolean b1, boolean b2, Supplier r) { + test5(i < j >>> k, i < j, Test::get); + } + \n\ + void test6(boolean b1, boolean b2, Supplier r) { + test6(i < j, i < j >> k, Test::get); + } + \n\ + void test7(boolean b1, boolean b2, Supplier r) { + test7(i < j, i < j >>> k, Test::get); + } + \n\ + private static String get() { + return null; + } + }"""); + } + void run(String[] args) throws Exception { int passed = 0, failed = 0; final Pattern p = (args != null && args.length > 0) From e289c72d86c1b8ed541b582d7014521d50e8e0a7 Mon Sep 17 00:00:00 2001 From: Dingli Zhang Date: Wed, 25 Nov 2026 10:32:54 +0000 Subject: [PATCH 86/95] 8398138: RISC-V: Restrict C2 far flags branches to equality conditions Reviewed-by: fyang, gcao --- src/hotspot/cpu/riscv/riscv.ad | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/hotspot/cpu/riscv/riscv.ad b/src/hotspot/cpu/riscv/riscv.ad index 4d595d7b1bd..bd2447540dd 100644 --- a/src/hotspot/cpu/riscv/riscv.ad +++ b/src/hotspot/cpu/riscv/riscv.ad @@ -10159,7 +10159,7 @@ instruct branch(label lbl) // ============================================================================ // Compare and Branch Instructions -// Patterns for short (< 12KiB) variants +// Patterns for near conditional branches // Compare flags and branch near instructions. instruct cmpFlag_branch(cmpOpEqNe cmp, rFlagsReg cr, label lbl) %{ @@ -10544,9 +10544,11 @@ instruct cmpP_narrowOop_imm0_branch(cmpOpEqNe cmp, iRegN op1, immP_0 zero, label ins_short_branch(1); %} -// Patterns for far (20KiB) variants +// Patterns for far conditional branches -instruct far_cmpFlag_branch(cmpOp cmp, rFlagsReg cr, label lbl) %{ +// FastLock/FastUnlock set cr (t1) to zero on success and nonzero on failure. +// C2 tests this result only for equality or inequality with zero. +instruct far_cmpFlag_branch(cmpOpEqNe cmp, rFlagsReg cr, label lbl) %{ match(If cmp cr); effect(USE lbl); From db1d3405964538de86e381ad3992d763c5f37219 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 25 Nov 2026 16:56:40 +0000 Subject: [PATCH 87/95] 8398245: [Leyden] Remove old AOT code which caches klass initialization state Reviewed-by: iveresov, iklam, heidinga --- src/hotspot/share/code/aotCodeCache.cpp | 43 ++++++------------------- 1 file changed, 9 insertions(+), 34 deletions(-) diff --git a/src/hotspot/share/code/aotCodeCache.cpp b/src/hotspot/share/code/aotCodeCache.cpp index 0f1b1919ea0..f8ffe513a38 100644 --- a/src/hotspot/share/code/aotCodeCache.cpp +++ b/src/hotspot/share/code/aotCodeCache.cpp @@ -3877,26 +3877,21 @@ bool AOTCodeCache::write_klass(Klass* klass) { } klass = oak->bottom_klass(); // overwrites klass } - uint init_state = 0; if (klass->is_instance_klass()) { - // A few classes are initialized in the assembly phase before code generation. - // When run in production, the code will assume they are initialized, again. InstanceKlass* ik = InstanceKlass::cast(klass); - init_state = (ik->is_initialized() ? 1 : 0); can_write &= AOTCacheAccess::can_generate_aot_code_for(ik); } else { assert(klass->is_typeArray_klass(), "must be"); can_write &= AOTCacheAccess::can_generate_aot_code(klass); } ResourceMark rm; - uint state = (array_dim << 1) | (init_state & 1); if (can_write) { DataKind kind = DataKind::Klass; if (!write_kind(kind)) { return false; } - // Record state of instance klass initialization and array dimensions. - if (!write_int(state)) { + // Record array dimensions. + if (!write_int(array_dim)) { return false; } // Record array's properties @@ -3909,21 +3904,23 @@ bool AOTCodeCache::write_klass(Klass* klass) { } log_debug(aot, codecache, metadata)("%d (A%d): Registered klass: %s%s%s @ 0x%08x", compile_id(), comp_level(), klass->external_name(), - (!klass->is_instance_klass() ? "" : (init_state == 1 ? " (initialized)" : " (not-initialized)")), + (!klass->is_instance_klass() ? "" : (InstanceKlass::cast(klass)->is_initialized() ? + " (initialized)" : " (not-initialized)")), (array_dim > 0 ? " (object array)" : ""), cast_to_u4(klass_narrow_ptr)); return true; } log_debug(aot, codecache, metadata)("%d (A%d): Klass is not registered: %s%s%s", compile_id(), comp_level(), klass->external_name(), - (!klass->is_instance_klass() ? "" : (init_state == 1 ? " (initialized)" : " (not-initialized)")), + (!klass->is_instance_klass() ? "" : (InstanceKlass::cast(klass)->is_initialized() ? + " (initialized)" : " (not-initialized)")), (array_dim > 0 ? " (object array)" : "")); set_lookup_failed(); return false; } Klass* AOTCodeReader::read_klass(JavaThread* thread) { - uint state; - if (!read_int((int*)&state)) { + uint array_dim; + if (!read_int((int*)&array_dim)) { return nullptr; } uint array_desc; @@ -3934,8 +3931,6 @@ Klass* AOTCodeReader::read_klass(JavaThread* thread) { if (!read_int((int*)&klass_narrow_ptr)) { return nullptr; } - uint init_state = (state & 1); - uint array_dim = (state >> 1); Klass* k = AOTCacheAccess::narrow_ptr_to_klass(klass_narrow_ptr); if (k == nullptr || !AOTMetaspace::in_aot_cache((address)k)) { // Something changed in CDS @@ -3952,27 +3947,7 @@ Klass* AOTCodeReader::read_klass(JavaThread* thread) { compile_id(), comp_level(), k->external_name()); return nullptr; } - // If the klass was seen to be initialized during AOT cache assembly, - // it must also be initialized here, in the production run, when this nmethod loads. - // Exception: "preload" code (AP4) can handle uninitialized classes. - // There is no exception for A1, A2 code or A4 code. - // - // Note: This init-state check is of minor importance compared to the clinit deps - // list/counter on this nmethod's CompileTrainingData, which has already determined - // the nmethod's readiness to load. (For many more details, see comments near - // CompileTrainingData::_init_deps_left.) This check is superficially similar, - // but it checks a relatively small number of classes, which may or may not be - // necessary to the nmethod's compiled code. Think of it as an extra sanity check. - // But it is an approximate check, and may fail spuriously, discarding good AOT code. - // After JDK-8380476 FIXME: Maybe get rid of this approximate check; replace with - // a more accurate and efficient check based on dependencies.hpp (new DepType). - // (Also, the metadata for arrays should have its own DataKind::ArrayKlass.) - if (k->is_instance_klass() && !InstanceKlass::cast(k)->is_initialized() && (init_state == 1) && !_entry->for_preload()) { - set_lookup_failed("Klass is not initialized"); - log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed for klass %s: not initialized", - compile_id(), comp_level(), k->external_name()); - return nullptr; - } + // FIXME: The metadata for arrays should have its own DataKind::ArrayKlass. if (array_dim > 0) { assert(k->is_instance_klass() || k->is_typeArray_klass(), "sanity check"); Klass* ak = k->array_klass_or_null(array_dim); From c1e50d63f385f970dd22f594a0c89bfaa55bdd2c Mon Sep 17 00:00:00 2001 From: Ioi Lam Date: Wed, 25 Nov 2026 17:28:49 +0000 Subject: [PATCH 88/95] 8398324: Test runtime/cds/appcds/aotCache/AgentBootClassPath.java fails with 'class,path.*boot.* .1. = .*/boot1.jar' missing from stdout/stderr Reviewed-by: dcubed --- .../jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java index fa2e14725e6..95a75c5c626 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotCache/AgentBootClassPath.java @@ -99,8 +99,8 @@ public void checkExecution(OutputAnalyzer out, RunMode runMode) { if (runMode == RunMode.ASSEMBLY) { // Make sure boot2.jar is not included in the classpath(s) of the config file out.shouldContain("Reading classpath(s) from AgentBootClassPathApp.aotconfig (size = 3)"); - out.shouldMatch("class,path.*boot.* .1. = .*/boot1.jar"); - out.shouldMatch("class,path.*app.* .2. = .*/app.jar"); + out.shouldMatch("class,path.*boot.* .1. = .*boot1.jar"); + out.shouldMatch("class,path.*app.* .2. = .*app.jar"); } if (runMode.isApplicationExecuted()) { out.shouldContain("AgentBootClassPathBoot1 loader = null"); From 5608271b38459abdd0c691230fb0896faa131f64 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Wed, 25 Nov 2026 18:50:09 +0000 Subject: [PATCH 89/95] 8394915: Thread dump improvements Reviewed-by: kevinw, sspitsyn, dholmes --- src/hotspot/share/services/threadService.cpp | 12 + .../concurrent/StructuredTaskScopeImpl.java | 5 +- .../jdk/internal/misc/ThreadFlock.java | 27 +- .../classes/jdk/internal/vm/ThreadDumper.java | 58 +-- .../jdk/internal/vm/ThreadSnapshot.java | 8 + .../sun/management/doc-files/threadDump.html | 13 + .../HotSpotDiagnosticMXBean/DumpThreads.java | 335 +++++++++++++++--- .../misc/ThreadFlock/ThreadFlockTest.java | 44 +-- .../jdk/test/lib/threaddump/ThreadDump.java | 18 + 9 files changed, 407 insertions(+), 113 deletions(-) diff --git a/src/hotspot/share/services/threadService.cpp b/src/hotspot/share/services/threadService.cpp index e0c53bc3a9f..de0f8f1e5e9 100644 --- a/src/hotspot/share/services/threadService.cpp +++ b/src/hotspot/share/services/threadService.cpp @@ -1414,6 +1414,7 @@ class jdk_internal_vm_ThreadSnapshot: AllStatic { static bool _inited; static int _name_offset; static int _threadStatus_offset; + static int _cpuTime_offset; static int _carrierThread_offset; static int _stackTrace_offset; static int _locks_offset; @@ -1424,6 +1425,7 @@ class jdk_internal_vm_ThreadSnapshot: AllStatic { static void compute_offsets(InstanceKlass* klass, TRAPS) { JavaClasses::compute_offset(_name_offset, klass, "name", vmSymbols::string_signature(), false); JavaClasses::compute_offset(_threadStatus_offset, klass, "threadStatus", vmSymbols::int_signature(), false); + JavaClasses::compute_offset(_cpuTime_offset, klass, "cpuTime", vmSymbols::long_signature(), false); JavaClasses::compute_offset(_carrierThread_offset, klass, "carrierThread", vmSymbols::thread_signature(), false); JavaClasses::compute_offset(_stackTrace_offset, klass, "stackTrace", vmSymbols::java_lang_StackTraceElement_array(), false); JavaClasses::compute_offset(_locks_offset, klass, "locks", vmSymbols::jdk_internal_vm_ThreadLock_array(), false); @@ -1451,6 +1453,9 @@ class jdk_internal_vm_ThreadSnapshot: AllStatic { static void set_thread_status(oop snapshot, int status) { snapshot->int_field_put(_threadStatus_offset, status); } + static void set_cpu_time(oop snapshot, jlong cpu_time) { + snapshot->long_field_put(_cpuTime_offset, cpu_time); + } static void set_carrier_thread(oop snapshot, oop carrier_thread) { snapshot->obj_field_put(_carrierThread_offset, carrier_thread); } @@ -1470,6 +1475,7 @@ class jdk_internal_vm_ThreadSnapshot: AllStatic { bool jdk_internal_vm_ThreadSnapshot::_inited = false; int jdk_internal_vm_ThreadSnapshot::_name_offset; int jdk_internal_vm_ThreadSnapshot::_threadStatus_offset; +int jdk_internal_vm_ThreadSnapshot::_cpuTime_offset; int jdk_internal_vm_ThreadSnapshot::_carrierThread_offset; int jdk_internal_vm_ThreadSnapshot::_stackTrace_offset; int jdk_internal_vm_ThreadSnapshot::_locks_offset; @@ -1508,6 +1514,11 @@ oop ThreadSnapshotFactory::get_thread_snapshot(jobject jthread, TRAPS) { } assert(cl._thread_status != JavaThreadStatus::NEW, "unstarted Thread"); + jlong cpu_time = -1; + if (!is_virtual && os::is_thread_cpu_time_supported()) { + cpu_time = os::thread_cpu_time(java_thread, true); + } + // StackTrace InstanceKlass* ste_klass = vmClasses::StackTraceElement_klass(); assert(ste_klass != nullptr, "must be loaded"); @@ -1549,6 +1560,7 @@ oop ThreadSnapshotFactory::get_thread_snapshot(jobject jthread, TRAPS) { Handle snapshot = jdk_internal_vm_ThreadSnapshot::allocate(InstanceKlass::cast(snapshot_klass), CHECK_NULL); jdk_internal_vm_ThreadSnapshot::set_name(snapshot(), cl._thread_name.resolve()); jdk_internal_vm_ThreadSnapshot::set_thread_status(snapshot(), (int)cl._thread_status); + jdk_internal_vm_ThreadSnapshot::set_cpu_time(snapshot(), cpu_time); jdk_internal_vm_ThreadSnapshot::set_carrier_thread(snapshot(), cl._carrier_thread.resolve()); jdk_internal_vm_ThreadSnapshot::set_stack_trace(snapshot(), trace()); jdk_internal_vm_ThreadSnapshot::set_locks(snapshot(), locks()); diff --git a/src/java.base/share/classes/java/util/concurrent/StructuredTaskScopeImpl.java b/src/java.base/share/classes/java/util/concurrent/StructuredTaskScopeImpl.java index 5b813b6c435..6c1ec0bb098 100644 --- a/src/java.base/share/classes/java/util/concurrent/StructuredTaskScopeImpl.java +++ b/src/java.base/share/classes/java/util/concurrent/StructuredTaskScopeImpl.java @@ -69,7 +69,8 @@ private StructuredTaskScopeImpl(Joiner joiner, String name) { this.joiner = joiner; this.threadFactory = threadFactory; - this.flock = ThreadFlock.open((name != null) ? name : Objects.toIdentityString(this)); + String id = Objects.toIdentityString(this); + this.flock = ThreadFlock.open((name != null) ? name + "/" + id : id); } /** @@ -252,7 +253,7 @@ public R join() throws R_X, InterruptedException { // wait for all subtasks, the scope to be cancelled, or interrupt try { - flock.awaitAll(); + flock.awaitAll(this); } catch (InterruptedException e) { state = ST_JOIN_STARTED; // joining not completed, prevent new forks throw e; diff --git a/src/java.base/share/classes/jdk/internal/misc/ThreadFlock.java b/src/java.base/share/classes/jdk/internal/misc/ThreadFlock.java index 32f6d5d4905..0e0796b8509 100644 --- a/src/java.base/share/classes/jdk/internal/misc/ThreadFlock.java +++ b/src/java.base/share/classes/jdk/internal/misc/ThreadFlock.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,8 +49,8 @@ *

    ThreadFlock defines the {@link #open(String) open} method to open a new flock, * the {@link #start(Thread) start} method to start a thread in the flock, and the * {@link #close() close} method to close the flock. The {@code close} waits for all - * threads in the flock to finish. The {@link #awaitAll() awaitAll} method may be used - * to wait for all threads to finish without closing the flock. The {@link #wakeup()} + * threads in the flock to finish. The {@link #awaitAll(Object) awaitAll} method may be + * used to wait for all threads to finish without closing the flock. The {@link #wakeup()} * method will cause {@code awaitAll} method to complete early, which can be used to * support cancellation in higher-level APIs. ThreadFlock also defines the {@link * #shutdown() shutdown} method to prevent new threads from starting while allowing @@ -290,19 +290,20 @@ public void shutdown() { *

    This method clears the effect of any previous invocations of the * {@code wakeup} method. * + * @param blocker the synchronization object responsible for this thread waiting * @return true if there are no threads in the flock, false if wakeup was invoked * and there are unfinished threads * @throws InterruptedException if interrupted while waiting * @throws WrongThreadException if invoked by a thread that is not the owner */ - public boolean awaitAll() throws InterruptedException { + public boolean awaitAll(Object blocker) throws InterruptedException { ensureOwner(); if (getAndSetPermit(false)) return (threadCount == 0); while (threadCount > 0 && !permit) { - LockSupport.park(); + LockSupport.park(blocker); if (Thread.interrupted()) throw new InterruptedException(); } @@ -322,6 +323,7 @@ public boolean awaitAll() throws InterruptedException { *

    This method clears the effect of any previous invocations of the {@code wakeup} * method. * + * @param blocker the synchronization object responsible for this thread waiting * @param timeout the maximum duration to wait * @return true if there are no threads in the flock, false if wakeup was invoked * and there are unfinished threads @@ -329,7 +331,7 @@ public boolean awaitAll() throws InterruptedException { * @throws TimeoutException if the wait timed out * @throws WrongThreadException if invoked by a thread that is not the owner */ - public boolean awaitAll(Duration timeout) + public boolean awaitAll(Object blocker, Duration timeout) throws InterruptedException, TimeoutException { Objects.requireNonNull(timeout); ensureOwner(); @@ -341,7 +343,7 @@ public boolean awaitAll(Duration timeout) long nanos = NANOSECONDS.convert(timeout); long remainingNanos = nanos; while (threadCount > 0 && remainingNanos > 0 && !permit) { - LockSupport.parkNanos(remainingNanos); + LockSupport.parkNanos(blocker, remainingNanos); if (Thread.interrupted()) throw new InterruptedException(); remainingNanos = nanos - (System.nanoTime() - startNanos); @@ -357,8 +359,8 @@ public boolean awaitAll(Duration timeout) } /** - * Causes the call to {@link #awaitAll()} or {@link #awaitAll(Duration)} by the - * {@linkplain #owner() owner} to return immediately. + * Causes the call to {@link #awaitAll(Object)} or {@link #awaitAll(Object, Duration)} + * by the {@linkplain #owner() owner} to return immediately. * *

    If the owner is blocked in {@code awaitAll} then it will return immediately. * If the owner is not blocked in {@code awaitAll} then its next call to wait @@ -475,12 +477,7 @@ public boolean containsThread(Thread thread) { @Override public String toString() { - String id = Objects.toIdentityString(this); - if (name != null) { - return name + "/" + id; - } else { - return id; - } + return name; } /** diff --git a/src/java.base/share/classes/jdk/internal/vm/ThreadDumper.java b/src/java.base/share/classes/jdk/internal/vm/ThreadDumper.java index 63d2d300421..a4935856bf3 100644 --- a/src/java.base/share/classes/jdk/internal/vm/ThreadDumper.java +++ b/src/java.base/share/classes/jdk/internal/vm/ThreadDumper.java @@ -184,9 +184,12 @@ private static boolean dumpThread(Thread thread, TextWriter writer) { } Instant now = Instant.now(); Thread.State state = snapshot.threadState(); - writer.println("#" + thread.threadId() + " \"" + snapshot.threadName() - + "\" " + (thread.isVirtual() ? "virtual " : "") + state + " " + now); - + writer.println("#" + thread.threadId() + " \"" + escape(snapshot.threadName()) + + "\" " + (thread.isVirtual() ? "virtual " : "") + + decorateObject(thread) + + " " + state + + " cpuTime=" + snapshot.cpuTime() + + " " + now); StackTraceElement[] stackTrace = snapshot.stackTrace(); int depth = 0; while (depth < stackTrace.length) { @@ -359,7 +362,11 @@ private static boolean dumpThread(Thread thread, JsonWriter jsonWriter) { jsonWriter.writeProperty("virtual", Boolean.TRUE); } jsonWriter.writeProperty("name", snapshot.threadName()); + jsonWriter.writeProperty("threadObj", Objects.toIdentityString(thread)); jsonWriter.writeProperty("state", state); + if (snapshot.cpuTime() != -1L) { + jsonWriter.writeLongProperty("cpuTime", snapshot.cpuTime()); + } // park blocker Object parkBlocker = snapshot.parkBlocker(); @@ -562,34 +569,33 @@ void startArray(String name) { void endArray() { endObject(true); } + } - /** - * Escape any characters that need to be escape in the JSON output. - */ - private static String escape(String value) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - switch (c) { - case '"' -> sb.append("\\\""); - case '\\' -> sb.append("\\\\"); - case '/' -> sb.append("\\/"); - case '\b' -> sb.append("\\b"); - case '\f' -> sb.append("\\f"); - case '\n' -> sb.append("\\n"); - case '\r' -> sb.append("\\r"); - case '\t' -> sb.append("\\t"); - default -> { - if (c <= 0x1f) { - sb.append(String.format("\\u%04x", c)); - } else { - sb.append(c); - } + /** + * Escapes characters for JSON strings and quoted thread names in plain text dumps. + */ + private static String escape(String value) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + switch (c) { + case '"' -> sb.append("\\\""); + case '\\' -> sb.append("\\\\"); + case '\b' -> sb.append("\\b"); + case '\f' -> sb.append("\\f"); + case '\n' -> sb.append("\\n"); + case '\r' -> sb.append("\\r"); + case '\t' -> sb.append("\\t"); + default -> { + if (c <= 0x1f) { + sb.append(String.format("\\u%04x", (int) c)); + } else { + sb.append(c); } } } - return sb.toString(); } + return sb.toString(); } /** diff --git a/src/java.base/share/classes/jdk/internal/vm/ThreadSnapshot.java b/src/java.base/share/classes/jdk/internal/vm/ThreadSnapshot.java index 69370891688..42d3c11ebf4 100644 --- a/src/java.base/share/classes/jdk/internal/vm/ThreadSnapshot.java +++ b/src/java.base/share/classes/jdk/internal/vm/ThreadSnapshot.java @@ -40,6 +40,7 @@ public class ThreadSnapshot { // filled by VM private String name; private int threadStatus; + private long cpuTime; private Thread carrierThread; private StackTraceElement[] stackTrace; // owned monitors @@ -98,6 +99,13 @@ Thread.State threadState() { return jdk.internal.misc.VM.toThreadState(threadStatus); } + /** + * Returns CPU time in nanoseconds or -1L if not available. + */ + long cpuTime() { + return cpuTime; + } + /** * Returns the thread stack trace. */ diff --git a/src/jdk.management/share/classes/com/sun/management/doc-files/threadDump.html b/src/jdk.management/share/classes/com/sun/management/doc-files/threadDump.html index f7dd84d4f32..3f0a5fba766 100644 --- a/src/jdk.management/share/classes/com/sun/management/doc-files/threadDump.html +++ b/src/jdk.management/share/classes/com/sun/management/doc-files/threadDump.html @@ -159,12 +159,25 @@

    JSON Thread Dump Format

    no The {@linkplain java.lang.Thread#getName() thread name}. + + threadObj + string + yes + The {@linkplain java.util.Objects#toIdentityString(Object) identity string} + of the java.lang.Thread object. + state string no The string representation of the {@linkplain java.lang.Thread#getState() thread state}. + + cpuTime + number + yes + The thread CPU time, in nanoseconds, if available. + virtual boolean diff --git a/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/DumpThreads.java b/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/DumpThreads.java index 4206d2f8ebe..68870e83ba9 100644 --- a/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/DumpThreads.java +++ b/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/DumpThreads.java @@ -23,31 +23,25 @@ /* * @test - * @bug 8284161 8287008 8309406 8356870 8365057 + * @bug 8284161 8287008 8309406 8356870 8365057 8394915 * @summary Basic test for com.sun.management.HotSpotDiagnosticMXBean.dumpThreads * @requires vm.continuations * @modules java.base/jdk.internal.vm jdk.management * @library /test/lib - * @build jdk.test.whitebox.WhiteBox - * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox - * @run junit/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI - * --enable-native-access=ALL-UNNAMED DumpThreads - * @run junit/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI - * --enable-native-access=ALL-UNNAMED -Djdk.trackAllThreads DumpThreads - * @run junit/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI - * --enable-native-access=ALL-UNNAMED -Djdk.trackAllThreads=true DumpThreads - * @run junit/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI - * --enable-native-access=ALL-UNNAMED -Djdk.trackAllThreads=false DumpThreads + * @run junit/othervm --enable-native-access=ALL-UNNAMED DumpThreads + * @run junit/othervm --enable-native-access=ALL-UNNAMED -Djdk.trackAllThreads DumpThreads + * @run junit/othervm --enable-native-access=ALL-UNNAMED -Djdk.trackAllThreads=true DumpThreads + * @run junit/othervm --enable-native-access=ALL-UNNAMED -Djdk.trackAllThreads=false DumpThreads */ import java.lang.management.ManagementFactory; -import java.lang.reflect.Method; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Path; import java.time.ZonedDateTime; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; @@ -55,12 +49,12 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinWorkerThread; +import java.util.concurrent.StructuredTaskScope; +import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; @@ -69,15 +63,17 @@ import java.util.regex.Matcher; import com.sun.management.HotSpotDiagnosticMXBean; import com.sun.management.HotSpotDiagnosticMXBean.ThreadDumpFormat; +import static java.lang.Thread.State.*; + import jdk.test.lib.threaddump.ThreadDump; import jdk.test.lib.thread.VThreadPinner; import jdk.test.lib.thread.VThreadRunner; -import jdk.test.whitebox.WhiteBox; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.*; @@ -119,6 +115,7 @@ void testPlainText() throws Exception { assertNotNull(fields, "current thread not found"); assertEquals(currentThread.getName(), fields.name()); assertEquals(currentThread.isVirtual(), fields.isVirtual()); + assertEquals(Objects.toIdentityString(currentThread), fields.threadObj()); } } @@ -137,6 +134,7 @@ void testJsonFormat() throws Exception { .orElse(null); assertNotNull(ti, "current thread not found"); assertEquals(currentThread.isVirtual(), ti.isVirtual()); + assertEquals(Objects.toIdentityString(currentThread), ti.threadObj()); } } @@ -174,18 +172,15 @@ void testCommonPool() throws Exception { * Test that the JSON thread dump has a thread container for the given executor. */ private void testThreadContainer(ExecutorService executor, String name) throws Exception { - var threadRef = new AtomicReference(); - + var queue = new SynchronousQueue(); executor.submit(() -> { - threadRef.set(Thread.currentThread()); + queue.put(Thread.currentThread()); LockSupport.park(); + return null; }); - // capture Thread - Thread thread; - while ((thread = threadRef.get()) == null) { - Thread.sleep(20); - } + // executor managed thread + Thread thread = queue.take(); try { // dump threads to file and parse as JSON object @@ -267,7 +262,7 @@ void testBlockedThread(ThreadFactory factory, boolean pinned) throws Exception { ThreadFields fields = findThread(tid, lines); assertNotNull(fields, "thread not found"); assertEquals("BLOCKED", fields.state()); - assertTrue(contains(lines, "- waiting to lock <" + lockAsString)); + assertTrue(contains(lines, "- waiting to lock <" + lockAsString + ">")); // thread dump in JSON format should include thread in root container ThreadDump threadDump = dumpThreadsToJson(); @@ -338,7 +333,7 @@ void testWaitingThread(ThreadFactory factory, boolean pinned) throws Exception { // released it. List lines; ThreadDump.ThreadInfo ti; - synchronized(lock) { + synchronized (lock) { // thread dump in plain text should include thread lines = dumpThreadsToPlainText(); ThreadFields fields = findThread(tid, lines); @@ -364,17 +359,11 @@ void testWaitingThread(ThreadFactory factory, boolean pinned) throws Exception { } } - // Compiled native frames have no locals. If Object.wait0 has been compiled - // then we may not have the object that the thread is waiting on. - Method wait0 = Object.class.getDeclaredMethod("wait0", long.class); - boolean expectWaitingOn = !WhiteBox.getWhiteBox().isMethodCompiled(wait0); - if (expectWaitingOn) { - // plain text dump should have "waiting on" line - assertTrue(contains(lines, "- waiting on <" + lockAsString)); + // plain text dump should have "waiting on" line + assertTrue(contains(lines, "- waiting on <" + lockAsString + ">")); - // JSON thread dump should have waitingOn property - assertEquals(lockAsString, ti.waitingOn()); - } + // JSON thread dump should have waitingOn property + assertEquals(lockAsString, ti.waitingOn()); } finally { synchronized (lock) { @@ -435,7 +424,7 @@ void testParkedThread(ThreadFactory factory, boolean pinned) throws Exception { assertEquals("WAITING", fields.state()); String line = find(lines, "- parking to wait for , owner #" + Thread.currentThread().threadId())); // thread dump in JSON format should include thread in root container ThreadDump threadDump = dumpThreadsToJson(); @@ -519,9 +508,9 @@ void testThreadOwnsMonitor(ThreadFactory factory, boolean pinned) throws Excepti ThreadFields fields = findThread(tid, lines); assertNotNull(fields, "thread not found"); assertEquals("WAITING", fields.state()); - assertTrue(contains(lines, "- locked <" + lock1AsString)); - assertTrue(contains(lines, "- locked <" + lock2AsString)); - assertTrue(contains(lines, "- locked <" + lock3AsString)); + assertTrue(contains(lines, "- locked <" + lock1AsString + ">")); + assertTrue(contains(lines, "- locked <" + lock2AsString + ">")); + assertTrue(contains(lines, "- locked <" + lock3AsString + ">")); // thread dump in JSON format should include thread in root container ThreadDump threadDump = dumpThreadsToJson(); @@ -630,6 +619,187 @@ private void assertForkJoinWorkerThread(long tid) { assertTrue(thread instanceof ForkJoinWorkerThread, "not a ForkJoinWorkerThread"); } + /** + * Test thread waiting in Thread.join. + */ + @ParameterizedTest + @MethodSource("threadFactories") + void testThreadJoin(ThreadFactory factory) throws Exception { + Thread parkingThread = factory.newThread(LockSupport::park); + Thread joinerThread = factory.newThread(() -> { + try { + parkingThread.join(); + } catch (Throwable e) { + e.printStackTrace(); + } + }); + parkingThread.start(); + joinerThread.start(); + try { + // wait for joiner thread to wait in Thread.join + awaitWaiting(joinerThread, "java.lang.Thread.join"); + long joinerTid = joinerThread.threadId(); + + // plain text thread dump + List lines = dumpThreadsToPlainText(); + ThreadFields fields = findThread(joinerTid, lines); + assertNotNull(fields, "thread not found"); + assertEquals("WAITING", fields.state()); + + // JSON thread dump + ThreadDump threadDump = dumpThreadsToJson(); + ThreadDump.ThreadInfo ti = threadDump.rootThreadContainer() + .findThread(joinerTid) + .orElse(null); + assertNotNull(ti, "Thread " + joinerTid + " not found"); + + String expectedWaitingOn = Objects.toIdentityString(parkingThread); + + // plain text dump should have "waiting on" line + assertTrue(contains(lines, "- waiting on <" + expectedWaitingOn + ">")); + + // JSON thread dump should have waitingOn property + assertEquals(expectedWaitingOn, ti.waitingOn()); + + } finally { + LockSupport.unpark(parkingThread); + parkingThread.join(); + joinerThread.join(); + } + } + + /** + * Test thread parked in StructuredTaskScope.join. + */ + @ParameterizedTest + @MethodSource("threadFactories") + void testStructuredTaskScopeJoin(ThreadFactory factory) throws Exception { + var queue = new SynchronousQueue>(); + var thread = factory.newThread(() -> { + try (var scope = StructuredTaskScope.open()) { + queue.put(scope); + scope.fork(() -> LockSupport.park()); + scope.join(); + } catch (InterruptedException _) { + // expected + } catch (Throwable e) { + e.printStackTrace(); + } + }); + thread.start(); + try { + // wait for thread to start and park in join + StructuredTaskScope scope = queue.take(); + String scopeId = Objects.toIdentityString(scope); + awaitWaiting(thread, "java.util.concurrent.StructuredTaskScopeImpl.join"); + + // thread dump in plain text should have "parking to wait for" line + List lines = dumpThreadsToPlainText(); + ThreadFields fields = findThread(thread.threadId(), lines); + assertNotNull(fields, "thread not found"); + assertEquals("WAITING", fields.state()); + String line = find(lines, "- parking to wait for <" + scopeId + ">"); + assertNotNull(line, "parking to wait line not found"); + + // JSON thread dump should have the expected parkBlocker + ThreadDump threadDump = dumpThreadsToJson(); + var ti = threadDump.rootThreadContainer() + .findThread(thread.threadId()) + .orElseThrow(); + assertEquals(scopeId, ti.parkBlocker()); + } finally { + thread.interrupt(); + thread.join(); + } + } + + /** + * Test thread names with control characters. + */ + @ParameterizedTest + @ValueSource(strings = { + "worker-\u0000nul", + "worker-\u0001soh", + "worker-\u0007bell", + "worker-\u000Bvertical-tab", + "worker-\u001Bescape", + "worker-\u001Funit-separator", + "worker-\nnewline", + "worker-\ttab", + "worker-\"quote", + "worker-\\backslash" + }) + void testThreadName(String threadName) throws Exception { + var thread = Thread.ofPlatform().name(threadName).start(LockSupport::park); + try { + long tid = thread.threadId(); + + // plain text thread dump + List lines = dumpThreadsToPlainText(); + ThreadFields fields = findThread(tid, lines); + assertNotNull(fields, "thread not found"); + assertEquals(threadName, fields.name()); + + // JSON thread dump + ThreadDump threadDump = dumpThreadsToJson(); + ThreadDump.ThreadInfo ti = threadDump.rootThreadContainer() + .findThread(tid) + .orElse(null); + assertNotNull(ti, "thread not found"); + assertEquals(threadName, ti.name()); + } finally { + LockSupport.unpark(thread); + thread.join(); + } + } + + /** + * Test thread CPU time. + */ + @ParameterizedTest + @MethodSource("threadFactories") + void testCpuTime(ThreadFactory factory) throws Exception { + var started = new CountDownLatch(1); + Thread thread = factory.newThread(() -> { + started.countDown(); + LockSupport.park(); + }); + try { + // start thread and wait for it to start executing + thread.start(); + started.await(); + long tid = thread.threadId(); + + boolean cpuTimeSupported = ManagementFactory.getThreadMXBean().isThreadCpuTimeSupported(); + + // plain text thread dump + List lines = dumpThreadsToPlainText(); + ThreadFields fields = findThread(tid, lines); + assertNotNull(fields, "thread not found"); + if (fields.isVirtual() || !cpuTimeSupported) { + assertEquals(-1L, fields.cpuTime()); + } else { + assertTrue(fields.cpuTime() != -1L); + } + + // JSON thread dump + ThreadDump threadDump = dumpThreadsToJson(); + ThreadDump.ThreadInfo ti = threadDump.rootThreadContainer() + .findThread(tid) + .orElse(null); + assertNotNull(ti, "thread not found"); + if (thread.isVirtual() || !cpuTimeSupported) { + assertFalse(ti.cpuTime().isPresent()); + } else { + long cpuTime = ti.cpuTime().orElseThrow(); + assertTrue(cpuTime != -1L); + } + } finally { + LockSupport.unpark(thread); + thread.join(); + } + } + /** * Test that dumpThreads throws if the output file already exists. */ @@ -703,7 +873,12 @@ void testNull() { /** * Represents the data for a thread found in a plain text thread dump. */ - private record ThreadFields(long tid, String name, boolean isVirtual, String state) { } + private record ThreadFields(long tid, + String name, + boolean isVirtual, + String threadObj, + String state, + long cpuTime) { } /** * Find a thread in the lines of a plain text thread dump. @@ -717,15 +892,57 @@ private ThreadFields findThread(long tid, List lines) { return null; } - // #3 "main" RUNNABLE 2025-04-18T15:22:12.012450Z - // #36 "" virtual WAITING 2025-04-18T15:22:12.012450Z - Pattern pattern = Pattern.compile("#(\\d+)\\s+\"([^\"]*)\"\\s+(virtual\\s+)?(\\w+)\\s+(.*)"); + // #3 "main" RUNNABLE cpuTime=1190000 2025-04-18T15:22:12.012450Z + // #36 "" virtual WAITING cpuTime=-1 2025-04-18T15:22:12.012450Z + Pattern pattern = Pattern.compile( + "#(\\d+)\\s+\"((?:\\\\.|[^\"\\\\])*)\"\\s+(virtual\\s+)?" + + "<([^>\\s]+@[0-9a-f]+)>\\s+(\\w+)" + + "\\s+cpuTime=(-?\\d+)\\s+(\\S+)"); Matcher matcher = pattern.matcher(line); - assertTrue(matcher.matches()); - String name = matcher.group(2); - boolean isVirtual = "virtual ".equals(matcher.group(3)); - String state = matcher.group(4); - return new ThreadFields(tid, name, isVirtual, state); + assertTrue(matcher.matches(), line); + String threadName = unescapeThreadName(matcher.group(2)); + boolean isVirtual = (matcher.group(3) != null); + String threadObj = matcher.group(4); + String state = matcher.group(5); + long cpuTime = Long.parseLong(matcher.group(6)); + return new ThreadFields(tid, threadName, isVirtual, threadObj, state, cpuTime); + } + + /** + * Decodes escape sequences in a thread name from a plain text thread dump. + */ + private static String unescapeThreadName(String value) { + StringBuilder result = new StringBuilder(value.length()); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c != '\\') { + result.append(c); + continue; + } + i++; + if (i == value.length()) { + throw new IllegalArgumentException("Trailing escape"); + } + switch (value.charAt(i)) { + case '"' -> result.append('"'); + case '\\' -> result.append('\\'); + case 'b' -> result.append('\b'); + case 'f' -> result.append('\f'); + case 'n' -> result.append('\n'); + case 'r' -> result.append('\r'); + case 't' -> result.append('\t'); + case 'u' -> { + if (i + 4 >= value.length()) { + throw new IllegalArgumentException("Incomplete Unicode escape"); + } + result.append((char) Integer.parseInt( + value.substring(i + 1, i + 5), 16)); + i += 4; + } + default -> throw new IllegalArgumentException("Unknown escape"); + } + } + return result.toString(); } /** @@ -792,6 +1009,28 @@ private void await(Thread thread, Thread.State expectedState) throws Interrupted } } + /** + * Waits for the given thread to wait at the given location + * ({@code .}). + */ + private static void awaitWaiting(Thread target, String location) throws InterruptedException { + int index = location.lastIndexOf('.'); + String className = location.substring(0, index); + String methodName = location.substring(index + 1); + boolean found = false; + while (!found) { + Thread.State state = target.getState(); + assertTrue(state != TERMINATED, "Thread has terminated"); + found = (state == WAITING || state == TIMED_WAITING) + && Arrays.stream(target.getStackTrace()) + .anyMatch(f -> f.getClassName().equals(className) + && f.getMethodName().equals(methodName)); + if (!found) { + Thread.sleep(20); + } + } + } + /** * Waits for the boolean value to become true. */ diff --git a/test/jdk/jdk/internal/misc/ThreadFlock/ThreadFlockTest.java b/test/jdk/jdk/internal/misc/ThreadFlock/ThreadFlockTest.java index 82ca2069f96..96042f3a836 100644 --- a/test/jdk/jdk/internal/misc/ThreadFlock/ThreadFlockTest.java +++ b/test/jdk/jdk/internal/misc/ThreadFlock/ThreadFlockTest.java @@ -382,8 +382,8 @@ private void testStartConfined(ThreadFlock flock, @Test void testAwaitAllWithNoThreads() throws Exception { try (var flock = ThreadFlock.open(null)) { - assertTrue(flock.awaitAll()); - assertTrue(flock.awaitAll(Duration.ofSeconds(1))); + assertTrue(flock.awaitAll(null)); + assertTrue(flock.awaitAll(null, Duration.ofSeconds(1))); } } @@ -403,7 +403,7 @@ void testAwaitAllWithThreads(ThreadFactory factory) throws Exception { }; Thread thread = factory.newThread(task); flock.start(thread); - assertTrue(flock.awaitAll()); + assertTrue(flock.awaitAll(null)); assertTrue(done.get()); } } @@ -424,7 +424,7 @@ void testAwaitAllWithTimeout1(ThreadFactory factory) throws Exception { flock.start(thread); long startMillis = millisTime(); - boolean done = flock.awaitAll(Duration.ofSeconds(30)); + boolean done = flock.awaitAll(null, Duration.ofSeconds(30)); assertTrue(done); checkDuration(startMillis, 1900, 20_000); } @@ -450,7 +450,7 @@ void testAwaitAllWithTimeout2(ThreadFactory factory) throws Exception { try { long startMillis = millisTime(); try { - flock.awaitAll(Duration.ofSeconds(2)); + flock.awaitAll(null, Duration.ofSeconds(2)); fail("awaitAll did not throw"); } catch (TimeoutException e) { checkDuration(startMillis, 1900, 20_000); @@ -481,7 +481,7 @@ void testAwaitAllWithTimeout3(ThreadFactory factory) throws Exception { try { for (int i = 0; i < 3; i++) { try { - flock.awaitAll(Duration.ofMillis(50)); + flock.awaitAll(null, Duration.ofMillis(50)); fail("awaitAll did not throw"); } catch (TimeoutException expected) { } } @@ -489,7 +489,7 @@ void testAwaitAllWithTimeout3(ThreadFactory factory) throws Exception { latch.countDown(); } - boolean done = flock.awaitAll(); + boolean done = flock.awaitAll(null); assertTrue(done); } } @@ -513,18 +513,18 @@ void testAwaitAllWithTimeout4(ThreadFactory factory) throws Exception { try { try { - flock.awaitAll(Duration.ofSeconds(0)); + flock.awaitAll(null, Duration.ofSeconds(0)); fail("awaitAll did not throw"); } catch (TimeoutException expected) { } try { - flock.awaitAll(Duration.ofSeconds(-1)); + flock.awaitAll(null, Duration.ofSeconds(-1)); fail("awaitAll did not throw"); } catch (TimeoutException expected) { } } finally { latch.countDown(); } - boolean done = flock.awaitAll(); + boolean done = flock.awaitAll(null); assertTrue(done); } } @@ -553,17 +553,17 @@ void testInterruptAwaitAll1(ThreadFactory factory) { // invoke awaitAll with interrupted status set. Thread.currentThread().interrupt(); try { - flock.awaitAll(); + flock.awaitAll(null); fail("awaitAll did not throw"); } catch (InterruptedException e) { // interrupted status should be clear assertFalse(Thread.currentThread().isInterrupted()); } - // invoke awaitAll(Duration) with interrupted status set. + // invoke awaitAll(null, Duration) with interrupted status set. Thread.currentThread().interrupt(); try { - flock.awaitAll(Duration.ofSeconds(30)); + flock.awaitAll(null, Duration.ofSeconds(30)); fail("awaitAll did not throw"); } catch (TimeoutException e) { fail("TimeoutException not expected"); @@ -606,7 +606,7 @@ void testInterruptAwaitAll2(ThreadFactory factory) { scheduleInterrupt(Thread.currentThread(), Duration.ofMillis(500)); try { - flock.awaitAll(); + flock.awaitAll(null); fail("awaitAll did not throw"); } catch (InterruptedException e) { // interrupted status should be clear @@ -615,7 +615,7 @@ void testInterruptAwaitAll2(ThreadFactory factory) { scheduleInterrupt(Thread.currentThread(), Duration.ofMillis(500)); try { - flock.awaitAll(Duration.ofSeconds(30)); + flock.awaitAll(null, Duration.ofSeconds(30)); fail("awaitAll did not throw"); } catch (TimeoutException e) { fail("TimeoutException not expected"); @@ -642,8 +642,8 @@ void testInterruptAwaitAll2(ThreadFactory factory) { void testAwaitAfterClose() throws Exception { var flock = ThreadFlock.open(null); flock.close(); - assertTrue(flock.awaitAll()); - assertTrue(flock.awaitAll(Duration.ofSeconds(1))); + assertTrue(flock.awaitAll(null)); + assertTrue(flock.awaitAll(null, Duration.ofSeconds(1))); } /** @@ -676,8 +676,8 @@ private void testAwaitAllConfined(ThreadFlock flock, var exception = new AtomicReference(); Thread thread = factory.apply(() -> { try { - flock.awaitAll(); - flock.awaitAll(Duration.ofMillis(1)); + flock.awaitAll(null); + flock.awaitAll(null, Duration.ofMillis(1)); } catch (Exception e) { exception.set(e); } @@ -709,7 +709,7 @@ void testWakeupAwaitAll1(ThreadFactory factory) throws Exception { // invoke awaitAll with permit try { flock.wakeup(); - assertFalse(flock.awaitAll()); + assertFalse(flock.awaitAll(null)); } finally { latch.countDown(); } @@ -743,7 +743,7 @@ void testWakeupAwaitAll2(ThreadFactory factory) throws Exception { flock.start(thread2); try { - assertFalse(flock.awaitAll()); + assertFalse(flock.awaitAll(null)); } finally { latch.countDown(); } @@ -950,7 +950,7 @@ void testToString() { void testNulls() { try (var flock = ThreadFlock.open(null)) { assertThrows(NullPointerException.class, () -> flock.start(null)); - assertThrows(NullPointerException.class, () -> flock.awaitAll(null)); + assertThrows(NullPointerException.class, () -> flock.awaitAll(null, null)); assertThrows(NullPointerException.class, () -> flock.containsThread(null)); } } diff --git a/test/lib/jdk/test/lib/threaddump/ThreadDump.java b/test/lib/jdk/test/lib/threaddump/ThreadDump.java index 77dd3dd8c03..2ff9893cca7 100644 --- a/test/lib/jdk/test/lib/threaddump/ThreadDump.java +++ b/test/lib/jdk/test/lib/threaddump/ThreadDump.java @@ -257,6 +257,24 @@ public String state() { return threadObj.get("state").asString(); } + /** + * Returns the thread's threadObj member or null. + */ + public String threadObj() { + return threadObj.getOrAbsent("threadObj") + .map(JSONValue::asString) + .orElse(null); + } + + /** + * Returns the thread's CPU time if available. + */ + public OptionalLong cpuTime() { + return threadObj.getOrAbsent("cpuTime") + .map(v -> OptionalLong.of(v.asLong())) + .orElseGet(OptionalLong::empty); + } + /** * Returns true if virtual thread. */ From 112d09b2711e539915d5a0af6f7ec273db71e0f7 Mon Sep 17 00:00:00 2001 From: Frederic Parain Date: Wed, 25 Nov 2026 20:21:34 +0000 Subject: [PATCH 90/95] 8397462: C1 crash: assert(state != nullptr) failed: state must be defined Reviewed-by: thartmann, kvn --- src/hotspot/cpu/aarch64/c1_LIRGenerator_aarch64.cpp | 8 +++++--- src/hotspot/cpu/arm/c1_LIRGenerator_arm.cpp | 8 +++++--- src/hotspot/cpu/ppc/c1_LIRGenerator_ppc.cpp | 9 ++++++--- src/hotspot/cpu/riscv/c1_LIRGenerator_riscv.cpp | 8 +++++--- src/hotspot/cpu/s390/c1_LIRGenerator_s390.cpp | 9 ++++++--- src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp | 9 ++++++--- .../c1/TestUnloadedArrayKlassAfterOOME_C1.java | 10 ++++++++++ 7 files changed, 43 insertions(+), 18 deletions(-) diff --git a/src/hotspot/cpu/aarch64/c1_LIRGenerator_aarch64.cpp b/src/hotspot/cpu/aarch64/c1_LIRGenerator_aarch64.cpp index 61855f1b40e..bad5d5436fe 100644 --- a/src/hotspot/cpu/aarch64/c1_LIRGenerator_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/c1_LIRGenerator_aarch64.cpp @@ -1176,6 +1176,11 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { // and therefore provide the state before the parameters have been consumed CodeEmitInfo* patching_info = nullptr; ciKlass* obj = ciObjArrayKlass::make(x->klass()); + + if (x->klass()->is_loaded() && !obj->is_loaded()) { + BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); + } + if (!x->klass()->is_loaded() || !obj->is_loaded() || PatchALot) { patching_info = state_for(x, x->state_before()); } @@ -1197,9 +1202,6 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { bool is_null_free = obj->is_loaded() && obj->as_array_klass()->is_elem_null_free(); CodeStub* slow_path = new NewObjectArrayStub(klass_reg, len, reg, info, is_null_free); - if (x->klass()->is_loaded() && !obj->is_loaded()) { - BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); - } klass2reg_with_patching(klass_reg, obj, patching_info); bool always_slow_path = is_null_free || is_flat; diff --git a/src/hotspot/cpu/arm/c1_LIRGenerator_arm.cpp b/src/hotspot/cpu/arm/c1_LIRGenerator_arm.cpp index 519aed16b5f..ac37ee0b1f3 100644 --- a/src/hotspot/cpu/arm/c1_LIRGenerator_arm.cpp +++ b/src/hotspot/cpu/arm/c1_LIRGenerator_arm.cpp @@ -986,6 +986,11 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { CodeEmitInfo* patching_info = nullptr; ciMetadata* obj = ciObjArrayKlass::make(x->klass()); + + if (x->klass()->is_loaded() && !obj->is_loaded()) { + BAILOUT("encountered unloaded_ciobjarrayklass due to out of memory error"); + } + if (!x->klass()->is_loaded() || !obj->is_loaded() || PatchALot) { patching_info = state_for(x, x->state_before()); } @@ -1000,9 +1005,6 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { CodeStub* slow_path = new NewObjectArrayStub(klass_reg, len, reg, info); - if (x->klass()->is_loaded() && !obj->is_loaded()) { - BAILOUT("encountered unloaded_ciobjarrayklass due to out of memory error"); - } klass2reg_with_patching(klass_reg, obj, patching_info); __ allocate_array(reg, len, tmp1, tmp2, tmp3, tmp4, T_OBJECT, klass_reg, slow_path); diff --git a/src/hotspot/cpu/ppc/c1_LIRGenerator_ppc.cpp b/src/hotspot/cpu/ppc/c1_LIRGenerator_ppc.cpp index be7b297a0f6..a50796927b1 100644 --- a/src/hotspot/cpu/ppc/c1_LIRGenerator_ppc.cpp +++ b/src/hotspot/cpu/ppc/c1_LIRGenerator_ppc.cpp @@ -889,6 +889,11 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { // the state before the parameters have been consumed. CodeEmitInfo* patching_info = nullptr; ciKlass* obj = ciObjArrayKlass::make(x->klass()); + + if (x->klass()->is_loaded() && !obj->is_loaded()) { + BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); + } + if (!x->klass()->is_loaded() || !obj->is_loaded() || PatchALot) { patching_info = state_for(x, x->state_before()); } @@ -910,9 +915,7 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { bool is_null_free = obj->is_loaded() && obj->as_array_klass()->is_elem_null_free(); CodeStub* slow_path = new NewObjectArrayStub(klass_reg, len, reg, info, is_null_free); - if (x->klass()->is_loaded() && !obj->is_loaded()) { - BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); - } + klass2reg_with_patching(klass_reg, obj, patching_info); bool always_slow_path = is_null_free || is_flat; __ allocate_array(reg, len, tmp1, tmp2, tmp3, tmp4, T_OBJECT, klass_reg, slow_path, true /*zero_array*/, always_slow_path); diff --git a/src/hotspot/cpu/riscv/c1_LIRGenerator_riscv.cpp b/src/hotspot/cpu/riscv/c1_LIRGenerator_riscv.cpp index 6c18a6c7e5d..87815c66457 100644 --- a/src/hotspot/cpu/riscv/c1_LIRGenerator_riscv.cpp +++ b/src/hotspot/cpu/riscv/c1_LIRGenerator_riscv.cpp @@ -1045,6 +1045,11 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { // and therefore provide the state before the parameters have been consumed CodeEmitInfo* patching_info = nullptr; ciKlass* obj = ciObjArrayKlass::make(x->klass()); + + if (x->klass()->is_loaded() && !obj->is_loaded()) { + BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); + } + if (!x->klass()->is_loaded() || !obj->is_loaded() || PatchALot) { patching_info = state_for(x, x->state_before()); } @@ -1067,9 +1072,6 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { CodeStub* slow_path = new NewObjectArrayStub(klass_reg, len, reg, info, is_null_free); - if (x->klass()->is_loaded() && !obj->is_loaded()) { - BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); - } klass2reg_with_patching(klass_reg, obj, patching_info); bool always_slow_path = is_null_free || is_flat; __ allocate_array(reg, len, tmp1, tmp2, tmp3, tmp4, T_OBJECT, klass_reg, slow_path, true /*zero_array*/, always_slow_path); diff --git a/src/hotspot/cpu/s390/c1_LIRGenerator_s390.cpp b/src/hotspot/cpu/s390/c1_LIRGenerator_s390.cpp index 3d9a81489d0..758445c04b6 100644 --- a/src/hotspot/cpu/s390/c1_LIRGenerator_s390.cpp +++ b/src/hotspot/cpu/s390/c1_LIRGenerator_s390.cpp @@ -823,6 +823,11 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { // and therefore provide the state before the parameters have been consumed. CodeEmitInfo* patching_info = nullptr; ciKlass* obj = ciObjArrayKlass::make(x->klass()); + + if (x->klass()->is_loaded() && !obj->is_loaded()) { + BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); + } + if (!x->klass()->is_loaded() || !obj->is_loaded() || PatchALot) { patching_info = state_for (x, x->state_before()); } @@ -842,9 +847,7 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { bool is_null_free = obj->is_loaded() && obj->as_array_klass()->is_elem_null_free(); CodeStub* slow_path = new NewObjectArrayStub(klass_reg, len, reg, info, is_null_free); - if (x->klass()->is_loaded() && !obj->is_loaded()) { - BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); - } + klass2reg_with_patching(klass_reg, obj, patching_info); __ allocate_array(reg, len, tmp1, tmp2, tmp3, tmp4, T_OBJECT, klass_reg, slow_path, true, is_null_free || is_flat); diff --git a/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp b/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp index 6b50c744fed..683ddc3d4ba 100644 --- a/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp +++ b/src/hotspot/cpu/x86/c1_LIRGenerator_x86.cpp @@ -1177,6 +1177,11 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { // and therefore provide the state before the parameters have been consumed CodeEmitInfo* patching_info = nullptr; ciKlass* obj = ciObjArrayKlass::make(x->klass()); + + if (x->klass()->is_loaded() && !obj->is_loaded()) { + BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); + } + if (!x->klass()->is_loaded() || !obj->is_loaded() || PatchALot) { patching_info = state_for(x, x->state_before()); } @@ -1199,9 +1204,7 @@ void LIRGenerator::do_NewObjectArray(NewObjectArray* x) { bool is_null_free = obj->is_loaded() && obj->as_array_klass()->is_elem_null_free(); CodeStub* slow_path = new NewObjectArrayStub(klass_reg, len, reg, info, is_null_free); - if (x->klass()->is_loaded() && !obj->is_loaded()) { - BAILOUT("encountered unloaded ciobjarrayklass due to out of memory error"); - } + klass2reg_with_patching(klass_reg, obj, patching_info); bool always_slow_path = is_null_free || is_flat; __ allocate_array(reg, len, tmp1, tmp2, tmp3, tmp4, T_OBJECT, klass_reg, slow_path, true /*zero_array*/, always_slow_path); diff --git a/test/hotspot/jtreg/compiler/c1/TestUnloadedArrayKlassAfterOOME_C1.java b/test/hotspot/jtreg/compiler/c1/TestUnloadedArrayKlassAfterOOME_C1.java index 86c0b2ded36..c8341f35e45 100644 --- a/test/hotspot/jtreg/compiler/c1/TestUnloadedArrayKlassAfterOOME_C1.java +++ b/test/hotspot/jtreg/compiler/c1/TestUnloadedArrayKlassAfterOOME_C1.java @@ -50,6 +50,7 @@ public static void main(String[] args) throws Exception { options.add("-Xmx12m"); options.add("-XX:CompileCommand=compileonly," + getTestClass() + "::testNew"); options.add("-XX:CompileCommand=compileonly," + getTestClass() + "::testArrayCopy"); + options.add("-XX:CompileCommand=compileonly," + getTestClass() + "::testNewWithoutCatch"); options.add(getTestClass()); OutputAnalyzer oa = ProcessTools.executeTestJava(options); @@ -93,6 +94,10 @@ static void testArrayCopy(Object[] array) { } } + static Object[] testNewWithoutCatch() { + return new Value[10]; + } + public static void main(String[] args) { Object[] array = new Object[10]; Value value = new Value(); @@ -106,6 +111,11 @@ public static void main(String[] args) { } testNew(); testArrayCopy(array); + try { + testNewWithoutCatch(); + } catch (OutOfMemoryError expected) { + // Ignore + } } } } From fa4fd40faf916f87a0d74a13051291e92cee4d87 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 25 Nov 2026 21:02:46 +0000 Subject: [PATCH 91/95] 8397728: [Linux] font configuration needs to work even if only variable fonts are installed Reviewed-by: kizune, azvegint --- src/java.desktop/unix/native/common/awt/fontpath.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/java.desktop/unix/native/common/awt/fontpath.c b/src/java.desktop/unix/native/common/awt/fontpath.c index a7c2dfe763a..bfe8abfa6c7 100644 --- a/src/java.desktop/unix/native/common/awt/fontpath.c +++ b/src/java.desktop/unix/native/common/awt/fontpath.c @@ -982,7 +982,7 @@ Java_sun_font_FontConfigManager_getFontConfig jarray fcFontArr = NULL; FcCharSet *unionCharset = NULL; FcCharSet *prevUnionCharset = NULL; - int expectedWeight, expectedSlant, skippedVarFont; + int expectedWeight, expectedSlant, skippedVarFont, skipVarFonts; fcCompFontObj = (*env)->GetObjectArrayElement(env, fcCompFontArray, i); fcNameStr = @@ -1072,6 +1072,7 @@ Java_sun_font_FontConfigManager_getFontConfig (*FcPatternGetInteger)(pattern, FC_WEIGHT, 0, &expectedWeight); (*FcPatternGetInteger)(pattern, FC_SLANT, 0, &expectedSlant); skippedVarFont = 0; + skipVarFonts = 1; for (j=0; jfonts[j]; FcChar8 *fontformat; @@ -1080,7 +1081,7 @@ Java_sun_font_FontConfigManager_getFontConfig int weight, slant; fontformat = NULL; - if (fontCount == 0) { + if (skipVarFonts && (fontCount == 0) && (j < (nfonts / 2))) { // Query to see if it is a variable font. 0x8000000 is used as the // font index to tell fontconfig you want the variable font info. // NULL is returned from FcFreeTypeQuery if it is not a variable font. @@ -1111,6 +1112,12 @@ Java_sun_font_FontConfigManager_getFontConfig && (strcmp((char*)fontformat, "CFF") != 0) #endif ) { + /* If we reach the end without finding non-variable fonts, reset */ + if ((skipVarFonts == 1) && (fontCount == 0) && (j == (nfonts - 1))) { + skipVarFonts = 0; + skippedVarFont = 0; + j = -1; + } continue; } From 74707e4e48bdc5f888ddada12d0a4defb5ffc6c0 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 25 Nov 2026 23:05:22 +0000 Subject: [PATCH 92/95] 8398247: [Leyden] Arrays should have its own DataKind::ArrayKlass metadata in AOT code Reviewed-by: iveresov, iklam --- src/hotspot/share/code/aotCodeCache.cpp | 146 +++++++++++++++++------- src/hotspot/share/code/aotCodeCache.hpp | 25 ++-- 2 files changed, 120 insertions(+), 51 deletions(-) diff --git a/src/hotspot/share/code/aotCodeCache.cpp b/src/hotspot/share/code/aotCodeCache.cpp index f8ffe513a38..bef51a9a049 100644 --- a/src/hotspot/share/code/aotCodeCache.cpp +++ b/src/hotspot/share/code/aotCodeCache.cpp @@ -3722,7 +3722,9 @@ Metadata* AOTCodeReader::read_metadata(JavaThread* thread) { } else if (kind == DataKind::No_Data) { m = (Metadata*)Universe::non_oop_word(); } else if (kind == DataKind::Klass) { - m = (Metadata*)read_klass(thread); + m = (Metadata*)read_klass(); + } else if (kind == DataKind::ArrayKlass) { + m = (Metadata*)read_array_klass(thread); } else if (kind == DataKind::Method) { m = (Metadata*)read_method(); } else if (kind == DataKind::MethodCnts) { @@ -3861,32 +3863,86 @@ Method* AOTCodeReader::read_method() { } bool AOTCodeCache::write_klass(Klass* klass) { - uint array_dim = 0; + if (klass->is_array_klass()) { + return write_array_klass(ArrayKlass::cast(klass)); + } + ResourceMark rm; + InstanceKlass* ik = InstanceKlass::cast(klass); + if (AOTCacheAccess::can_generate_aot_code_for(ik)) { + DataKind kind = DataKind::Klass; + if (!write_kind(kind)) { + return false; + } + narrowPtr klass_narrow_ptr = AOTCacheAccess::to_narrow_ptr(klass); + if (!write_int((int)checked_cast(klass_narrow_ptr))) { + return false; + } + log_debug(aot, codecache, metadata)("%d (A%d): Registered klass: %s%s @ 0x%08x", + compile_id(), comp_level(), klass->external_name(), + (!klass->is_instance_klass() ? "" : (InstanceKlass::cast(klass)->is_initialized() ? + " (initialized)" : " (not-initialized)")), + cast_to_u4(klass_narrow_ptr)); + return true; + } + log_debug(aot, codecache, metadata)("%d (A%d): Klass is not registered: %s%s", + compile_id(), comp_level(), klass->external_name(), + (!klass->is_instance_klass() ? "" : (InstanceKlass::cast(klass)->is_initialized() ? + " (initialized)" : " (not-initialized)"))); + set_lookup_failed(); + return false; +} + +Klass* AOTCodeReader::read_klass() { + narrowPtr klass_narrow_ptr; + if (!read_int((int*)&klass_narrow_ptr)) { + return nullptr; + } + Klass* k = AOTCacheAccess::narrow_ptr_to_klass(klass_narrow_ptr); + if (k == nullptr || !AOTMetaspace::in_aot_cache((address)k) || !k->is_klass()) { + // Something changed in CDS + set_lookup_failed("Klass is not in AOT cache"); + log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed klass: " INTPTR_FORMAT " is not in AOT cache", + compile_id(), comp_level(), p2i((address)k)); + return nullptr; + } + ResourceMark rm; + if (!k->is_instance_klass() || !InstanceKlass::cast(k)->is_loaded()) { + set_lookup_failed("Klass is not loaded"); + log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed for klass %s: not loaded", + compile_id(), comp_level(), k->external_name()); + return nullptr; + } + log_debug(aot, codecache, metadata)("%d (A%d): Found klass %s", + compile_id(), comp_level(), k->external_name()); + return k; +} + +bool AOTCodeCache::write_array_klass(ArrayKlass* klass) { + uint array_dim = klass->dimension(); uint array_desc = ArrayProperties::Invalid().value(); - bool can_write = true; + Klass* bottom = klass; if (klass->is_objArray_klass()) { // We must check klass and its bottom_klass. - can_write = AOTCacheAccess::can_generate_aot_code(klass); ObjArrayKlass* oak = ObjArrayKlass::cast(klass); - array_dim = oak->dimension(); + bottom = oak->bottom_klass(); // Preserve property of object array if (klass->is_flatArray_klass()) { array_desc = ArrayDescription::flat(oak->properties(), FlatArrayKlass::cast(klass)->layout_kind()).value(); } else if (klass->is_refArray_klass()) { array_desc = ArrayDescription::reference(oak->properties()).value(); } - klass = oak->bottom_klass(); // overwrites klass } - if (klass->is_instance_klass()) { - InstanceKlass* ik = InstanceKlass::cast(klass); + bool can_write = AOTCacheAccess::can_generate_aot_code(klass); + if (bottom->is_instance_klass()) { + InstanceKlass* ik = InstanceKlass::cast(bottom); can_write &= AOTCacheAccess::can_generate_aot_code_for(ik); } else { - assert(klass->is_typeArray_klass(), "must be"); - can_write &= AOTCacheAccess::can_generate_aot_code(klass); + assert(bottom->is_typeArray_klass(), "must be"); + can_write &= AOTCacheAccess::can_generate_aot_code(bottom); } ResourceMark rm; if (can_write) { - DataKind kind = DataKind::Klass; + DataKind kind = DataKind::ArrayKlass; if (!write_kind(kind)) { return false; } @@ -3898,27 +3954,27 @@ bool AOTCodeCache::write_klass(Klass* klass) { if (!write_int(array_desc)) { return false; } - narrowPtr klass_narrow_ptr = AOTCacheAccess::to_narrow_ptr(klass); + narrowPtr klass_narrow_ptr = AOTCacheAccess::to_narrow_ptr(bottom); if (!write_int((int)checked_cast(klass_narrow_ptr))) { return false; } log_debug(aot, codecache, metadata)("%d (A%d): Registered klass: %s%s%s @ 0x%08x", compile_id(), comp_level(), klass->external_name(), - (!klass->is_instance_klass() ? "" : (InstanceKlass::cast(klass)->is_initialized() ? - " (initialized)" : " (not-initialized)")), - (array_dim > 0 ? " (object array)" : ""), cast_to_u4(klass_narrow_ptr)); + (!bottom->is_instance_klass() ? "" : (InstanceKlass::cast(bottom)->is_initialized() ? + " (initialized)" : " (not-initialized)")), + (array_dim > 0 ? " (array)" : ""), cast_to_u4(klass_narrow_ptr)); return true; } log_debug(aot, codecache, metadata)("%d (A%d): Klass is not registered: %s%s%s", compile_id(), comp_level(), klass->external_name(), - (!klass->is_instance_klass() ? "" : (InstanceKlass::cast(klass)->is_initialized() ? - " (initialized)" : " (not-initialized)")), - (array_dim > 0 ? " (object array)" : "")); + (!bottom->is_instance_klass() ? "" : (InstanceKlass::cast(bottom)->is_initialized() ? + " (initialized)" : " (not-initialized)")), + (array_dim > 0 ? " (array)" : "")); set_lookup_failed(); return false; } -Klass* AOTCodeReader::read_klass(JavaThread* thread) { +Klass* AOTCodeReader::read_array_klass(JavaThread* thread) { uint array_dim; if (!read_int((int*)&array_dim)) { return nullptr; @@ -3932,14 +3988,13 @@ Klass* AOTCodeReader::read_klass(JavaThread* thread) { return nullptr; } Klass* k = AOTCacheAccess::narrow_ptr_to_klass(klass_narrow_ptr); - if (k == nullptr || !AOTMetaspace::in_aot_cache((address)k)) { + if (k == nullptr || !AOTMetaspace::in_aot_cache((address)k) || !k->is_klass()) { // Something changed in CDS set_lookup_failed("Klass is not in AOT cache"); log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed klass: " INTPTR_FORMAT " is not in AOT cache", compile_id(), comp_level(), p2i((address)k)); return nullptr; } - assert(k->is_klass(), "sanity"); ResourceMark rm; if (k->is_instance_klass() && !InstanceKlass::cast(k)->is_loaded()) { set_lookup_failed("Klass is not loaded"); @@ -3947,28 +4002,38 @@ Klass* AOTCodeReader::read_klass(JavaThread* thread) { compile_id(), comp_level(), k->external_name()); return nullptr; } - // FIXME: The metadata for arrays should have its own DataKind::ArrayKlass. - if (array_dim > 0) { - assert(k->is_instance_klass() || k->is_typeArray_klass(), "sanity check"); - Klass* ak = k->array_klass_or_null(array_dim); - if (ak != nullptr && array_desc != ArrayProperties::Invalid().value()) { - ArrayDescription adesc = ArrayDescription::from_value(array_desc); - ak = ObjArrayKlass::cast(ak)->klass_from_description(adesc, thread); - } - if (ak == nullptr) { - set_lookup_failed("Lookup failed for array klass"); - log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed for %d-dimensions array klass %s", + if (!k->is_instance_klass() && !k->is_typeArray_klass()) { + set_lookup_failed("Klass is not instance or array"); + log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed for klass %s: not instance or array", + compile_id(), comp_level(), k->external_name()); + return nullptr; + } + if (array_dim < 1 || array_dim > 255) { + set_lookup_failed("Lookup failed for array klass"); + log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed for array klass %s: wrong dimension %u", + compile_id(), comp_level(), k->external_name(), array_dim); + return nullptr; + } + Klass* ak = k->array_klass_or_null(array_dim); + if (ak != nullptr && array_desc != ArrayProperties::Invalid().value()) { + if (!ak->is_objArray_klass()) { + set_lookup_failed("Lookup failed for object array klass"); + log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed for %d-dimensions array klass %s: not object array", compile_id(), comp_level(), array_dim, k->external_name()); return nullptr; } - log_debug(aot, codecache, metadata)("%d (A%d): Found %d-dimensions array klass %s", + ArrayDescription adesc = ArrayDescription::from_value(array_desc); + ak = ObjArrayKlass::cast(ak)->klass_from_description(adesc, thread); + } + if (ak == nullptr) { + set_lookup_failed("Lookup failed for array klass"); + log_debug(aot, codecache, metadata)("%d (A%d): Lookup failed for %d-dimensions array klass %s", compile_id(), comp_level(), array_dim, k->external_name()); - return ak; - } else { - log_debug(aot, codecache, metadata)("%d (A%d): Found klass %s", - compile_id(), comp_level(), k->external_name()); - return k; + return nullptr; } + log_debug(aot, codecache, metadata)("%d (A%d): Found %d-dimensions array klass %s", + compile_id(), comp_level(), array_dim, k->external_name()); + return ak; } bool AOTCodeCache::write_oop(jobject& jo) { @@ -4086,8 +4151,9 @@ oop AOTCodeReader::read_oop(JavaThread* thread) { return nullptr; } else if (kind == DataKind::No_Data) { return cast_to_oop(Universe::non_oop_word()); - } else if (kind == DataKind::Klass) { - Klass* k = read_klass(thread); + } else if (kind == DataKind::Klass || kind == DataKind::ArrayKlass) { + Klass* k = (kind == DataKind::Klass) ? read_klass() : + read_array_klass(thread); if (k == nullptr) { return nullptr; } diff --git a/src/hotspot/share/code/aotCodeCache.hpp b/src/hotspot/share/code/aotCodeCache.hpp index 85c66785456..a193badbef7 100644 --- a/src/hotspot/share/code/aotCodeCache.hpp +++ b/src/hotspot/share/code/aotCodeCache.hpp @@ -578,16 +578,17 @@ class AOTStubData : public StackObj { #define AOTCODECACHE_DECLARE_FUN(type, name, func) type _saved_ ## name; enum class DataKind: int { - No_Data = -1, - Null = 0, - Klass = 1, - Method = 2, - String = 3, - MH_Oop = 4, - Primitive = 5, // primitive Class object - SysLoader = 6, // java_system_loader - PlaLoader = 7, // java_platform_loader - MethodCnts= 8 + No_Data = -1, + Null = 0, + Klass = 1, + ArrayKlass = 2, + Method = 3, + String = 4, + MH_Oop = 5, + Primitive = 6, // primitive Class object + SysLoader = 7, // java_system_loader + PlaLoader = 8, // java_platform_loader + MethodCnts = 9 }; struct AOTCodeEntryStats; @@ -974,6 +975,7 @@ class AOTCodeCache : public CHeapObj { void log_stats_on_exit(AOTCodeEntryStats& stats); bool write_klass(Klass* klass); + bool write_array_klass(ArrayKlass* klass); bool write_method(Method* method); bool write_fingerprint(Method* method); @@ -1191,7 +1193,8 @@ class AOTCodeReader { const char* _failure; // Failed to lookup for info (skip only this code load) void set_lookup_failed(const char* failure) { _failure = failure; } - Klass* read_klass(JavaThread* thread); + Klass* read_klass(); + Klass* read_array_klass(JavaThread* thread); Method* read_method(); bool verify_fingerprint(Method* method); From 2dfdbe89b7fc900f8dac8202bfdfbf18616d4f1b Mon Sep 17 00:00:00 2001 From: Fei Yang Date: Thu, 26 Nov 2026 00:39:02 +0000 Subject: [PATCH 93/95] 8398282: Fix missing diagnostic unlock in TestHumongousAllocFailureRecovery Reviewed-by: kvn, mdoerr, shade --- .../generational/TestHumongousAllocFailureRecovery.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java b/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java index 6a4d1ae15f9..bfe0d56db8a 100644 --- a/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java +++ b/test/hotspot/jtreg/gc/shenandoah/generational/TestHumongousAllocFailureRecovery.java @@ -29,11 +29,11 @@ * @requires vm.gc.Shenandoah * @library /test/lib * @run main/othervm - * -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC - * -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=passive + * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational + * -XX:+UnlockDiagnosticVMOptions -XX:ShenandoahGCHeuristics=passive * -Xmx128m -Xms128m - * -XX:ShenandoahRegionSize=1m -XX:+AlwaysPreTouch - * -XX:ConcGCThreads=1 -XX:ParallelGCThreads=1 + * -XX:+UnlockExperimentalVMOptions -XX:ShenandoahRegionSize=1m + * -XX:+AlwaysPreTouch -XX:ConcGCThreads=1 -XX:ParallelGCThreads=1 * TestHumongousAllocFailureRecovery */ From ff502d5ba051b209dc81bcd2806605cb31aa7cb8 Mon Sep 17 00:00:00 2001 From: Dingli Zhang Date: Thu, 26 Nov 2026 01:25:39 +0000 Subject: [PATCH 94/95] 8398306: Remove obsolete C1 lir_xloadbarrier_test opcode Reviewed-by: fyang, eosterlund, stefank --- src/hotspot/share/c1/c1_LIR.cpp | 6 ------ src/hotspot/share/c1/c1_LIR.hpp | 5 ----- 2 files changed, 11 deletions(-) diff --git a/src/hotspot/share/c1/c1_LIR.cpp b/src/hotspot/share/c1/c1_LIR.cpp index 9d0048fa1da..167686e3fad 100644 --- a/src/hotspot/share/c1/c1_LIR.cpp +++ b/src/hotspot/share/c1/c1_LIR.cpp @@ -1275,12 +1275,6 @@ void LIR_List::set_cmp_oprs(LIR_Op* op) { _cmp_opr1 = op->as_OpCompareAndSwap()->result_opr(); _cmp_opr2 = LIR_OprFact::intConst(1); break; -#if INCLUDE_ZGC - case lir_xloadbarrier_test: - _cmp_opr1 = FrameMap::as_opr(t1); - _cmp_opr2 = LIR_OprFact::intConst(0); - break; -#endif default: break; } diff --git a/src/hotspot/share/c1/c1_LIR.hpp b/src/hotspot/share/c1/c1_LIR.hpp index 56eadbbfd4c..c28ff65e5c9 100644 --- a/src/hotspot/share/c1/c1_LIR.hpp +++ b/src/hotspot/share/c1/c1_LIR.hpp @@ -1017,11 +1017,6 @@ enum LIR_Code { , begin_opAssert , lir_assert , end_opAssert -#if INCLUDE_ZGC - , begin_opXLoadBarrierTest - , lir_xloadbarrier_test - , end_opXLoadBarrierTest -#endif }; From 5aa798a73df225cbb8198333469825e22fb66bcc Mon Sep 17 00:00:00 2001 From: Jatin Bhateja Date: Thu, 26 Nov 2026 04:49:28 +0000 Subject: [PATCH 95/95] 8398034: C2: [VectorAPI] Assertion failure due to wrong type in check_vbox Reviewed-by: thartmann, qamai --- src/hotspot/share/opto/vectorIntrinsics.cpp | 1 + .../TestRearrangeUninitializedMaskClass.java | 66 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 test/hotspot/jtreg/compiler/vectorapi/TestRearrangeUninitializedMaskClass.java diff --git a/src/hotspot/share/opto/vectorIntrinsics.cpp b/src/hotspot/share/opto/vectorIntrinsics.cpp index 0da22c6a133..33a7521fe35 100644 --- a/src/hotspot/share/opto/vectorIntrinsics.cpp +++ b/src/hotspot/share/opto/vectorIntrinsics.cpp @@ -2066,6 +2066,7 @@ bool LibraryCallKit::inline_vector_rearrange() { mask_klass->const_oop() == nullptr || !is_klass_initialized(mask_klass))) { log_if_needed(" ** mask_klass argument not initialized"); + return false; } if (!arch_supports_vector(Op_AndV, num_elem, elem_bt, VecMaskNotUsed)) { log_if_needed(" ** not supported: arity=2 op=and vlen=%d etype=%s ismask=no", diff --git a/test/hotspot/jtreg/compiler/vectorapi/TestRearrangeUninitializedMaskClass.java b/test/hotspot/jtreg/compiler/vectorapi/TestRearrangeUninitializedMaskClass.java new file mode 100644 index 00000000000..11cd3909907 --- /dev/null +++ b/test/hotspot/jtreg/compiler/vectorapi/TestRearrangeUninitializedMaskClass.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8398034 + * @summary Assertion failure due to wrong type in check_vbox when the mask class is not initialized + * @modules jdk.incubator.vector + * + * @run main/othervm -Xcomp -XX:-TieredCompilation ${test.main.class} + */ + +package compiler.vectorapi; + +import jdk.incubator.vector.ShortVector; +import jdk.incubator.vector.VectorMask; +import jdk.incubator.vector.VectorShuffle; +import jdk.incubator.vector.VectorSpecies; + +public class TestRearrangeUninitializedMaskClass { + static final VectorSpecies S128 = ShortVector.SPECIES_128; + static final VectorSpecies S256 = ShortVector.SPECIES_256; + static final short[] a = new short[S256.length()]; + static final int[] idx = new int[S256.length()]; + static final boolean[] m = new boolean[S256.length()]; + + static void unmasked256() { + ShortVector.fromArray(S256, a, 0).rearrange(VectorShuffle.fromArray(S256, idx, 0)).intoArray(a, 0); + } + + static void masked128() { + ShortVector.fromArray(S128, a, 0).rearrange(VectorShuffle.fromArray(S128, idx, 0), + VectorMask.fromArray(S128, m, 0)).intoArray(a, 0); + } + + static void masked256() { + ShortVector.fromArray(S256, a, 0).rearrange(VectorShuffle.fromArray(S256, idx, 0), + VectorMask.fromArray(S256, m, 0)).intoArray(a, 0); + } + + public static void main(String[] args) { + unmasked256(); + masked128(); + masked256(); + } +}