1 /*
  2  *  Copyright (c) 2020, 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  * @modules java.base/jdk.internal.ref
 28  *          jdk.incubator.foreign
 29  * @run testng/othervm
 30  *     --enable-native-access=ALL-UNNAMED
 31  *     TestNulls
 32  */
 33 
 34 import jdk.incubator.foreign.*;
 35 import jdk.internal.ref.CleanerFactory;
 36 import org.testng.annotations.DataProvider;
 37 import org.testng.annotations.NoInjection;
 38 import org.testng.annotations.Test;
 39 
 40 import java.lang.constant.Constable;
 41 import java.lang.invoke.MethodHandle;
 42 import java.lang.invoke.MethodHandles;
 43 import java.lang.invoke.MethodType;
 44 import java.lang.invoke.VarHandle;
 45 import java.lang.ref.Cleaner;
 46 import java.lang.reflect.Array;
 47 import java.lang.reflect.InvocationTargetException;
 48 import java.lang.reflect.Method;
 49 import java.lang.reflect.Modifier;
 50 import java.nio.ByteBuffer;
 51 import java.nio.ByteOrder;
 52 import java.nio.channels.FileChannel;
 53 import java.nio.charset.Charset;
 54 import java.nio.file.Path;
 55 import java.util.*;
 56 import java.util.concurrent.atomic.AtomicReference;
 57 import java.util.function.Consumer;
 58 import java.util.function.Supplier;
 59 import java.util.function.UnaryOperator;
 60 import java.util.stream.Collectors;
 61 import java.util.stream.Stream;
 62 
 63 import static jdk.incubator.foreign.ValueLayout.JAVA_INT;
 64 import static jdk.incubator.foreign.ValueLayout.JAVA_LONG;
 65 import static org.testng.Assert.*;
 66 import static org.testng.Assert.fail;
 67 
 68 /**
 69  * This test makes sure that public API classes (listed in {@link TestNulls#CLASSES}) throws NPEs whenever
 70  * nulls are provided. The test looks at all the public methods in all the listed classes, and injects
 71  * values automatically. If an API takes a reference, the test will try to inject nulls. For APIs taking
 72  * either reference arrays, or collections, the framework will also generate additional <em>replacements</em>
 73  * (e.g. other than just replacing the array, or collection with null), such as an array or collection
 74  * with null elements. The test can be customized by adding/removing classes to the {@link #CLASSES} array,
 75  * by adding/removing default mappings for standard carrier types (see {@link #DEFAULT_VALUES} or by
 76  * adding/removing custom replacements (see {@link #REPLACEMENT_VALUES}).
 77  */
 78 public class TestNulls {
 79 
 80     static final Class<?>[] CLASSES = new Class<?>[] {
 81             MemorySegment.class,
 82             MemoryAddress.class,
 83             MemoryLayout.class,
 84             MemoryLayout.PathElement.class,
 85             SequenceLayout.class,
 86             ValueLayout.class,
 87             ValueLayout.OfBoolean.class,
 88             ValueLayout.OfByte.class,
 89             ValueLayout.OfChar.class,
 90             ValueLayout.OfShort.class,
 91             ValueLayout.OfInt.class,
 92             ValueLayout.OfFloat.class,
 93             ValueLayout.OfLong.class,
 94             ValueLayout.OfDouble.class,
 95             ValueLayout.OfAddress.class,
 96             GroupLayout.class,
 97             Addressable.class,
 98             SymbolLookup.class,
 99             MemoryHandles.class,
100             CLinker.class,
101             VaList.class,
102             VaList.Builder.class,
103             FunctionDescriptor.class,
104             SegmentAllocator.class,
105             ResourceScope.class,
106             NativeSymbol.class
107     };
108 
109     static final Set<String> EXCLUDE_LIST = Set.of(
110             "jdk.incubator.foreign.ResourceScope/newConfinedScope(java.lang.ref.Cleaner)/0/0",
111             "jdk.incubator.foreign.ResourceScope/newSharedScope(java.lang.ref.Cleaner)/0/0",
112             "jdk.incubator.foreign.MemoryLayout/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
113             "jdk.incubator.foreign.SequenceLayout/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
114             "jdk.incubator.foreign.ValueLayout/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
115             "jdk.incubator.foreign.ValueLayout$OfAddress/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
116             "jdk.incubator.foreign.ValueLayout$OfBoolean/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
117             "jdk.incubator.foreign.ValueLayout$OfByte/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
118             "jdk.incubator.foreign.ValueLayout$OfChar/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
119             "jdk.incubator.foreign.ValueLayout$OfShort/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
120             "jdk.incubator.foreign.ValueLayout$OfInt/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
121             "jdk.incubator.foreign.ValueLayout$OfFloat/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
122             "jdk.incubator.foreign.ValueLayout$OfLong/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
123             "jdk.incubator.foreign.ValueLayout$OfDouble/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
124             "jdk.incubator.foreign.GroupLayout/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0",
125             "jdk.incubator.foreign.MemoryHandles/insertCoordinates(java.lang.invoke.VarHandle,int,java.lang.Object[])/2/1",
126             "jdk.incubator.foreign.FunctionDescriptor/withAttribute(java.lang.String,java.lang.constant.Constable)/1/0"
127     );
128 
129     static final Set<String> OBJECT_METHODS = Stream.of(Object.class.getMethods())
130             .map(Method::getName)
131             .collect(Collectors.toSet());
132 
133     static final Map<Class<?>, Object> DEFAULT_VALUES = new HashMap<>();
134 
135     static <Z> void addDefaultMapping(Class<Z> carrier, Z value) {
136         DEFAULT_VALUES.put(carrier, value);
137     }
138 
139     static {
140         addDefaultMapping(char.class, (char)0);
141         addDefaultMapping(byte.class, (byte)0);
142         addDefaultMapping(short.class, (short)0);
143         addDefaultMapping(int.class, 0);
144         addDefaultMapping(float.class, 0f);
145         addDefaultMapping(long.class, 0L);
146         addDefaultMapping(double.class, 0d);
147         addDefaultMapping(boolean.class, true);
148         addDefaultMapping(ByteOrder.class, ByteOrder.nativeOrder());
149         addDefaultMapping(Thread.class, Thread.currentThread());
150         addDefaultMapping(Cleaner.class, CleanerFactory.cleaner());
151         addDefaultMapping(ByteBuffer.class, ByteBuffer.wrap(new byte[10]));
152         addDefaultMapping(Path.class, Path.of("nonExistent"));
153         addDefaultMapping(FileChannel.MapMode.class, FileChannel.MapMode.PRIVATE);
154         addDefaultMapping(UnaryOperator.class, UnaryOperator.identity());
155         addDefaultMapping(String.class, "Hello!");
156         addDefaultMapping(Constable.class, "Hello!");
157         addDefaultMapping(Class.class, String.class);
158         addDefaultMapping(Runnable.class, () -> {});
159         addDefaultMapping(Object.class, new Object());
160         addDefaultMapping(VarHandle.class, MemoryHandles.varHandle(JAVA_INT));
161         addDefaultMapping(MethodHandle.class, MethodHandles.identity(int.class));
162         addDefaultMapping(List.class, List.of());
163         addDefaultMapping(Charset.class, Charset.defaultCharset());
164         addDefaultMapping(Consumer.class, x -> {});
165         addDefaultMapping(MethodType.class, MethodType.methodType(void.class));
166         addDefaultMapping(MemoryAddress.class, MemoryAddress.ofLong(1));
167         addDefaultMapping(Addressable.class, MemoryAddress.ofLong(1));
168         addDefaultMapping(MemoryLayout.class, ValueLayout.JAVA_INT);
169         addDefaultMapping(ValueLayout.class, ValueLayout.JAVA_INT);
170         addDefaultMapping(ValueLayout.OfAddress.class, ValueLayout.ADDRESS);
171         addDefaultMapping(ValueLayout.OfByte.class, ValueLayout.JAVA_BYTE);
172         addDefaultMapping(ValueLayout.OfBoolean.class, ValueLayout.JAVA_BOOLEAN);
173         addDefaultMapping(ValueLayout.OfChar.class, ValueLayout.JAVA_CHAR);
174         addDefaultMapping(ValueLayout.OfShort.class, ValueLayout.JAVA_SHORT);
175         addDefaultMapping(ValueLayout.OfInt.class, ValueLayout.JAVA_INT);
176         addDefaultMapping(ValueLayout.OfFloat.class, ValueLayout.JAVA_FLOAT);
177         addDefaultMapping(ValueLayout.OfLong.class, JAVA_LONG);
178         addDefaultMapping(ValueLayout.OfDouble.class, ValueLayout.JAVA_DOUBLE);
179         addDefaultMapping(GroupLayout.class, MemoryLayout.structLayout(ValueLayout.JAVA_INT));
180         addDefaultMapping(SequenceLayout.class, MemoryLayout.sequenceLayout(ValueLayout.JAVA_INT));
181         addDefaultMapping(MemorySegment.class, MemorySegment.ofArray(new byte[10]));
182         addDefaultMapping(FunctionDescriptor.class, FunctionDescriptor.ofVoid());
183         addDefaultMapping(CLinker.class, CLinker.systemCLinker());
184         addDefaultMapping(VaList.class, VaListHelper.vaList);
185         addDefaultMapping(VaList.Builder.class, VaListHelper.vaListBuilder);
186         addDefaultMapping(ResourceScope.class, ResourceScope.newSharedScope());
187         addDefaultMapping(SegmentAllocator.class, SegmentAllocator.prefixAllocator(MemorySegment.ofArray(new byte[10])));
188         addDefaultMapping(Supplier.class, () -> null);
189         addDefaultMapping(ClassLoader.class, TestNulls.class.getClassLoader());
190         addDefaultMapping(SymbolLookup.class, CLinker.systemCLinker());
191         addDefaultMapping(NativeSymbol.class, NativeSymbol.ofAddress("dummy", MemoryAddress.ofLong(1), ResourceScope.globalScope()));
192     }
193 
194     static class VaListHelper {
195         static final VaList vaList;
196         static final VaList.Builder vaListBuilder;
197 
198         static {
199             AtomicReference<VaList.Builder> builderRef = new AtomicReference<>();
200             vaList = VaList.make(b -> {
201                 builderRef.set(b);
202                 b.addVarg(JAVA_LONG, 42L);
203             }, ResourceScope.newImplicitScope());
204             vaListBuilder = builderRef.get();
205         }
206     }
207 
208     static final Map<Class<?>, Object[]> REPLACEMENT_VALUES = new HashMap<>();
209 
210     @SafeVarargs
211     static <Z> void addReplacements(Class<Z> carrier, Z... value) {
212         REPLACEMENT_VALUES.put(carrier, value);
213     }
214 
215     static {
216         addReplacements(Collection.class, null, Stream.of(new Object[] { null }).collect(Collectors.toList()));
217         addReplacements(List.class, null, Stream.of(new Object[] { null }).collect(Collectors.toList()));
218         addReplacements(Set.class, null, Stream.of(new Object[] { null }).collect(Collectors.toSet()));
219     }
220 
221     @Test(dataProvider = "cases")
222     public void testNulls(String testName, @NoInjection Method meth, Object receiver, Object[] args) {
223         try {
224             meth.invoke(receiver, args);
225             fail("Method invocation completed normally");
226         } catch (InvocationTargetException ex) {
227             Class<?> cause = ex.getCause().getClass();
228             assertEquals(cause, NullPointerException.class, "got " + cause.getName() + " - expected NullPointerException");
229         } catch (Throwable ex) {
230             fail("Unexpected exception: " + ex);
231         }
232     }
233 
234     @DataProvider(name = "cases")
235     static Iterator<Object[]> cases() {
236         List<Object[]> cases = new ArrayList<>();
237         for (Class<?> clazz : CLASSES) {
238             for (Method m : clazz.getMethods()) {
239                 if (OBJECT_METHODS.contains(m.getName())) continue;
240                 boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
241                 List<Integer> refIndices = new ArrayList<>();
242                 for (int i = 0; i < m.getParameterCount(); i++) {
243                     Class<?> param = m.getParameterTypes()[i];
244                     if (!param.isPrimitive()) {
245                         refIndices.add(i);
246                     }
247                 }
248                 for (int i : refIndices) {
249                     Object[] replacements = replacements(m.getParameterTypes()[i]);
250                     for (int r = 0 ; r < replacements.length ; r++) {
251                         String testName = clazz.getName() + "/" + shortSig(m) + "/" + i + "/" + r;
252                         if (EXCLUDE_LIST.contains(testName)) continue;
253                         Object[] args = new Object[m.getParameterCount()];
254                         for (int j = 0; j < args.length; j++) {
255                             args[j] = defaultValue(m.getParameterTypes()[j]);
256                         }
257                         args[i] = replacements[r];
258                         Object receiver = isStatic ? null : defaultValue(clazz);
259                         cases.add(new Object[]{testName, m, receiver, args});
260                     }
261                 }
262             }
263         }
264         return cases.iterator();
265     };
266 
267     static String shortSig(Method m) {
268         StringJoiner sj = new StringJoiner(",", m.getName() + "(", ")");
269         for (Class<?> parameterType : m.getParameterTypes()) {
270             sj.add(parameterType.getTypeName());
271         }
272         return sj.toString();
273     }
274 
275     static Object defaultValue(Class<?> carrier) {
276         if (carrier.isArray()) {
277             return Array.newInstance(carrier.componentType(), 0);
278         }
279         Object value = DEFAULT_VALUES.get(carrier);
280         if (value == null) {
281             throw new UnsupportedOperationException(carrier.getName());
282         }
283         return value;
284     }
285 
286     static Object[] replacements(Class<?> carrier) {
287         if (carrier.isArray() && !carrier.getComponentType().isPrimitive()) {
288             Object arr = Array.newInstance(carrier.componentType(), 1);
289             Array.set(arr, 0, null);
290             return new Object[] { null, arr };
291         }
292         return REPLACEMENT_VALUES.getOrDefault(carrier, new Object[] { null });
293     }
294 }