Skip to content

MessageBuffer.putByteBuffer corrupts copies from sliced or read-only heap buffers #1036

Open

Description

@PHJ2000

MessageBuffer.putByteBuffer copies incorrect bytes or writes to the wrong positions for sliced and read-only sources in the default Unsafe-backed implementation.

Three valid-input cases:

  1. Sliced heap source: wrap [9, 1, 2, 3], set its position to 1, and pass source.slice() with length 3. The destination receives [9, 1, 2] instead of [1, 2, 3], because the source array offset is omitted.
  2. Read-only heap source into a sliced heap destination: the fallback writes at index in the backing array, ignoring the destination slice's array offset. Bytes before the destination slice can be overwritten.
  3. Read-only heap source into a direct destination: every loop iteration writes at address + index, so only the last source byte survives at that position.

A minimal example for the first case:

ByteBuffer source = ByteBuffer.wrap(new byte[] {9, 1, 2, 3});
source.position(1);
MessageBuffer destination = MessageBuffer.allocate(3);
destination.putByteBuffer(0, source.slice(), 3);
System.out.println(Arrays.toString(destination.toByteArray()));
// Expected: [1, 2, 3]
// Actual:   [9, 1, 2]

Reproduced on current main with OpenJDK 21 on Linux x86_64. A regression matrix covering heap/direct storage, read-only sources, source/destination slices, and zero/partial lengths fails in 10 of 64 cases before the fix. It also checks source position, limit and mark, and destination bytes outside the copied range.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions