apache/dubbo · error · IndexOutOfBoundsException

hex2bytes: length < 0, length is {}

Error message

hex2bytes: length < 0, length is {}

What it means

Thrown by Bytes.hex2bytes(String, int, int) when the length argument is negative. The conversion reads len characters and produces len/2 bytes; a negative length is rejected after the even-length and offset checks. It guards against allocating a negative-sized array or looping incorrectly.

Source

Thrown at dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java:446

    /**
     * from hex string.
     *
     * @param str hex string.
     * @param off offset.
     * @param len length.
     * @return byte array.
     */
    public static byte[] hex2bytes(final String str, final int off, int len) {
        if ((len & 1) == 1) {
            throw new IllegalArgumentException("hex2bytes: ( len & 1 ) == 1.");
        }

        if (off < 0) {
            throw new IndexOutOfBoundsException("hex2bytes: offset < 0, offset is " + off);
        }
        if (len < 0) {
            throw new IndexOutOfBoundsException("hex2bytes: length < 0, length is " + len);
        }
        if (off + len > str.length()) {
            throw new IndexOutOfBoundsException("hex2bytes: offset + length > array length.");
        }

        int num = len / 2, r = off, w = 0;
        byte[] b = new byte[num];
        for (int i = 0; i < num; i++) {
            b[w++] = (byte) (hex(str.charAt(r++)) << 4 | hex(str.charAt(r++)));
        }
        return b;
    }

    /**
     * to base64 string.
     *
     * @param b byte array.
     * @return base64 string.

View on GitHub (pinned to 3a3043227f)

Solutions

  1. Validate length >= 0 before calling hex2bytes.
  2. Use hex2bytes(String) to avoid manual length computation.
  3. Sanitize untrusted length inputs at the parse boundary.

Example fix

// before
int len = end - start; // negative if end < start
byte[] b = Bytes.hex2bytes(hex, off, len); // throws [156]

// after
int len = Math.max(0, end - start);
byte[] b = Bytes.hex2bytes(hex, off, len);
Defensive patterns

Strategy: validation

Validate before calling

if (len < 0) throw new IllegalArgumentException("negative length: " + len);
byte[] b = Bytes.hex2bytes(str, off, len);

Prevention

When it happens

Trigger: Calling Bytes.hex2bytes(str, off, len) with len < 0. Common when len is derived from (end - start) with end < start, or an uninitialized/parsed length that is negative.

Common situations: Length from a corrupt protocol field; arithmetic producing a negative difference; default sentinel -1 for 'unset' passed through unchecked.

Related errors


AI-assisted analysis of apache/dubbo@3a3043227f (2026-08-14). Data as JSON: /api/errors/6afdc0824c1ec2ab. Report an issue: GitHub.