Unidata / netcdf-java

The Unidata netcdf-java library
https://docs.unidata.ucar.edu/netcdf-java/current/userguide/index.html
BSD 3-Clause "New" or "Revised" License
142 stars 69 forks source link

[VERSION]: 5.5.2 Exception thrown when accessing char data from NetcdfDatasets.openNcmlDataset #1235

Closed jmasson-l3h closed 12 months ago

jmasson-l3h commented 12 months ago

Versions impacted by the bug

v5.x

What went wrong?

When processing variable length char data , the ncml parser attempts to read outside of bounds and throws an exception.

Minimal example

public static void main(String[] args) throws FileNotFoundException, URISyntaxException {

        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        URL input_ncml_url = classloader.getResource("test.ncml");
        Path path = Paths.get(input_ncml_url.toURI());
        File input_ncml = path.toFile();

        NetcdfDataset dataset = null;
        FileReader reader = new FileReader(input_ncml);

        try {
            dataset = NetcdfDatasets.openNcmlDataset(reader, null, null);
            Variable x = dataset.findVariable("variable_length_char");
            for (int i = 0; i < x.getSize(); i++) {
                System.out.println((int)x.read().getChar(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
<?xml version="1.0" encoding="UTF-8"?>
<netcdf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2  http://www.unidata.ucar.edu/schemas/netcdf/ncml-2.2.xsd" xmlns="http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2">
    <dimension name="num_fields" length="4" isUnlimited="false"/>
    <dimension name="max_len" length="4" isUnlimited="false"/>
    <variable name="variable_length_char" type="char" shape="num_fields max_len">
        <values>a bb ccc dddd</values>
    </variable>
</netcdf>

Relevant stack trace

java.lang.ArrayIndexOutOfBoundsException: Index 13 out of bounds for length 13
    at ucar.ma2.ArrayChar.getChar(ArrayChar.java:472)
    at ucar.ma2.IteratorFast.getCharNext(IteratorFast.java:150)
    at ucar.ma2.MAMath.copyChar(MAMath.java:318)
    at ucar.ma2.MAMath.copy(MAMath.java:191)
    at ucar.ma2.Array.copy(Array.java:657)
    at ucar.nc2.Variable._read(Variable.java:733)
    at ucar.nc2.dataset.VariableDS._read(VariableDS.java:430)
    at ucar.nc2.Variable.read(Variable.java:614)
    at ncml_test.Ncml_Test.main(Ncml_Test.java:34)

Relevant log messages

No response

If you have an example file that you can share, please attach it to this issue.

If so, may we include it in our test datasets to help ensure the bug does not return once fixed? Note: the test datasets are publicly accessible without restriction.

Yes

Code of Conduct