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  * @run testng TestMismatch
  27  */
  28 
  29 import java.lang.invoke.VarHandle;
  30 import java.util.ArrayList;
  31 import java.util.List;
  32 import java.util.concurrent.atomic.AtomicReference;
  33 import java.util.function.IntFunction;
  34 import jdk.incubator.foreign.MemoryAddress;
  35 import jdk.incubator.foreign.MemoryLayouts;
  36 import jdk.incubator.foreign.MemorySegment;
  37 import org.testng.annotations.DataProvider;
  38 import org.testng.annotations.Test;
  39 import static java.lang.System.out;
  40 import static jdk.incubator.foreign.MemorySegment.READ;
  41 import static org.testng.Assert.assertEquals;
  42 import static org.testng.Assert.assertThrows;
  43 
  44 public class TestMismatch {
  45 
  46     final static VarHandle BYTE_HANDLE = MemoryLayouts.JAVA_BYTE.varHandle(byte.class);
  47 
  48     // stores a increasing sequence of values into the memory of the given segment
  49     static MemorySegment initializeSegment(MemorySegment segment) {
  50         MemoryAddress addr = segment.baseAddress();
  51         for (int i = 0 ; i < segment.byteSize() ; i++) {
  52             BYTE_HANDLE.set(addr.addOffset(i), (byte)i);
  53         }
  54         return segment;
  55     }
  56 
  57     @Test(dataProvider = "slices")
  58     public void testSameValues(MemorySegment ss1, MemorySegment ss2) {
  59         out.format("testSameValues s1:%s, s2:%s\n", ss1, ss2);
  60         MemorySegment s1 = initializeSegment(ss1);
  61         MemorySegment s2 = initializeSegment(ss2);
  62 
  63         if (s1.byteSize() == s2.byteSize()) {
  64             assertEquals(s1.mismatch(s2), -1);  // identical
  65             assertEquals(s2.mismatch(s1), -1);
  66         } else if (s1.byteSize() > s2.byteSize()) {
  67             assertEquals(s1.mismatch(s2), s2.byteSize());  // proper prefix
  68             assertEquals(s2.mismatch(s1), s2.byteSize());
  69         } else {
  70             assert s1.byteSize() < s2.byteSize();
  71             assertEquals(s1.mismatch(s2), s1.byteSize());  // proper prefix
  72             assertEquals(s2.mismatch(s1), s1.byteSize());
  73         }
  74     }
  75 
  76     @Test(dataProvider = "slices")
  77     public void testDifferentValues(MemorySegment s1, MemorySegment s2) {
  78         out.format("testDifferentValues s1:%s, s2:%s\n", s1, s2);
  79         s1 = initializeSegment(s1);
  80         s2 = initializeSegment(s2);
  81 
  82         for (long i = s2.byteSize() -1 ; i >= 0; i--) {
  83             long expectedMismatchOffset = i;
  84             BYTE_HANDLE.set(s2.baseAddress().addOffset(i), (byte) 0xFF);
  85 
  86             if (s1.byteSize() == s2.byteSize()) {
  87                 assertEquals(s1.mismatch(s2), expectedMismatchOffset);
  88                 assertEquals(s2.mismatch(s1), expectedMismatchOffset);
  89             } else if (s1.byteSize() > s2.byteSize()) {
  90                 assertEquals(s1.mismatch(s2), expectedMismatchOffset);
  91                 assertEquals(s2.mismatch(s1), expectedMismatchOffset);
  92             } else {
  93                 assert s1.byteSize() < s2.byteSize();
  94                 var off = Math.min(s1.byteSize(), expectedMismatchOffset);
  95                 assertEquals(s1.mismatch(s2), off);  // proper prefix
  96                 assertEquals(s2.mismatch(s1), off);
  97             }
  98         }
  99     }
 100 
 101     @Test
 102     public void testEmpty() {
 103         var s1 = MemorySegment.ofArray(new byte[0]);
 104         assertEquals(s1.mismatch(s1), -1);
 105         try (var nativeSegment = MemorySegment.allocateNative(4)) {
 106             var s2 = nativeSegment.asSlice(0, 0);
 107             assertEquals(s1.mismatch(s2), -1);
 108             assertEquals(s2.mismatch(s1), -1);
 109         }
 110     }
 111 
 112     @Test
 113     public void testLarge() {
 114         try (var s1 = MemorySegment.allocateNative((long)Integer.MAX_VALUE + 10L);
 115              var s2 = MemorySegment.allocateNative((long)Integer.MAX_VALUE + 10L)) {
 116             assertEquals(s1.mismatch(s1), -1);
 117             assertEquals(s1.mismatch(s2), -1);
 118             assertEquals(s2.mismatch(s1), -1);
 119 
 120             testLargeAcrossMaxBoundary(s1, s2);
 121 
 122             testLargeMismatchAcrossMaxBoundary(s1, s2);
 123         }
 124     }
 125 
 126     private void testLargeAcrossMaxBoundary(MemorySegment s1, MemorySegment s2) {
 127         for (long i = s2.byteSize() -1 ; i >= Integer.MAX_VALUE - 10L; i--) {
 128             var s3 = s1.asSlice(0, i);
 129             var s4 = s2.asSlice(0, i);
 130             assertEquals(s3.mismatch(s3), -1);
 131             assertEquals(s3.mismatch(s4), -1);
 132             assertEquals(s4.mismatch(s3), -1);
 133         }
 134     }
 135 
 136     private void testLargeMismatchAcrossMaxBoundary(MemorySegment s1, MemorySegment s2) {
 137         for (long i = s2.byteSize() -1 ; i >= Integer.MAX_VALUE - 10L; i--) {
 138             BYTE_HANDLE.set(s2.baseAddress().addOffset(i), (byte) 0xFF);
 139             long expectedMismatchOffset = i;
 140             assertEquals(s1.mismatch(s2), expectedMismatchOffset);
 141             assertEquals(s2.mismatch(s1), expectedMismatchOffset);
 142         }
 143     }
 144 
 145     static final Class<IllegalStateException> ISE = IllegalStateException.class;
 146     static final Class<UnsupportedOperationException> UOE = UnsupportedOperationException.class;
 147 
 148     @Test
 149     public void testClosed() {
 150         var s1 = MemorySegment.ofArray(new byte[4]);
 151         var s2 = MemorySegment.ofArray(new byte[4]);
 152         s1.close();
 153         assertThrows(ISE, () -> s1.mismatch(s1));
 154         assertThrows(ISE, () -> s1.mismatch(s2));
 155         assertThrows(ISE, () -> s2.mismatch(s1));
 156     }
 157 
 158     @Test
 159     public void testInsufficientAccessModes() {
 160         var s1 = MemorySegment.ofArray(new byte[4]);
 161         var s2 = MemorySegment.ofArray(new byte[4]);
 162         var s1WithoutRead = s1.withAccessModes(s1.accessModes() & ~READ);
 163         var s2WithoutRead = s2.withAccessModes(s2.accessModes() & ~READ);
 164 
 165         assertThrows(UOE, () -> s1.mismatch(s2WithoutRead));
 166         assertThrows(UOE, () -> s1WithoutRead.mismatch(s2));
 167         assertThrows(UOE, () -> s1WithoutRead.mismatch(s2WithoutRead));
 168     }
 169 
 170     @Test(expectedExceptions = NullPointerException.class)
 171     public void testNull() {
 172         var segment = MemorySegment.ofArray(new byte[4]);
 173         segment.mismatch(null);
 174     }
 175 
 176     @Test
 177     public void testThreadAccess() throws Exception {
 178         var segment = MemorySegment.ofArray(new byte[4]);
 179         {
 180             AtomicReference<RuntimeException> exception = new AtomicReference<>();
 181             Runnable action = () -> {
 182                 try {
 183                     MemorySegment.ofArray(new byte[4]).mismatch(segment);
 184                 } catch (RuntimeException e) {
 185                     exception.set(e);
 186                 }
 187             };
 188             Thread thread = new Thread(action);
 189             thread.start();
 190             thread.join();
 191 
 192             RuntimeException e = exception.get();
 193             if (!(e instanceof IllegalStateException)) {
 194                 throw e;
 195             }
 196         }
 197         {
 198             AtomicReference<RuntimeException> exception = new AtomicReference<>();
 199             Runnable action = () -> {
 200                 try {
 201                     segment.mismatch(MemorySegment.ofArray(new byte[4]));
 202                 } catch (RuntimeException e) {
 203                     exception.set(e);
 204                 }
 205             };
 206             Thread thread = new Thread(action);
 207             thread.start();
 208             thread.join();
 209 
 210             RuntimeException e = exception.get();
 211             if (!(e instanceof IllegalStateException)) {
 212                 throw e;
 213             }
 214         }
 215     }
 216 
 217     enum SegmentKind {
 218         NATIVE(MemorySegment::allocateNative),
 219         ARRAY(i -> MemorySegment.ofArray(new byte[i]));
 220 
 221         final IntFunction<MemorySegment> segmentFactory;
 222 
 223         SegmentKind(IntFunction<MemorySegment> segmentFactory) {
 224             this.segmentFactory = segmentFactory;
 225         }
 226 
 227         MemorySegment makeSegment(int elems) {
 228             return segmentFactory.apply(elems);
 229         }
 230     }
 231 
 232     @DataProvider(name = "slices")
 233     static Object[][] slices() {
 234         int[] sizes = { 16, 8, 1 };
 235         List<MemorySegment> aSlices = new ArrayList<>();
 236         List<MemorySegment> bSlices = new ArrayList<>();
 237         for (List<MemorySegment> slices : List.of(aSlices, bSlices)) {
 238             for (SegmentKind kind : SegmentKind.values()) {
 239                 MemorySegment segment = kind.makeSegment(16);
 240                 //compute all slices
 241                 for (int size : sizes) {
 242                     for (int index = 0 ; index < 16 ; index += size) {
 243                         MemorySegment slice = segment.asSlice(index, size);
 244                         slices.add(slice);
 245                     }
 246                 }
 247             }
 248         }
 249         assert aSlices.size() == bSlices.size();
 250         Object[][] sliceArray = new Object[aSlices.size() * bSlices.size()][];
 251         for (int i = 0 ; i < aSlices.size() ; i++) {
 252             for (int j = 0 ; j < bSlices.size() ; j++) {
 253                 sliceArray[i * aSlices.size() + j] = new Object[] { aSlices.get(i), bSlices.get(j) };
 254             }
 255         }
 256         return sliceArray;
 257     }
 258 }