mjanicek / rembulan

Rembulan, an implementation of Lua 5.3 for the Java Virtual Machine
Apache License 2.0
163 stars 28 forks source link

There is a potential runtime exception #27

Open Liloveyang opened 4 years ago

Liloveyang commented 4 years ago

Hello developer, first of all, thank you for opening your code. We developed a tool to scan whether there is runtime exception in the source code of the project. Then we scanned your code and found a method that may need to add try catch module! It is the putto method of rembulan-runtime \src\main\java\net\sandius\rembulan\stringbytestring.java.

Error reason: there is not enough space for ByteBuffer to store byte array parsed by string. Here is my test code,Thank you for your reply.

import sun.nio.cs.UTF_32;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Objects;

public class StringByteString {
    private final String string;
    private final Charset charset;

    private int byteHashCode;
    private int byteLength;

    StringByteString(String s, Charset charset) {
        this.string = Objects.requireNonNull(s);
        this.charset = Objects.requireNonNull(charset);
        if (!charset.canEncode()) {
            throw new IllegalArgumentException("Charset cannot encode: " + charset.name());
        }
        this.byteHashCode = 0;
        this.byteLength = string.isEmpty() ? 0 : -1;
    }

    private byte[] toBytes() {
        // TODO: cache the result
        return string.getBytes(charset);
    }

    public byte[] getBytes() {
        byte[] bytes = toBytes();

        // must make a defensive copy
        return Arrays.copyOf(bytes, bytes.length);
    }

    public void putTo(ByteBuffer buffer) {
        // ByteBuffer cannot be directly extended: it's safe to use a possibly cached array
        buffer.put(toBytes());
    }

    public static void main(String[] args) {
        StringByteString stringByteString = new StringByteString("I am Test",new UTF_32());
        ByteBuffer byteBuffer = ByteBuffer.allocate(2);
        stringByteString.putTo(byteBuffer);
    }
}