1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
36
37
38
39
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
49
50
51
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
58
59
60
61
62
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
102
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
116
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
129
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
139
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
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
162
163
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
175
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
201
202
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);
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);
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
242
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 }