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             for (long i = s2.byteSize() -1 ; i >= Integer.MAX_VALUE - 10L; i--) {
 121                 BYTE_HANDLE.set(s2.baseAddress().addOffset(i), (byte) 0xFF);
 122                 long expectedMismatchOffset = i;
 123                 assertEquals(s1.mismatch(s2), expectedMismatchOffset);
 124                 assertEquals(s2.mismatch(s1), expectedMismatchOffset);
 125             }
 126         }
 127     }
 128 
 129     static final Class<IllegalStateException> ISE = IllegalStateException.class;
 130     static final Class<UnsupportedOperationException> UOE = UnsupportedOperationException.class;
 131 
 132     @Test
 133     public void testClosed() {
 134         var s1 = MemorySegment.ofArray(new byte[4]);
 135         var s2 = MemorySegment.ofArray(new byte[4]);
 136         s1.close();
 137         assertThrows(ISE, () -> s1.mismatch(s1));
 138         assertThrows(ISE, () -> s1.mismatch(s2));
 139         assertThrows(ISE, () -> s2.mismatch(s1));
 140     }
 141 
 142     @Test
 143     public void testInsufficientAccessModes() {
 144         var s1 = MemorySegment.ofArray(new byte[4]);
 145         var s2 = MemorySegment.ofArray(new byte[4]);
 146         var s1WithoutRead = s1.withAccessModes(s1.accessModes() & ~READ);
 147         var s2WithoutRead = s2.withAccessModes(s2.accessModes() & ~READ);
 148 
 149         assertThrows(UOE, () -> s1.mismatch(s2WithoutRead));
 150         assertThrows(UOE, () -> s1WithoutRead.mismatch(s2));
 151         assertThrows(UOE, () -> s1WithoutRead.mismatch(s2WithoutRead));
 152     }
 153 
 154     @Test(expectedExceptions = NullPointerException.class)
 155     public void testNull() {
 156         var segment = MemorySegment.ofArray(new byte[4]);
 157         segment.mismatch(null);
 158     }
 159 
 160     @Test
 161     public void testThreadAccess() throws Exception {
 162         var segment = MemorySegment.ofArray(new byte[4]);
 163         {
 164             AtomicReference<RuntimeException> exception = new AtomicReference<>();
 165             Runnable action = () -> {
 166                 try {
 167                     MemorySegment.ofArray(new byte[4]).mismatch(segment);
 168                 } catch (RuntimeException e) {
 169                     exception.set(e);
 170                 }
 171             };
 172             Thread thread = new Thread(action);
 173             thread.start();
 174             thread.join();
 175 
 176             RuntimeException e = exception.get();
 177             if (!(e instanceof IllegalStateException)) {
 178                 throw e;
 179             }
 180         }
 181         {
 182             AtomicReference<RuntimeException> exception = new AtomicReference<>();
 183             Runnable action = () -> {
 184                 try {
 185                     segment.mismatch(MemorySegment.ofArray(new byte[4]));
 186                 } catch (RuntimeException e) {
 187                     exception.set(e);
 188                 }
 189             };
 190             Thread thread = new Thread(action);
 191             thread.start();
 192             thread.join();
 193 
 194             RuntimeException e = exception.get();
 195             if (!(e instanceof IllegalStateException)) {
 196                 throw e;
 197             }
 198         }
 199     }
 200 
 201     enum SegmentKind {
 202         NATIVE(MemorySegment::allocateNative),
 203         ARRAY(i -> MemorySegment.ofArray(new byte[i]));
 204 
 205         final IntFunction<MemorySegment> segmentFactory;
 206 
 207         SegmentKind(IntFunction<MemorySegment> segmentFactory) {
 208             this.segmentFactory = segmentFactory;
 209         }
 210 
 211         MemorySegment makeSegment(int elems) {
 212             return segmentFactory.apply(elems);
 213         }
 214     }
 215 
 216     @DataProvider(name = "slices")
 217     static Object[][] slices() {
 218         int[] sizes = { 16, 8, 1 };
 219         List<MemorySegment> aSlices = new ArrayList<>();
 220         List<MemorySegment> bSlices = new ArrayList<>();
 221         for (List<MemorySegment> slices : List.of(aSlices, bSlices)) {
 222             for (SegmentKind kind : SegmentKind.values()) {
 223                 MemorySegment segment = kind.makeSegment(16);
 224                 //compute all slices
 225                 for (int size : sizes) {
 226                     for (int index = 0 ; index < 16 ; index += size) {
 227                         MemorySegment slice = segment.asSlice(index, size);
 228                         slices.add(slice);
 229                     }
 230                 }
 231             }
 232         }
 233         assert aSlices.size() == bSlices.size();
 234         Object[][] sliceArray = new Object[aSlices.size() * bSlices.size()][];
 235         for (int i = 0 ; i < aSlices.size() ; i++) {
 236             for (int j = 0 ; j < bSlices.size() ; j++) {
 237                 sliceArray[i * aSlices.size() + j] = new Object[] { aSlices.get(i), bSlices.get(j) };
 238             }
 239         }
 240         return sliceArray;
 241     }
 242 }