Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Writing NC_VLEN attribute of NC_STRINGs can result in garbled values #2143

Closed
krisfed opened this issue Nov 12, 2021 · 8 comments · Fixed by #2179
Closed

Writing NC_VLEN attribute of NC_STRINGs can result in garbled values #2143

krisfed opened this issue Nov 12, 2021 · 8 comments · Fixed by #2179

Comments

@krisfed
Copy link

krisfed commented Nov 12, 2021

Hi all,

We are seeing a difference in writing behavior between variables and attributes of the "NC_VLEN of NC_STRINGs" type. Under some conditions, writing NC_VLEN attribute of NC_STRINGs can result in garbage values, while writing a similar variable under the same conditions seems to work fine.

As far as I can tell it has something to do with attributes needing NC_VLEN data to still be in memory by the time of the nc_close() call.

Here is some simplistic code that reproduces the issue. It uses the same code for writing a variable and for writing an attribute. The raw NC_VLEN data should be getting cleaned up by the time of nc_close() call (it is in a different scope):

#include <iostream>
#include <vector>
#include <string>
#include "netcdf.h"

void checkErrorCode(int status, const char* message){
    if (status != NC_NOERR){
        std::cout << "Error code: " << status << " from " << message << std::endl;
        std::cout << nc_strerror(status) << std::endl << std::endl;
    }
}


void writeVariable(const int dimlength, int ncid, nc_type vlen_typeID)
{
    // Setup data
    std::unique_ptr<nc_vlen_t[]> data(new nc_vlen_t[dimlength]);
    
    const int totalNumStrings = 13;
    std::string stringsInVLEN[totalNumStrings] = {"banana", "kiwi", "apple", "grape", "apple", "cherry", "lemon", "melon", "watermelon", "strawberry", "peach", "raspberry", "pineapple"};
    const char* charPointers[totalNumStrings];
    
    for (int i=0; i<totalNumStrings; i++){
        charPointers[i] = stringsInVLEN[i].c_str();
    }
    
    // create six variable length arrays of strings
    int stringIndex = 0;
    
    const int first_size = 2;
    data[0].len = first_size;
    data[0].p = charPointers+stringIndex;
    stringIndex += first_size;
    
    const int second_size = 1;
    data[1].len = second_size;
    data[1].p = charPointers+stringIndex;
    stringIndex += second_size;
    
    const int third_size = 5;
    data[2].len = third_size;
    data[2].p = charPointers+stringIndex;
    stringIndex += third_size;
    
    const int fourth_size = 3;
    data[3].len = fourth_size;
    data[3].p = charPointers+stringIndex;
    stringIndex += fourth_size;
    
    const int fifth_size = 0;
    data[4].len = fifth_size;
    data[4].p = charPointers+stringIndex;
    stringIndex += fifth_size;
    
    const int sixth_size = 2;
    data[5].len = sixth_size;
    data[5].p = charPointers+stringIndex;
    stringIndex += sixth_size;
    
        
    // Write vlen variable named Fruits
    
    // Define dimension
    int dimid;
    int retval = nc_def_dim(ncid, "D1", dimlength, &dimid);
    checkErrorCode(retval, "nc_def_dim");
    
    // Define variable
    int varid;
    retval = nc_def_var(ncid, "Fruits", vlen_typeID, 1, &dimid, &varid);
    checkErrorCode(retval, "nc_def_var");
    
    // Write variable
    retval = nc_put_var(ncid, varid, data.get());
    checkErrorCode(retval, "nc_put_var");
    
}

void writeAttribute(const int attlength, int ncid, nc_type vlen_typeID)
{
    // Setup data
    std::unique_ptr<nc_vlen_t[]> data(new nc_vlen_t[attlength]);
    
    const int totalNumStrings = 13;
    std::string stringsInVLEN[totalNumStrings] = {"banana", "kiwi", "apple", "grape", "apple", "cherry", "lemon", "melon", "watermelon", "strawberry", "peach", "raspberry", "pineapple"};
    const char* charPointers[totalNumStrings];
    
    for (int i=0; i<totalNumStrings; i++){
        charPointers[i] = stringsInVLEN[i].c_str();
    }
    
    // create six variable length arrays of strings
    int stringIndex = 0;
    
    const int first_size = 2;
    data[0].len = first_size;
    data[0].p = charPointers+stringIndex;
    stringIndex += first_size;
    
    const int second_size = 1;
    data[1].len = second_size;
    data[1].p = charPointers+stringIndex;
    stringIndex += second_size;
    
    const int third_size = 5;
    data[2].len = third_size;
    data[2].p = charPointers+stringIndex;
    stringIndex += third_size;
    
    const int fourth_size = 3;
    data[3].len = fourth_size;
    data[3].p = charPointers+stringIndex;
    stringIndex += fourth_size;
    
    const int fifth_size = 0;
    data[4].len = fifth_size;
    data[4].p = charPointers+stringIndex;
    stringIndex += fifth_size;
    
    const int sixth_size = 2;
    data[5].len = sixth_size;
    data[5].p = charPointers+stringIndex;
    stringIndex += sixth_size;
    
        
    // Write vlen attribute named Fruits
    int retval = nc_put_att(ncid, NC_GLOBAL, "Fruit", vlen_typeID, attlength, data.get());
    checkErrorCode(retval, "nc_put_att");
    
}

int main(int argc, const char * argv[]) {
    
    const int attlength = 6;

    // Open file
    int ncid;
    int retval;
    
    retval = nc_create("vlen_of_strings_att.nc", NC_NETCDF4, &ncid);
    checkErrorCode(retval, "nc_create");
    
    // Define vlen type named MY_VLEN_STRING
    nc_type vlen_typeID;
    retval = nc_def_vlen(ncid, "MY_VLEN_STRING", NC_STRING, &vlen_typeID);
    checkErrorCode(retval, "nc_def_vlen");
    
    // write variable - will be able to read it back fine
    writeVariable(attlength, ncid, vlen_typeID);
    
    // write attribute - will read back garbled values
    writeAttribute(attlength, ncid, vlen_typeID);
    
    retval = nc_close(ncid);
    checkErrorCode(retval, "nc_close");
    
    return retval;
}

Here is the results of running it. The error codes for all operations seem to be NC_NOERR (so it is a silent failure). You can see that ncdump reads the variable fine, but the attribute's data is garbled. We see the same when we try to read the attribute data with nc_get_att().

$ ./a.out 
$ ncdump vlen_of_strings_att.nc 
netcdf vlen_of_strings_att {
types:
  string(*) MY_VLEN_STRING ;
dimensions:
	D1 = 6 ;
variables:
	MY_VLEN_STRING Fruits(D1) ;

// global attributes:
		MY_VLEN_STRING :Fruit = {"banana", "\n?\002\001"}, {""}, 
    {"????\177", "apple", "????\177", "", "#?\002\001"}, 
    {"?\005??\177", "", "?\005??\177"}, {}, {"????\177", "?\005??\177"} ;
data:

 Fruits = {"banana", "kiwi"}, {"apple"}, 
    {"grape", "apple", "cherry", "lemon", "melon"}, 
    {"watermelon", "strawberry", "peach"}, {}, {"raspberry", "pineapple"} ;
}

We are using netcdf 4.8.1, and the above code was run on a mac (but we are seeing the same issue on other platforms).

Does this look like a bug? Is it a known issue?

@DennisHeimbigner
Copy link
Collaborator

Sadly the VLEN code needs substantial refactoring.
I just have not had time to revisit it.
As for needing to stay in memory, where did you see that. I think
it is supposed to copy.

@krisfed
Copy link
Author

krisfed commented Nov 12, 2021

Thanks for taking a look Dennis!

I just thought it might have to do with staying in memory because I did not see this issue in cases when nc_close() is in the same scope as the NC_VLEN data, or if data is created with "new", but "delete" is not called, and in similar cases where NC_VLEN data should still be in memory before the nc_close() call. So that was my best guess at what might be the reason behind this issue.

It also sounds like it could be a little related to the other NC_VLEN issue I reported earlier: #2041 , where there were errors/crashes on nc_close() when writing a "nested" NC_VLEN attribute. I know NC_VLEN of NC_STRINGs is kind of similar to a nested NC_VLEN (as NC_STRING is an NC_VLEN of NC_CHARs). So in both cases there is something special about nc_close() call when writing (nested-ish) NC_VLEN attributes.

@krisfed
Copy link
Author

krisfed commented Nov 17, 2021

Wanted to note that with writing some very large NC_VLENs of NC_STRINGs attributes, we also saw a crash on nc_close(). Additional similarity with that previously reported issue.

@DennisHeimbigner
Copy link
Collaborator

I did some more experimentation with this. I think your guess is mostly correct.
The attribute data is probably copied internally but it does not do a deep
copy. I think it does a shallow copy of the top level. This would explain why we do not
see this for vlens of the int types or enums. I would expect it for vlens of opaque, string,
some compounds and vlens of vlens.
I can hack together a fix; it is really important to you?

@krisfed
Copy link
Author

krisfed commented Jan 4, 2022

It would be really nice to have a fix in the next netcdf release, if possible!

@DennisHeimbigner
Copy link
Collaborator

I am working on the fix (actually the more general problem of reclaiming VLENS).
I am mostly done, except I have one very difficult problem I am trying to solve.
Attached is the proposed PR report that describes the changes.
vlenfix.txt

@krisfed
Copy link
Author

krisfed commented Jan 5, 2022

Thank you very much for working on this, Dennis!

If nc_free_vlen(s) are deprecated in favor of ncaux_reclaim_data, and if netcdf_aux.h file is being touched anyway, could "typeid" argument name for ncaux_end_compound be renamed to make it easier to compile with C++ (as I mentioned on #2078)?

@DennisHeimbigner
Copy link
Collaborator

Oops I forgot about typeid. I will make sure it is removed.

DennisHeimbigner added a commit to DennisHeimbigner/netcdf-c that referenced this issue Jan 9, 2022
re: Unidata#541
re: Unidata#1208
re: Unidata#2078
re: Unidata#2041
re: Unidata#2143

For a long time, there have been known problems with the
management of complex types containing VLENs.  This also
involves the string type because it is stored as a VLEN of
chars.

This PR (mostly) fixes this problem. But note that it adds new
functions to netcdf.h (see below) and this may require bumping
the .so number.  These new functions can be removed, if desired,
in favor of functions in netcdf_aux.h, but netcdf.h seems the
better place for them because they are intended as alternatives
to the nc_free_vlen and nc_free_string functions already in
netcdf.h.

The term complex type refers to any type that directly or
transitively references a VLEN type. So an array of VLENS, a
compound with a VLEN field, and so on.

In order to properly handle instances of these complex types, it
is necessary to have function that can recursively walk
instances of such types to perform various actions on them.  The
term "deep" is also used to mean recursive.

At the moment, the two operations needed by the netcdf library are:
* free'ing an instance of the complex type
* copying an instance of the complex type.

The current library does only shallow free and shallow copy of
complex types. This means that only the top level is properly
free'd or copied, but deep internal blocks in the instance are
not touched.

Note that the term "vector" will be used to mean a contiguous (in
memory) sequence of instances of some type. Given an array with,
say, dimensions 2 X 3 X 4, this will be stored in memory as a
vector of length 2*3*4=24 instances.

The use cases are primarily these.

## nc_get_vars
Suppose one is reading a vector of instances using nc_get_vars
(or nc_get_vara or nc_get_var, etc.).  These functions will
return the vector in the top-level memory provided.  All
interior blocks (form nested VLEN or strings) will have been
dynamically allocated.

After using this vector of instances, it is necessary to free
(aka reclaim) the dynamically allocated memory, otherwise a
memory leak occurs.  So, the recursive reclaim function is used
to walk the returned instance vector and do a deep reclaim of
the data.

Currently functions are defined in netcdf.h that are supposed to
handle this: nc_free_vlen(), nc_free_vlens(), and
nc_free_string().  Unfortunately, these functions only do a
shallow free, so deeply nested instances are not properly
handled by them.

Note that internally, the provided data is immediately written so
there is no need to copy it. But the caller may need to reclaim the
data it passed into the function.

## nc_put_att
Suppose one is writing a vector of instances as the data of an attribute
using, say, nc_put_att.

Internally, the incoming attribute data must be copied and stored
so that changes/reclamation of the input data will not affect
the attribute.

Again, the code inside the netcdf library does only shallow copying
rather than deep copy. As a result, one sees effects such as described
in Github Issue Unidata#2143.

Also, after defining the attribute, it may be necessary for the user
to free the data that was provided as input to nc_put_att().

## nc_get_att
Suppose one is reading a vector of instances as the data of an attribute
using, say, nc_get_att.

Internally, the existing attribute data must be copied and returned
to the caller, and the caller is responsible for reclaiming
the returned data.

Again, the code inside the netcdf library does only shallow copying
rather than deep copy. So this can lead to memory leaks and errors
because the deep data is shared between the library and the user.

# Solution

The solution is to build properly recursive reclaim and copy
functions and use those as needed.
These recursive functions are defined in libdispatch/dinstance.c
and their signatures are defined in include/netcdf.h.
For back compatibility, corresponding "ncaux_XXX" functions
are defined in include/netcdf_aux.h.
````
int nc_reclaim_data(int ncid, nc_type xtypeid, void* memory, size_t count);
int nc_reclaim_data_all(int ncid, nc_type xtypeid, void* memory, size_t count);
int nc_copy_data(int ncid, nc_type xtypeid, const void* memory, size_t count, void* copy);
int nc_copy_data_all(int ncid, nc_type xtypeid, const void* memory, size_t count, void** copyp);
````
There are two variants. The first two, nc_reclaim_data() and
nc_copy_data(), assume the top-level vector is managed by the
caller. For reclaim, this is so the user can use, for example, a
statically allocated vector. For copy, it assumes the user
provides the space into which the copy is stored.

The second two, nc_reclaim_data_all() and
nc_copy_data_all(), allows the functions to manage the
top-level.  So for nc_reclaim_data_all, the top level is
assumed to be dynamically allocated and will be free'd by
nc_reclaim_data_all().  The nc_copy_data_all() function
will allocate the top level and return a pointer to it to the
user. The user can later pass that pointer to
nc_reclaim_data_all() to reclaim the instance(s).

# Internal Changes
The netcdf-c library internals are changed to use the proper
reclaim and copy functions.  It turns out that the places where
these functions are needed is quite pervasive in the netcdf-c
library code.  Using these functions also allows some
simplification of the code since the stdata and vldata fields of
NC_ATT_INFO are no longer needed.  Currently this is commented
out using the SEPDATA \#define macro.  When any bugs are largely
fixed, all this code will be removed.

# Known Bugs

1. There is still one known failure that has not been solved.
   All the failures revolve around some variant of this .cdl file.
   The proximate cause of failure is the use of a VLEN FillValue.
````
        netcdf x {
        types:
          float(*) row_of_floats ;
        dimensions:
          m = 5 ;
        variables:
          row_of_floats ragged_array(m) ;
              row_of_floats ragged_array:_FillValue = {-999} ;
        data:
          ragged_array = {10, 11, 12, 13, 14}, {20, 21, 22, 23}, {30, 31, 32},
                         {40, 41}, _ ;
        }
````
When a solution is found, I will either add it to this PR or post a new PR.

# Related Changes

* Mark nc_free_vlen(s) as deprecated in favor of ncaux_reclaim_data.
* Remove the --enable-unfixed-memory-leaks option.
* Remove the NC_VLENS_NOTEST code that suppresses some vlen tests.
* Document this change in docs/internal.md
* Disable the tst_vlen_data test in ncdump/tst_nccopy4.sh.
* Mark types as fixed size or not (transitively) to optimize the reclaim
  and copy functions.

# Misc. Changes

* Make Doxygen process libdispatch/daux.c
* Make sure the NC_ATT_INFO_T.container field is set.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants