View Javadoc
1   /*
2    * Copyright 2025 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.internal;
17  
18  import io.netty.util.internal.logging.InternalLogger;
19  import io.netty.util.internal.logging.InternalLoggerFactory;
20  
21  import java.lang.foreign.Arena;
22  import java.lang.foreign.FunctionDescriptor;
23  import java.lang.foreign.Linker;
24  import java.lang.foreign.MemorySegment;
25  import java.lang.foreign.SymbolLookup;
26  import java.lang.foreign.ValueLayout;
27  import java.lang.invoke.MethodHandle;
28  import java.lang.invoke.MethodHandles;
29  import java.nio.ByteBuffer;
30  import java.util.Locale;
31  
32  import static java.lang.invoke.MethodType.methodType;
33  
34  /**
35   * Allocates direct buffers with malloc and free from libc, linked through the Foreign Function & Memory API.
36   * <p>
37   * The FFM API is compiled against the {@code netty-ffm-stub} module. It and the signature-polymorphic
38   * {@link MethodHandle} calls are only used from the nested classes, which are only loaded on Java versions that
39   * have the FFM API, so this class still loads and verifies where it is missing (e.g. Android).
40   */
41  public class CleanerJava24Linker implements Cleaner {
42      private static final InternalLogger logger;
43      private static final boolean SUPPORTED;
44  
45      static {
46          Throwable error;
47          if (System.getProperty("org.graalvm.nativeimage.imagecode") != null) {
48              // A native image can only link the downcalls that were registered when the image was built, and
49              // linking on first use is too late to fall back to another cleaner, so a native image never uses
50              // this one. We don't use PlatformDependent0 or the logger here, since this class may be initialized
51              // at build time.
52              logger = null;
53              error = new UnsupportedOperationException(
54                      "Linking to malloc and free is not supported in a native image.");
55          } else {
56              logger = InternalLoggerFactory.getInstance(CleanerJava24Linker.class);
57              // Only attempt to use MemorySegments on Java 24 or greater, where warnings about Unsafe
58              // memory access operations start to appear.
59              // The following JDK bugs do NOT affect our implementation because the memory segments we
60              // create are associated with the GLOBAL_SESSION:
61              // - https://bugs.openjdk.org/browse/JDK-8357145
62              // - https://bugs.openjdk.org/browse/JDK-8357268
63              if (PlatformDependent0.javaVersion() >= 24) {
64                  try {
65                      error = Symbols.UNAVAILABILITY_CAUSE;
66                  } catch (Throwable throwable) {
67                      error = throwable;
68                  }
69              } else {
70                  error = new UnsupportedOperationException("java.lang.foreign.MemorySegment unavailable");
71              }
72              if (error == null) {
73                  logger.debug("java.nio.ByteBuffer.cleaner(): available");
74              } else {
75                  logger.debug("java.nio.ByteBuffer.cleaner(): unavailable", error);
76              }
77          }
78          SUPPORTED = error == null;
79      }
80  
81      static boolean isSupported() {
82          return SUPPORTED;
83      }
84  
85      @Override
86      public CleanableDirectBuffer allocate(int capacity) {
87          return CleanableDirectBufferImpl.allocate(capacity);
88      }
89  
90      @Override
91      public void freeDirectBuffer(ByteBuffer buffer) {
92          throw new UnsupportedOperationException("Cannot clean arbitrary ByteBuffer instances");
93      }
94  
95      @Override
96      public boolean hasExpensiveClean() {
97          return false;
98      }
99  
100     static long malloc(int capacity) {
101         // Always allocate at least 1 byte, to avoid relying on non-portable behavior
102         // of malloc(3) for zero size allocations.
103         long addr = Holder.malloc(Math.max(capacity, 1L));
104         if (addr == 0) {
105             throw new OutOfMemoryError("malloc(2) failed to allocate " + capacity + " bytes");
106         }
107         return addr;
108     }
109 
110     static void free(long memoryAddress) {
111         Holder.free(memoryAddress);
112     }
113 
114     /**
115      * Checks that native access is enabled for this module, and that this platform has a 64-bit native linker
116      * that finds malloc and free. This links no downcall, which is left to {@link Holder}.
117      */
118     private static final class Symbols {
119         static final MemorySegment MALLOC;
120         static final MemorySegment FREE;
121         static final Throwable UNAVAILABILITY_CAUSE;
122 
123         static {
124             MemorySegment malloc = null;
125             MemorySegment free = null;
126             Throwable error = null;
127             try {
128                 // First, we need to check if we have access to "restricted" methods through the Java Module system.
129                 // Class.getModule() is not part of the Java 8 API we compile against, so we look it up.
130                 MethodHandle getModule = MethodHandles.lookup().findVirtual(
131                         Class.class, "getModule", methodType(Module.class));
132                 Module module = (Module) getModule.invokeExact(CleanerJava24Linker.class);
133                 if (!module.isNativeAccessEnabled()) {
134                     throw new UnsupportedOperationException(
135                             "Native access (restricted methods) is not enabled for the io.netty.common module.");
136                 }
137 
138                 // Second, we need to check the size of a pointer address. For simplicity, we'd like to assume the size
139                 // of an address is the same as a Java long. So effectively, we're only enabled on 64-bit platforms.
140                 if (ValueLayout.ADDRESS.byteSize() != Long.BYTES) {
141                     throw new UnsupportedOperationException(
142                             "Linking to malloc and free is only supported on 64-bit platforms.");
143                 }
144 
145                 // Finally, we check that this platform has a native linker, and that it finds malloc and free.
146                 SymbolLookup symbols = Linker.nativeLinker().defaultLookup();
147                 malloc = symbols.findOrThrow("malloc");
148                 free = symbols.findOrThrow("free");
149             } catch (Throwable throwable) {
150                 malloc = null;
151                 free = null;
152                 error = throwable;
153             }
154             MALLOC = malloc;
155             FREE = free;
156             UNAVAILABILITY_CAUSE = error;
157         }
158     }
159 
160     /**
161      * Links malloc and free on first use rather than when {@link PlatformDependent} is initialized,
162      * because creating the downcall handles is a startup cost for applications that may never allocate
163      * a direct buffer.
164      */
165     private static final class Holder {
166         private static final long RTLD_DEFAULT_UNSUPPORTED = Long.MIN_VALUE;
167         private static final MethodHandle INVOKE_MALLOC;
168         private static final MethodHandle INVOKE_FREE;
169 
170         static {
171             Linker linker = Linker.nativeLinker();
172             MemorySegment malloc = Symbols.MALLOC;
173             MemorySegment free = Symbols.FREE;
174             // The default lookup only searches libc, so prefer what dlsym(RTLD_DEFAULT) finds: it honours an
175             // allocator interposed with LD_PRELOAD, like the PLT of libjvm does for Unsafe.allocateMemory.
176             long rtldDefault = rtldDefault();
177             if (rtldDefault != RTLD_DEFAULT_UNSUPPORTED) {
178                 try {
179                     MethodHandle dlsym = linker.downcallHandle(linker.defaultLookup().findOrThrow("dlsym"),
180                         FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
181                     try (Arena arena = Arena.ofConfined()) {
182                         long mallocAddr = (long) dlsym.invokeExact(rtldDefault, arena.allocateFrom("malloc"));
183                         long freeAddr = (long) dlsym.invokeExact(rtldDefault, arena.allocateFrom("free"));
184                         if (mallocAddr != 0 && freeAddr != 0) {
185                             malloc = MemorySegment.ofAddress(mallocAddr);
186                             free = MemorySegment.ofAddress(freeAddr);
187                         }
188                     }
189                 } catch (Throwable throwable) {
190                     logger.debug("dlsym(RTLD_DEFAULT) did not resolve malloc/free, using default lookup", throwable);
191                 }
192             }
193             INVOKE_MALLOC = linker.downcallHandle(malloc,
194                 FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG));
195             INVOKE_FREE = linker.downcallHandle(free,
196                 FunctionDescriptor.ofVoid(ValueLayout.JAVA_LONG));
197         }
198 
199         /**
200          * The value of the {@code RTLD_DEFAULT} pseudo-handle for {@code dlsym(3)} on this platform, or
201          * {@link #RTLD_DEFAULT_UNSUPPORTED} if we do not know it. The value is not standardised: glibc and musl use
202          * {@code (void*) 0}, while macOS and the BSDs use {@code (void*) -2}. Windows has no {@code dlsym}.
203          */
204         private static long rtldDefault() {
205             String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
206             if (os.contains("linux")) {
207                 return 0L;
208             }
209             if (os.contains("mac") || os.contains("darwin") || os.contains("bsd")) {
210                 return -2L;
211             }
212             return RTLD_DEFAULT_UNSUPPORTED;
213         }
214 
215         static long malloc(long size) {
216             try {
217                 return (long) INVOKE_MALLOC.invokeExact(size);
218             } catch (Throwable e) {
219                 throw new Error(e); // Should not happen.
220             }
221         }
222 
223         static void free(long memoryAddress) {
224             try {
225                 INVOKE_FREE.invokeExact(memoryAddress);
226             } catch (Throwable e) {
227                 throw new Error(e); // Should not happen.
228             }
229         }
230     }
231 
232     private static final class CleanableDirectBufferImpl implements CleanableDirectBuffer {
233         private final ByteBuffer buffer;
234         private final long memoryAddress;
235 
236         CleanableDirectBufferImpl(ByteBuffer buffer, long memoryAddress) {
237             this.buffer = buffer;
238             this.memoryAddress = memoryAddress;
239         }
240 
241         // Creates the ByteBuffer close to the caller: C2 only scalar-replaces it when the whole (deep)
242         // DirectByteBuffer construction fits within MaxInlineLevel of the caller.
243         static CleanableDirectBuffer allocate(int capacity) {
244             PlatformDependent.incrementMemoryCounter(capacity);
245             long addr;
246             try {
247                 addr = malloc(capacity);
248             } catch (Throwable e) {
249                 PlatformDependent.decrementMemoryCounter(capacity);
250                 throw e;
251             }
252             try {
253                 return new CleanableDirectBufferImpl(
254                         MemorySegment.ofAddress(addr).reinterpret(capacity).asByteBuffer(), addr);
255             } catch (Throwable throwable) {
256                 PlatformDependent.decrementMemoryCounter(capacity);
257                 Error error = new Error(throwable);
258                 try {
259                     free(addr);
260                 } catch (Throwable e) {
261                     error.addSuppressed(e);
262                 }
263                 throw error;
264             }
265         }
266 
267         @Override
268         public ByteBuffer buffer() {
269             return buffer;
270         }
271 
272         @Override
273         public void clean() {
274             int capacity = buffer.capacity();
275             free(memoryAddress);
276             PlatformDependent.decrementMemoryCounter(capacity);
277         }
278 
279         @Override
280         public boolean hasMemoryAddress() {
281             return true;
282         }
283 
284         @Override
285         public long memoryAddress() {
286             return memoryAddress;
287         }
288     }
289 }