Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8321466

SIGSEGV when reading from a MemorySegment when address is 0

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 22
    • core-libs
    • None

      On operations like MemorySegment::get, the operation should probably fail with an `IllegalStateException` or equivalent. Otherwise this leads to segfault.


      Typically I was refactoring some code and also plying with the API, and stumble on this crash.

      Clearly my code is wrong, yet I don't thin this should crash the JVM

      ```
      package io.github.bric3.panama.b.memory;

      import java.lang.foreign.Arena;
      import java.lang.foreign.MemoryLayout;
      import java.lang.foreign.MemoryLayout.PathElement;
      import java.lang.foreign.MemorySegment;

      import static java.lang.foreign.ValueLayout.ADDRESS;
      import static java.lang.foreign.ValueLayout.JAVA_BYTE;

      public class AccessingData {
        public static void main(String[] args) {
          var basic_struct_LAYOUT = MemoryLayout.structLayout(
                  MemoryLayout.sequenceLayout(
                          64,
                          JAVA_BYTE
                  ).withName("buf"),
                  JAVA_BYTE.withName("buf_len"),
                  JAVA_BYTE.withName("flags")
          ).withName("basic_struct");

          var pathToFlags = PathElement.groupElement("flags");
          var flags = basic_struct_LAYOUT.varHandle(
                  pathToFlags
          );

          try (var arena = Arena.ofConfined()) {
            var memorySegment = arena.allocate(basic_struct_LAYOUT);
            flags.set(memorySegment, 0L, (byte) 0b0001_0001);

            // the bad code
            var retargeted = memorySegment.get(ADDRESS.withTargetLayout(basic_struct_LAYOUT), 0);
            byte flagsValue_JVMCrash = retargeted.get(JAVA_BYTE, basic_struct_LAYOUT.byteOffset(pathToFlags)); // this crashes
          }
        }
      }
      ```

      And the summary printed on stdout does not help much if you're a inexperienced with JVM crashes.

      ```
      # Problematic frame:
      # V [libjvm.dylib+0x9b69d8] Unsafe_GetByte(JNIEnv_*, _jobject*, _jobject*, long)+0x14c
      ```

      ----
      MacOS 14.1.2 (Sonoma)
      CPU: M1
      OpenJDK Runtime Environment (22.0+26) (build 22-ea+26-2112)

            Unassigned Unassigned
            bdutheil Brice Dutheil
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: