1 /*
  2  *  Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
  3  *  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  *  This code is free software; you can redistribute it and/or modify it
  6  *  under the terms of the GNU General Public License version 2 only, as
  7  *  published by the Free Software Foundation.
  8  *
  9  *  This code is distributed in the hope that it will be useful, but WITHOUT
 10  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  *  version 2 for more details (a copy is included in the LICENSE file that
 13  *  accompanied this code).
 14  *
 15  *  You should have received a copy of the GNU General Public License version
 16  *  2 along with this work; if not, write to the Free Software Foundation,
 17  *  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  *  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  *  or visit www.oracle.com if you need additional information or have any
 21  *  questions.
 22  */
 23 
 24 /*
 25  * @test
 26  * @requires ((os.arch == "amd64" | os.arch == "x86_64") & sun.arch.data.model == "64") | os.arch == "aarch64"
 27  * @run testng/othervm --enable-native-access=ALL-UNNAMED TestScopedOperations
 28  */
 29 
 30 import jdk.incubator.foreign.MemoryAddress;
 31 import jdk.incubator.foreign.MemoryLayout;
 32 import jdk.incubator.foreign.MemorySegment;
 33 import jdk.incubator.foreign.NativeSymbol;
 34 import jdk.incubator.foreign.ResourceScope;
 35 import jdk.incubator.foreign.SegmentAllocator;
 36 import jdk.incubator.foreign.VaList;
 37 import jdk.incubator.foreign.ValueLayout;
 38 import org.testng.annotations.DataProvider;
 39 import org.testng.annotations.Test;
 40 
 41 import java.io.File;
 42 import java.io.IOException;
 43 import java.nio.channels.FileChannel;
 44 import java.nio.file.Path;
 45 import java.util.ArrayList;
 46 import java.util.List;
 47 import java.util.concurrent.atomic.AtomicReference;
 48 import java.util.function.Consumer;
 49 import java.util.function.Function;
 50 
 51 import static jdk.incubator.foreign.ValueLayout.JAVA_BYTE;
 52 import static jdk.incubator.foreign.ValueLayout.JAVA_INT;
 53 import static jdk.incubator.foreign.ValueLayout.JAVA_LONG;
 54 import static org.testng.Assert.assertEquals;
 55 import static org.testng.Assert.assertNotNull;
 56 import static org.testng.Assert.assertTrue;
 57 import static org.testng.Assert.fail;
 58 
 59 public class TestScopedOperations {
 60 
 61     static Path tempPath;
 62 
 63     static {
 64         try {
 65             File file = File.createTempFile("scopedBuffer", "txt");
 66             file.deleteOnExit();
 67             tempPath = file.toPath();
 68         } catch (IOException ex) {
 69             throw new ExceptionInInitializerError(ex);
 70         }
 71     }
 72 
 73     @Test(dataProvider = "scopedOperations")
 74     public <Z> void testOpAfterClose(String name, ScopedOperation<Z> scopedOperation) {
 75         ResourceScope scope = ResourceScope.newConfinedScope();
 76         Z obj = scopedOperation.apply(scope);
 77         scope.close();
 78         try {
 79             scopedOperation.accept(obj);
 80             fail();
 81         } catch (IllegalStateException ex) {
 82             assertTrue(ex.getMessage().contains("closed"));
 83         }
 84     }
 85 
 86     @Test(dataProvider = "scopedOperations")
 87     public <Z> void testOpOutsideConfinement(String name, ScopedOperation<Z> scopedOperation) {
 88         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
 89             Z obj = scopedOperation.apply(scope);
 90             AtomicReference<Throwable> failed = new AtomicReference<>();
 91             Thread t = new Thread(() -> {
 92                 try {
 93                     scopedOperation.accept(obj);
 94                 } catch (Throwable ex) {
 95                     failed.set(ex);
 96                 }
 97             });
 98             t.start();
 99             t.join();
100             assertNotNull(failed.get());
101             assertEquals(failed.get().getClass(), IllegalStateException.class);
102             assertTrue(failed.get().getMessage().contains("outside"));
103         } catch (InterruptedException ex) {
104             throw new AssertionError(ex);
105         }
106     }
107 
108     static List<ScopedOperation> scopedOperations = new ArrayList<>();
109 
110     static {
111         // scope operations
112         ScopedOperation.ofScope(scope -> scope.addCloseAction(() -> {
113         }), "ResourceScope::addOnClose");
114         ScopedOperation.ofScope(scope -> {
115             ResourceScope scope2 = ResourceScope.newConfinedScope();
116             scope2.keepAlive(scope);
117             scope2.close();
118         }, "ResourceScope::keepAlive");
119         ScopedOperation.ofScope(scope -> MemorySegment.allocateNative(100, scope), "MemorySegment::allocateNative");
120         ScopedOperation.ofScope(scope -> {
121             try {
122                 MemorySegment.mapFile(tempPath, 0, 10, FileChannel.MapMode.READ_WRITE, scope);
123             } catch (IOException ex) {
124                 fail();
125             }
126         }, "MemorySegment::mapFromFile");
127         ScopedOperation.ofScope(scope -> VaList.make(b -> b.addVarg(JAVA_INT, 42), scope), "VaList::make");
128         ScopedOperation.ofScope(scope -> VaList.ofAddress(MemoryAddress.ofLong(42), scope), "VaList::make");
129         ScopedOperation.ofScope(SegmentAllocator::newNativeArena, "SegmentAllocator::arenaAllocator");
130         // segment operations
131         ScopedOperation.ofSegment(s -> s.toArray(JAVA_BYTE), "MemorySegment::toArray(BYTE)");
132         ScopedOperation.ofSegment(MemorySegment::address, "MemorySegment::address");
133         ScopedOperation.ofSegment(s -> s.copyFrom(s), "MemorySegment::copyFrom");
134         ScopedOperation.ofSegment(s -> s.mismatch(s), "MemorySegment::mismatch");
135         ScopedOperation.ofSegment(s -> s.fill((byte) 0), "MemorySegment::fill");
136         // valist operations
137         ScopedOperation.ofVaList(VaList::address, "VaList::address");
138         ScopedOperation.ofVaList(VaList::copy, "VaList::copy");
139         ScopedOperation.ofVaList(list -> list.nextVarg(ValueLayout.ADDRESS), "VaList::nextVarg/address");
140         ScopedOperation.ofVaList(list -> list.nextVarg(ValueLayout.JAVA_INT), "VaList::nextVarg/int");
141         ScopedOperation.ofVaList(list -> list.nextVarg(ValueLayout.JAVA_LONG), "VaList::nextVarg/long");
142         ScopedOperation.ofVaList(list -> list.nextVarg(ValueLayout.JAVA_DOUBLE), "VaList::nextVarg/double");
143         ScopedOperation.ofVaList(VaList::skip, "VaList::skip");
144         ScopedOperation.ofVaList(list -> list.nextVarg(MemoryLayout.structLayout(ValueLayout.JAVA_INT),
145                 SegmentAllocator.prefixAllocator(MemorySegment.ofArray(new byte[4]))), "VaList::nextVargs/segment");
146         // allocator operations
147         ScopedOperation.ofAllocator(a -> a.allocate(1), "NativeAllocator::allocate/size");
148         ScopedOperation.ofAllocator(a -> a.allocate(1, 1), "NativeAllocator::allocate/size/align");
149         ScopedOperation.ofAllocator(a -> a.allocate(JAVA_BYTE), "NativeAllocator::allocate/layout");
150         ScopedOperation.ofAllocator(a -> a.allocate(JAVA_BYTE, (byte) 0), "NativeAllocator::allocate/byte");
151         ScopedOperation.ofAllocator(a -> a.allocate(ValueLayout.JAVA_CHAR, (char) 0), "NativeAllocator::allocate/char");
152         ScopedOperation.ofAllocator(a -> a.allocate(ValueLayout.JAVA_SHORT, (short) 0), "NativeAllocator::allocate/short");
153         ScopedOperation.ofAllocator(a -> a.allocate(ValueLayout.JAVA_INT, 0), "NativeAllocator::allocate/int");
154         ScopedOperation.ofAllocator(a -> a.allocate(ValueLayout.JAVA_FLOAT, 0f), "NativeAllocator::allocate/float");
155         ScopedOperation.ofAllocator(a -> a.allocate(ValueLayout.JAVA_LONG, 0L), "NativeAllocator::allocate/long");
156         ScopedOperation.ofAllocator(a -> a.allocate(ValueLayout.JAVA_DOUBLE, 0d), "NativeAllocator::allocate/double");
157         ScopedOperation.ofAllocator(a -> a.allocateArray(JAVA_BYTE, 1L), "NativeAllocator::allocateArray/size");
158         ScopedOperation.ofAllocator(a -> a.allocateArray(JAVA_BYTE, new byte[]{0}), "NativeAllocator::allocateArray/byte");
159         ScopedOperation.ofAllocator(a -> a.allocateArray(ValueLayout.JAVA_CHAR, new char[]{0}), "NativeAllocator::allocateArray/char");
160         ScopedOperation.ofAllocator(a -> a.allocateArray(ValueLayout.JAVA_SHORT, new short[]{0}), "NativeAllocator::allocateArray/short");
161         ScopedOperation.ofAllocator(a -> a.allocateArray(ValueLayout.JAVA_INT, new int[]{0}), "NativeAllocator::allocateArray/int");
162         ScopedOperation.ofAllocator(a -> a.allocateArray(ValueLayout.JAVA_FLOAT, new float[]{0}), "NativeAllocator::allocateArray/float");
163         ScopedOperation.ofAllocator(a -> a.allocateArray(ValueLayout.JAVA_LONG, new long[]{0}), "NativeAllocator::allocateArray/long");
164         ScopedOperation.ofAllocator(a -> a.allocateArray(ValueLayout.JAVA_DOUBLE, new double[]{0}), "NativeAllocator::allocateArray/double");
165         // native symbol
166         ScopedOperation.of(scope -> NativeSymbol.ofAddress("", MemoryAddress.NULL, scope), NativeSymbol::address, "NativeSymbol::address");
167     };
168 
169     @DataProvider(name = "scopedOperations")
170     static Object[][] scopedOperations() {
171         return scopedOperations.stream().map(op -> new Object[] { op.name, op }).toArray(Object[][]::new);
172     }
173 
174     static class ScopedOperation<X> implements Consumer<X>, Function<ResourceScope, X> {
175 
176         final Function<ResourceScope, X> factory;
177         final Consumer<X> operation;
178         final String name;
179 
180         private ScopedOperation(Function<ResourceScope, X> factory, Consumer<X> operation, String name) {
181             this.factory = factory;
182             this.operation = operation;
183             this.name = name;
184         }
185 
186         @Override
187         public void accept(X obj) {
188             operation.accept(obj);
189         }
190 
191         @Override
192         public X apply(ResourceScope scope) {
193             return factory.apply(scope);
194         }
195 
196         static <Z> void of(Function<ResourceScope, Z> factory, Consumer<Z> consumer, String name) {
197             scopedOperations.add(new ScopedOperation<>(factory, consumer, name));
198         }
199 
200         static void ofScope(Consumer<ResourceScope> scopeConsumer, String name) {
201             scopedOperations.add(new ScopedOperation<>(Function.identity(), scopeConsumer, name));
202         }
203 
204         static void ofVaList(Consumer<VaList> vaListConsumer, String name) {
205             scopedOperations.add(new ScopedOperation<>(scope -> VaList.make(builder -> builder.addVarg(JAVA_LONG, 42), scope),
206                     vaListConsumer, name));
207         }
208 
209         static void ofSegment(Consumer<MemorySegment> segmentConsumer, String name) {
210             for (SegmentFactory segmentFactory : SegmentFactory.values()) {
211                 scopedOperations.add(new ScopedOperation<>(
212                         segmentFactory.segmentFactory,
213                         segmentConsumer,
214                         segmentFactory.name() + "/" + name));
215             }
216         }
217 
218         static void ofAllocator(Consumer<SegmentAllocator> allocatorConsumer, String name) {
219             for (AllocatorFactory allocatorFactory : AllocatorFactory.values()) {
220                 scopedOperations.add(new ScopedOperation<>(
221                         allocatorFactory.allocatorFactory,
222                         allocatorConsumer,
223                         allocatorFactory.name() + "/" + name));
224             }
225         }
226 
227         enum SegmentFactory {
228 
229             NATIVE(scope -> MemorySegment.allocateNative(10, scope)),
230             MAPPED(scope -> {
231                 try {
232                     return MemorySegment.mapFile(Path.of("foo.txt"), 0, 10, FileChannel.MapMode.READ_WRITE, scope);
233                 } catch (IOException ex) {
234                     throw new AssertionError(ex);
235                 }
236             }),
237             UNSAFE(scope -> MemorySegment.ofAddressNative(MemoryAddress.NULL, 10, scope));
238 
239             static {
240                 try {
241                     File f = new File("foo.txt");
242                     f.createNewFile();
243                     f.deleteOnExit();
244                 } catch (IOException ex) {
245                     throw new ExceptionInInitializerError(ex);
246                 }
247             }
248 
249             final Function<ResourceScope, MemorySegment> segmentFactory;
250 
251             SegmentFactory(Function<ResourceScope, MemorySegment> segmentFactory) {
252                 this.segmentFactory = segmentFactory;
253             }
254         }
255 
256         enum AllocatorFactory {
257             ARENA_BOUNDED(scope -> SegmentAllocator.newNativeArena(1000, scope)),
258             ARENA_UNBOUNDED(SegmentAllocator::newNativeArena);
259 
260             final Function<ResourceScope, SegmentAllocator> allocatorFactory;
261 
262             AllocatorFactory(Function<ResourceScope, SegmentAllocator> allocatorFactory) {
263                 this.allocatorFactory = allocatorFactory;
264             }
265         }
266     }
267 }