netcdf-c/ncdump/tst_vlen_data.c
Dennis Heimbigner 8b9253fef2 Fix various problem around VLEN's
re: https://github.com/Unidata/netcdf-c/issues/541
re: https://github.com/Unidata/netcdf-c/issues/1208
re: https://github.com/Unidata/netcdf-c/issues/2078
re: https://github.com/Unidata/netcdf-c/issues/2041
re: https://github.com/Unidata/netcdf-c/issues/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 https://github.com/Unidata/netcdf-c/issues/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.
2022-01-08 18:30:00 -07:00

177 lines
5.1 KiB
C

/* This is part of the netCDF package. Copyright 2018 University
Corporation for Atmospheric Research/Unidata See COPYRIGHT file for
conditions of use. See www.unidata.ucar.edu for more info.
Create a test file with a vlen type and vlen data for ncdump to read.
$Id: tst_vlen_data.c,v 1.12 2009/11/15 00:17:59 dmh Exp $
*/
/* WARNING: this test leaks memory.
The leak may be in HDF5.
*/
#include <nc_tests.h>
#include <stdlib.h>
#include <netcdf.h>
#include <netcdf_aux.h>
#include "err_macros.h"
#define FILE5_NAME "tst_vlen_data.nc"
#define TYPE5_NAME "row_of_floats"
#define TYPE5_TYPE NC_FLOAT
#define DIM5_NAME "m"
#define DIM5_LEN 5
#define VAR5_NAME "ragged_array"
#define VAR5_RANK 1
#define ATT5_NAME "_FillValue"
#define ATT5_LEN 1
#define NROWS 5
int
main(int argc, char **argv)
{
int ncid;
int dimid, varid;
nc_type typeid;
char name_in[NC_MAX_NAME+1];
nc_type base_typeid;
size_t base_size_in;
int class_in;
float value_in;
int i, j;
int var_dims[VAR5_RANK];
float **array; /* a ragged array */
nc_vlen_t ragged_data[DIM5_LEN];
float missing_value = -999.0;
nc_vlen_t missing_val;
nc_vlen_t val_in;
printf("\n*** Testing vlens.\n");
printf("*** creating vlen test file %s...", FILE5_NAME);
if (nc_create(FILE5_NAME, NC_CLOBBER | NC_NETCDF4, &ncid)) ERR;
/* Create a vlen type. */
if (nc_def_vlen(ncid, TYPE5_NAME, TYPE5_TYPE, &typeid)) ERR;
/* Declare a dimension for number of rows */
if (nc_def_dim(ncid, DIM5_NAME, DIM5_LEN, &dimid)) ERR;
/* Declare a variable of the vlen type */
var_dims[0] = dimid;
if (nc_def_var(ncid, VAR5_NAME, typeid, VAR5_RANK, var_dims, &varid)) ERR;
/* Create and write a variable attribute of the vlen type */
#if 0
/* In order to use ncaux_reclaim_data, all the interior nodes must have been alloc'd */
missing_val.p = (float*)malloc(sizeof(missing_value));
memcpy((void*)missing_val.p,&missing_value,sizeof(missing_value));
#else
missing_val.p = &missing_value;
#endif
missing_val.len = 1;
if (nc_put_att(ncid, varid, ATT5_NAME, typeid, ATT5_LEN, (void *) &missing_val)) ERR;
if (nc_enddef(ncid)) ERR;
#if 0
/* reclaim */
if(ncaux_reclaim_data(ncid,typeid,&missing_val,1)) ERR;
#endif
/* fill in pointers to data rows in preparation for writing */
array = (float **) malloc(NROWS * sizeof(float *));
if(array == NULL) ERR;
for (i = 0; i < NROWS; i++) {
int ncolumns = NROWS - i;
array[i] = (float *) malloc(ncolumns * sizeof(float));
if(array[i] == NULL) ERR;
for (j = 0; j < ncolumns; j++) {
array[i][j] = 10.0 * (i + 1) + j;
}
}
array[4][0] = missing_value; /* overwrite last row with missing for equality test */
for (i = 0; i < DIM5_LEN; i++) {
ragged_data[i].p = array[i];
ragged_data[i].len = NROWS - i;
}
/* Store data, writing all values of the ragged matrix in one call */
if(nc_put_var(ncid, varid, ragged_data)) ERR;
/* Write the file. */
if (nc_close(ncid)) ERR;
/* Check it out. */
/* Reopen the file. */
if (nc_open(FILE5_NAME, NC_NOWRITE, &ncid)) ERR;
/* Get info with the generic inquire for user-defined types */
if (nc_inq_user_type(ncid, typeid, name_in, &base_size_in, &base_typeid,
NULL, &class_in)) ERR;
if (strcmp(name_in, TYPE5_NAME) ||
base_size_in != sizeof(nc_vlen_t) ||
base_typeid != NC_FLOAT ||
class_in != NC_VLEN) ERR;
/* Get the same info with the vlen-specific inquire function */
if (nc_inq_vlen(ncid, typeid, name_in, &base_size_in, &base_typeid)) ERR;
if (strcmp(name_in, TYPE5_NAME) ||
base_size_in != sizeof(nc_vlen_t) ||
base_typeid != NC_FLOAT) ERR;
if (nc_inq_varid(ncid, VAR5_NAME, &varid)) ERR;
/* Read in attribute value and check it */
if (nc_get_att(ncid, varid, ATT5_NAME, &val_in)) ERR;
if (val_in.len != ATT5_LEN) ERR;
value_in = *(float *)val_in.p;
if (value_in != missing_value) ERR;
/* Free allocated space for attribute value when finished with it */
if (nc_free_vlen(&val_in)) ERR;
/* Read in each row, check its length and values */
for (i = 0; i < DIM5_LEN; i++) {
size_t index[VAR5_RANK];
float *fvals;
index[0] = i;
if (nc_get_var1(ncid, varid, index, (void *) &val_in)) ERR;
if (val_in.len != NROWS - i) ERR;
fvals = (float *)val_in.p;
for (j = 0; j < val_in.len; j++) {
if (fvals[j] != array[i][j] ) ERR;
}
if (nc_free_vlen(&val_in)) ERR;
}
/* Now read in all the rows at once, then check lengths and values */
{
nc_vlen_t vals_in[DIM5_LEN];
float *fvals;
size_t start[VAR5_RANK], count[VAR5_RANK];
start[0] = 0;
count[0] = NROWS;
if (nc_get_vara(ncid, varid, start, count, vals_in)) ERR;
for (i = 0; i < DIM5_LEN; i++) {
for (j = 0; j < vals_in[i].len; j++) {
fvals = (float *)vals_in[i].p;
if (fvals[j] != array[i][j] ) ERR;
}
if (nc_free_vlen(&vals_in[i])) ERR;
}
}
if (nc_close(ncid)) ERR;
/* Free space used for sample data. */
for (i = 0; i < NROWS; i++)
free(array[i]);
free(array);
SUMMARIZE_ERR;
FINAL_RESULTS;
}