You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ro...@apache.org on 2025/09/05 12:05:25 UTC

(sling-org-apache-sling-xss) 01/02: SLING-12930 - XSS API fails to build and run with Java 25 due to missing Unsafe.ensureClassInitialized

This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch issue/test-java-25
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-xss.git

commit e011f8e0d03c9a10a6c07b8b9569f0997afc9df9
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Fri Sep 5 14:03:09 2025 +0200

    SLING-12930 - XSS API fails to build and run with Java 25 due to missing Unsafe.ensureClassInitialized
    
    Fallback to MethodHandles.Lookup for initialising the class if the Unsafe method does not work.
    
    This API is available as of Java 15 so as long as we support Java 11 we cannot rely on it
    exclusively.
---
 .../org/apache/sling/xss/impl/AntiSamyPolicyAdapter.java   | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/src/main/java/org/apache/sling/xss/impl/AntiSamyPolicyAdapter.java b/src/main/java/org/apache/sling/xss/impl/AntiSamyPolicyAdapter.java
index 2028305..e524fbc 100644
--- a/src/main/java/org/apache/sling/xss/impl/AntiSamyPolicyAdapter.java
+++ b/src/main/java/org/apache/sling/xss/impl/AntiSamyPolicyAdapter.java
@@ -18,7 +18,10 @@
  */
 package org.apache.sling.xss.impl;
 
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
 import java.lang.reflect.Field;
+import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -247,13 +250,20 @@ public class AntiSamyPolicyAdapter {
             Field guards = HtmlPolicyBuilder.class.getDeclaredField("ATTRIBUTE_GUARDS");
 
             // although it looks distasteful, the 'sun.misc.Unsafe' approach is the only one that
-            // works with Java 8 through 17 .
+            // works with Java 8 through 21
             Field f = Unsafe.class.getDeclaredField("theUnsafe");
             f.setAccessible(true);
             Unsafe unsafe = (Unsafe) f.get(null);
 
             // required to be able to get the static field base
-            unsafe.ensureClassInitialized(HtmlPolicyBuilder.class);
+            try {
+                unsafe.ensureClassInitialized(HtmlPolicyBuilder.class);
+            } catch (NoSuchMethodError uoe) {
+                // fallback for Java 22+, see https://bugs.openjdk.org/browse/JDK-8316160
+                Lookup lookup = MethodHandles.lookup();
+                Method ensureInitialized = Lookup.class.getDeclaredMethod("ensureInitialized", Class.class);
+                ensureInitialized.invoke(lookup, HtmlPolicyBuilder.class);
+            }
 
             Object fieldBase = unsafe.staticFieldBase(guards);
             long fieldOffset = unsafe.staticFieldOffset(guards);