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

Error/Crash on nc_close when writing a "nested" NC_VLEN attribute #2041

Closed
krisfed opened this issue Jul 28, 2021 · 3 comments · Fixed by #2179
Closed

Error/Crash on nc_close when writing a "nested" NC_VLEN attribute #2041

krisfed opened this issue Jul 28, 2021 · 3 comments · Fixed by #2179

Comments

@krisfed
Copy link

krisfed commented Jul 28, 2021

I am running into problems when I try to write a "nested" NC_VLEN attribute (meaning there are two NC_VLEN types, and base type for one of them is the other NC_VLEN type). I seem to be able to write the same data as a variable without the same issues.

Here are simplistic reproduction steps:

#include <iostream>
#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;
    }
}

int main(int argc, const char * argv[]) {
    
    // Setup data
    const int DIM_LEN = 2;
    nc_vlen_t data[DIM_LEN];
    
    // first element in nested vlen
    const int first_nest_size = 2;
    nc_vlen_t first_nest[first_nest_size];

    const int first_size1 = 10;
    double first1[first_size1] = {2, 3, 5, 7, 11, 13, 17, 37, 79, 113};
    first_nest[0].p = first1;
    first_nest[0].len = first_size1;
    
    const int second_size1 = 5;
    double second1[second_size1] = {101, 121, 131, 141, 151};
    first_nest[1].p = second1;
    first_nest[1].len = second_size1;
    
    data[0].p = first_nest;
    data[0].len = first_nest_size;
    
    // second element in nested vlen
    const int second_nest_size = 1;
    nc_vlen_t second_nest[second_nest_size];

    const int first_size2 = 2;
    double first2[first_size2] = {55, 56};
    second_nest[0].p = first2;
    second_nest[0].len = first_size2;
    
    data[1].p = second_nest;
    data[1].len = second_nest_size;

    // Open file
    int ncid;
    int retval;
    
    retval = nc_create("nested_vlen_att.nc", NC_NETCDF4, &ncid);
    checkErrorCode(retval, "nc_create");
    
    // Define vlen type named MY_VLEN
    nc_type vlen_typeID;
    retval = nc_def_vlen(ncid, "MY_VLEN", NC_DOUBLE, &vlen_typeID);
    checkErrorCode(retval, "nc_def_vlen");
    
    // Define nested vlen type
    nc_type vlen_nested_typeID;
    retval = nc_def_vlen(ncid, "MY_NESTED_VLEN", vlen_typeID, &vlen_nested_typeID);
    checkErrorCode(retval, "nc_def_vlen (nested)");
    
    // Write vlen attribute
    retval = nc_put_att(ncid, NC_GLOBAL, "numbers_att", vlen_nested_typeID, DIM_LEN, data);
    checkErrorCode(retval, "nc_put_att");
    
//    // Write vlen variable
//    int dimid;
//    retval = nc_def_dim(ncid, "DIM", DIM_LEN, &dimid);
//    checkErrorCode(retval, "nc_def_dimid");
//    int varid;
//    retval = nc_def_var(ncid, "numbers_var", vlen_nested_typeID, 1, &dimid, &varid);
//    checkErrorCode(retval, "nc_def_var");
//    retval = nc_put_var(ncid, varid, data);
//    checkErrorCode(retval, "nc_put_var");
    
    retval = nc_close(ncid);
    checkErrorCode(retval, "nc_close");
    
    return retval;
}

Using netcdf-c version 4.7.4 on macOS 11.2.3 I sometimes get an error and sometimes a segfault:

$ ./a.out 
a.out(5539,0x101457e00) malloc: can't allocate region
:*** mach_vm_map(size=8893249870866587648, flags: 100) failed (error code=3)
a.out(5539,0x101457e00) malloc: *** set a breakpoint in malloc_error_break to debug
a.out(5539,0x101457e00) malloc: can't allocate region
:*** mach_vm_map(size=8893249870866587648, flags: 100) failed (error code=3)
a.out(5539,0x101457e00) malloc: *** set a breakpoint in malloc_error_break to debug
Error code: -107 from nc_close
NetCDF: Can't open HDF5 attribute

$ ./a.out 
Segmentation fault: 11

(I think segfault might be more likely to happen if I haven't deleted the nested_vlen_att.nc file, but it is not a clear pattern. It has happened after I have deleted the file too.)

On Debian 10, still with 4.7.4, I don't see an error (although I think I've seen the segfault sometimes). But ncdump shows that the attribute was not successfully written:

% ncdump nested_vlen_att.nc 
netcdf nested_vlen_att {
types:
  double(*) MY_VLEN ;
  MY_VLEN(*) MY_NESTED_VLEN ;

// global attributes:
		MY_NESTED_VLEN :numbers_att = {{2, 3, 5, 7, 11, 13, 17, 37, 79, 113}, {}}, {{}} ;
}

I couldn't find any documented limitations about this.. Is this a bug? Or is this a wrong way to created a "nested" NC_VLEN attribute?

@DennisHeimbigner
Copy link
Collaborator

The vlen handling code has a number of known errors. I will try to get to this
as soon as I can.

@krisfed
Copy link
Author

krisfed commented Aug 6, 2021

Thank you, Dennis!

Are the other known vlen issues already on github (or documented elsewhere)? I might have run into some of them too, and was planning to report them if I get clear repro steps...

@DennisHeimbigner
Copy link
Collaborator

They may be noted in the code. But you should add an issue for those you find
as a reminder to us.

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